vfs_fetcher.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. import time
  5. import json
  6. from typing import List, Dict, Any, Optional
  7. from curl_cffi import requests
  8. from app.visa_free_config_fetchers.base_fetcher import BaseFetcher
  9. COUNTRY_INFO = {
  10. "ie": {"iso3": "irl", "name": "Ireland"},
  11. "irl": {"iso3": "irl", "name": "Ireland"},
  12. "gb": {"iso3": "gbr", "name": "United Kingdom"},
  13. "uk": {"iso3": "gb", "name": "United Kingdom"},
  14. "gbr": {"iso3": "gbr", "name": "United Kingdom"},
  15. "cn": {"iso3": "chn", "name": "China"},
  16. "chn": {"iso3": "chn", "name": "China"},
  17. "sg": {"iso3": "sgp", "name": "Singapore"},
  18. "sgp": {"iso3": "sgp", "name": "Singapore"},
  19. "au": {"iso3": "aus", "name": "Australia"},
  20. "aus": {"iso3": "aus", "name": "Australia"},
  21. "nl": {"iso3": "nld", "name": "Netherlands"},
  22. "nld": {"iso3": "nld", "name": "Netherlands"},
  23. "fr": {"iso3": "fra", "name": "France"},
  24. "fra": {"iso3": "fra", "name": "France"},
  25. "it": {"iso3": "ita", "name": "Italy"},
  26. "ita": {"iso3": "ita", "name": "Italy"},
  27. "at": {"iso3": "aut", "name": "Austria"},
  28. "aut": {"iso3": "aut", "name": "Austria"},
  29. "dk": {"iso3": "dnk", "name": "Denmark"},
  30. "dnk": {"iso3": "dnk", "name": "Denmark"},
  31. "fi": {"iso3": "fin", "name": "Finland"},
  32. "fin": {"iso3": "fin", "name": "Finland"},
  33. "hu": {"iso3": "hun", "name": "Hungary"},
  34. "hun": {"iso3": "hun", "name": "Hungary"},
  35. "is": {"iso3": "isl", "name": "Iceland"},
  36. "isl": {"iso3": "isl", "name": "Iceland"},
  37. "no": {"iso3": "nor", "name": "Norway"},
  38. "nor": {"iso3": "nor", "name": "Norway"},
  39. "es": {"iso3": "esp", "name": "Spain"},
  40. "esp": {"iso3": "esp", "name": "Spain"},
  41. "de": {"iso3": "deu", "name": "Germany"},
  42. "deu": {"iso3": "deu", "name": "Germany"},
  43. "gr": {"iso3": "grc", "name": "Greece"},
  44. "grc": {"iso3": "grc", "name": "Greece"},
  45. "be": {"iso3": "bel", "name": "Belgium"},
  46. "bel": {"iso3": "bel", "name": "Belgium"},
  47. "pl": {"iso3": "pol", "name": "Poland"},
  48. "pol": {"iso3": "pol", "name": "Poland"}
  49. }
  50. ISO2_TO_ISO3_API = {
  51. "gb": "gbr",
  52. "uk": "gbr",
  53. "cn": "chn",
  54. "ie": "irl",
  55. "sg": "sgp",
  56. "au": "aus",
  57. "nl": "nld",
  58. "fr": "fra",
  59. "it": "ita",
  60. "at": "aut",
  61. "dk": "dnk",
  62. "fi": "fin",
  63. "hu": "hun",
  64. "is": "isl",
  65. "no": "nor",
  66. "es": "esp",
  67. "de": "deu",
  68. "gr": "grc",
  69. "be": "bel",
  70. "pl": "pol"
  71. }
  72. def _select_candidate_with_llm(candidates: List[Dict[str, Any]], prompt_context: str) -> Dict[str, Any]:
  73. if not candidates:
  74. raise RuntimeError("Empty candidate list passed to LLM selection")
  75. if len(candidates) == 1:
  76. return candidates[0]
  77. api_key = os.environ.get("QWEN_API_KEY") or os.environ.get("DASHSCOPE_API_KEY") or "sk-893e895724c6403d81374e515ffaf427"
  78. url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
  79. formatted_candidates = "\n".join([f"{i}: {json.dumps(c, ensure_ascii=False)}" for i, c in enumerate(candidates)])
  80. prompt = (
  81. f"上下文要求:{prompt_context}\n"
  82. f"候选列表:\n{formatted_candidates}\n"
  83. f"请判断哪个候选最符合要求。仅输出该候选的索引数字(0-indexed),不要有任何其他文字。"
  84. )
  85. headers = {
  86. "Authorization": f"Bearer {api_key}",
  87. "Content-Type": "application/json"
  88. }
  89. payload = {
  90. "model": "qwen-plus",
  91. "messages": [
  92. {"role": "system", "content": "你是一个配置选择助手。按指令仅输出数字索引。"},
  93. {"role": "user", "content": prompt}
  94. ],
  95. "temperature": 0.0
  96. }
  97. try:
  98. resp = requests.post(url, headers=headers, json=payload, timeout=10)
  99. if resp.status_code == 200:
  100. content = resp.json()["choices"][0]["message"]["content"].strip()
  101. match = re.search(r"\d+", content)
  102. if match:
  103. idx = int(match.group())
  104. if 0 <= idx < len(candidates):
  105. return candidates[idx]
  106. except Exception as e:
  107. print(f"[WARN] LLM candidate selection failed: {e}")
  108. return candidates[0]
  109. def _vfs_get(url: str, headers: dict, retries: int = 2) -> requests.Response:
  110. for attempt in range(retries + 1):
  111. resp = requests.get(url, headers=headers, impersonate="chrome120", timeout=10)
  112. if resp.status_code == 200 or attempt == retries:
  113. return resp
  114. time.sleep(0.5)
  115. return resp
  116. class VFSFetcher(BaseFetcher):
  117. def __init__(self):
  118. super(VFSFetcher, self).__init__("vfs")
  119. def fetch_external_vac_info(self, origin: str, target: str, visa_type: str, vac_code: str) -> Dict[str, Any]:
  120. """
  121. Call external VFS master API using curl-cffi when vac_info is missing from metadata.
  122. Raises RuntimeError if data fetching or matching fails.
  123. """
  124. origin_clean = origin.lower().strip()
  125. target_clean = target.lower().strip()
  126. vac_clean = vac_code.lower().strip()
  127. visa_clean = visa_type.lower().strip()
  128. origin_info = COUNTRY_INFO.get(origin_clean, {"iso3": origin_clean})
  129. target_info = COUNTRY_INFO.get(target_clean, {"iso3": target_clean})
  130. origin_iso3 = origin_info["iso3"]
  131. target_iso3 = target_info["iso3"]
  132. origin_api_iso3 = ISO2_TO_ISO3_API.get(origin_iso3, origin_iso3)
  133. target_api_iso3 = ISO2_TO_ISO3_API.get(target_iso3, target_iso3)
  134. domain = "lift-apicn.vfsglobal.com" if origin_api_iso3 in ["chn", "cn"] else "lift-api.vfsglobal.com"
  135. headers = {
  136. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  137. "Accept": "application/json, text/plain, */*",
  138. "Accept-Language": "en-US,en;q=0.9",
  139. "route": f"{origin_api_iso3}/en/{target_api_iso3}",
  140. "origin": "https://visa.vfsglobal.com",
  141. "referer": "https://visa.vfsglobal.com/"
  142. }
  143. # 1. Fetch Centers
  144. url_center = f"https://{domain}/master/center/{target_api_iso3}/{origin_api_iso3}/en-US"
  145. try:
  146. resp_center = _vfs_get(url_center, headers=headers)
  147. if resp_center.status_code != 200:
  148. raise RuntimeError(f"VFS master center API returned HTTP {resp_center.status_code}")
  149. centers = resp_center.json()
  150. except Exception as e:
  151. raise RuntimeError(f"Failed to fetch VFS centers for {origin_api_iso3}->{target_api_iso3}: {e}")
  152. if not isinstance(centers, list) or not centers:
  153. raise RuntimeError(f"No centers returned for {origin_api_iso3}->{target_api_iso3}")
  154. # Match center candidate
  155. matched_centers = []
  156. for c in centers:
  157. iso_c = str(c.get("isoCode") or "").lower()
  158. vac_c = str(c.get("vacCode") or "").lower()
  159. name_c = str(c.get("centerName") or "").lower()
  160. city_c = str(c.get("city") or "").lower()
  161. if vac_clean in iso_c or vac_clean in vac_c or vac_clean in name_c or vac_clean in city_c:
  162. matched_centers.append(c)
  163. if not matched_centers:
  164. matched_centers = centers
  165. if len(matched_centers) == 1:
  166. selected_center = matched_centers[0]
  167. else:
  168. selected_center = _select_candidate_with_llm(
  169. matched_centers,
  170. f"选择办理 {origin_api_iso3} 到 {target_api_iso3} 的 VAC 签证中心,目标中心编号/城市: {vac_clean}"
  171. )
  172. vac_code_fetched = selected_center.get("isoCode") or selected_center.get("vacCode") or vac_code.upper()
  173. center_name_fetched = selected_center.get("centerName", "")
  174. address_fetched = selected_center.get("address", "")
  175. # 2. Fetch Visa Categories
  176. url_cat = f"https://{domain}/master/visacategory/{target_api_iso3}/{origin_api_iso3}/{vac_code_fetched}/en-US"
  177. try:
  178. resp_cat = _vfs_get(url_cat, headers=headers)
  179. if resp_cat.status_code != 200:
  180. raise RuntimeError(f"VFS visa category API returned HTTP {resp_cat.status_code}, resp_cat.text is {resp_cat.text}")
  181. categories = resp_cat.json()
  182. except Exception as e:
  183. raise RuntimeError(f"Failed to fetch VFS visa category for center {vac_code_fetched}: {e}")
  184. if not isinstance(categories, list) or not categories:
  185. raise RuntimeError(f"No visa categories returned for center {vac_code_fetched}")
  186. if len(categories) == 1:
  187. selected_cat = categories[0]
  188. else:
  189. matched_cats = [
  190. cat for cat in categories
  191. if visa_clean in str(cat.get("name", "")).lower() or visa_clean in str(cat.get("code", "")).lower()
  192. ]
  193. if len(matched_cats) == 1:
  194. selected_cat = matched_cats[0]
  195. elif len(matched_cats) > 1:
  196. selected_cat = _select_candidate_with_llm(
  197. matched_cats,
  198. f"选择符合签证类型 '{visa_clean}' 的 Visa Category 类别"
  199. )
  200. else:
  201. selected_cat = _select_candidate_with_llm(
  202. categories,
  203. f"选择符合签证类型 '{visa_clean}' 的 Visa Category 类别"
  204. )
  205. cat_code_fetched = selected_cat.get("visaCategoryCode") or selected_cat.get("code", "")
  206. cat_name_fetched = selected_cat.get("name", "")
  207. # 3. Fetch Visa Subcategories (Note: unauthenticated subvisacategory API may return HTTP 500 on VFS backend)
  208. url_sub = f"https://{domain}/master/subvisacategory/{target_api_iso3}/{origin_api_iso3}/{vac_code_fetched}/{cat_code_fetched}/en-US"
  209. subcat_code_fetched = "To"
  210. subcat_name_fetched = "Tourist"
  211. try:
  212. resp_sub = _vfs_get(url_sub, headers=headers)
  213. if resp_sub.status_code == 200 and isinstance(resp_sub.json(), list) and resp_sub.json():
  214. subcategories = resp_sub.json()
  215. if len(subcategories) == 1:
  216. selected_sub = subcategories[0]
  217. else:
  218. selected_sub = _select_candidate_with_llm(
  219. subcategories,
  220. f"选择符合签证类型 '{visa_clean}' 的 Subvisa Category 子类别"
  221. )
  222. subcat_code_fetched = selected_sub.get("subCategoryCode") or selected_sub.get("code", "To")
  223. subcat_name_fetched = selected_sub.get("subCategoryName") or selected_sub.get("name", "Tourist")
  224. except Exception as e:
  225. print(f"[INFO] Subvisacategory query unauthenticated fallback: {e}")
  226. return {
  227. "routing_key": f"slot.{vac_clean}.{target_clean}.{visa_clean}",
  228. "vac_code": vac_code_fetched,
  229. "center_name": center_name_fetched,
  230. "address": address_fetched,
  231. "category_code": cat_code_fetched,
  232. "category_name": cat_name_fetched,
  233. "subcategory_code": subcat_code_fetched,
  234. "subcategory_name": subcat_name_fetched
  235. }
  236. def fetch_free_config(self, origin, target, visa_type, vac_code=None):
  237. origin_clean = origin.lower().strip()
  238. target_clean = target.lower().strip()
  239. vac_clean = (vac_code or "").lower().strip()
  240. visa_clean = visa_type.lower().strip()
  241. origin_info = COUNTRY_INFO.get(origin_clean, {"iso3": origin_clean, "name": origin.capitalize()})
  242. target_info = COUNTRY_INFO.get(target_clean, {"iso3": target_clean, "name": target.capitalize()})
  243. free_config = {
  244. "mission_code": target_info["iso3"],
  245. "mission_name": target_info["name"],
  246. "country_code": origin_info["iso3"],
  247. "country_name": origin_info["name"],
  248. "culture_code": "en-US",
  249. "language": "en",
  250. "apt_configs": {}
  251. }
  252. vacs = self.metadata.get("vacs", {})
  253. vac_key = "{}_{}_{}_{}".format(origin_clean, target_clean, vac_clean, visa_clean)
  254. vac_info = vacs.get(vac_key, {})
  255. if not vac_info and vac_clean:
  256. for k, v in vacs.items():
  257. if k.startswith("{}_{}_{}".format(origin_clean, target_clean, vac_clean)):
  258. vac_info = v
  259. break
  260. # If vac_info NOT found in metadata, call external tool / API online!
  261. if not vac_info and vac_clean:
  262. vac_info = self.fetch_external_vac_info(origin_clean, target_clean, visa_clean, vac_clean)
  263. if vac_info or vac_clean:
  264. routing_key = vac_info.get("routing_key", "slot.{}.{}.{}".format(vac_clean, target_clean, visa_clean))
  265. free_config["apt_configs"][routing_key] = {
  266. "center_name": vac_info.get("center_name", ""),
  267. "address": vac_info.get("address", ""),
  268. "vac_code": vac_info.get("vac_code", ""),
  269. "category_name": vac_info.get("category_name", ""),
  270. "category_code": vac_info.get("category_code", ""),
  271. "subcategory_name": vac_info.get("subcategory_name", ""),
  272. "subcategory_code": vac_info.get("subcategory_code", "")
  273. }
  274. return free_config