EugeneZhao commited on
Commit
85118da
·
verified ·
1 Parent(s): 2124871

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +106 -86
handler.py CHANGED
@@ -1,115 +1,135 @@
 
 
1
  import base64
 
2
  from io import BytesIO
3
 
4
  import requests
5
- import torch
6
  from PIL import Image
7
- from transformers import (
8
- AutoConfig,
9
- AutoProcessor,
10
- PretrainedConfig,
11
- Qwen2_5_VLForConditionalGeneration,
12
- )
13
 
14
  MODEL_ID = "ghost233lism/GeoAgent"
15
 
16
 
17
  class EndpointHandler:
18
  def __init__(self, path=""):
19
- dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
20
-
21
- # 关键修复:先读 config,再把 dict 子配置转成 PretrainedConfig
22
- config = AutoConfig.from_pretrained(
23
- MODEL_ID,
24
- trust_remote_code=True,
25
- )
26
-
27
- if hasattr(config, "text_config") and isinstance(config.text_config, dict):
28
- config.text_config = PretrainedConfig.from_dict(config.text_config)
29
-
30
- if hasattr(config, "vision_config") and isinstance(config.vision_config, dict):
31
- config.vision_config = PretrainedConfig.from_dict(config.vision_config)
32
-
33
- # 有些模型这里也可能是 dict,一并兜底
34
- if hasattr(config, "decoder_config") and isinstance(config.decoder_config, dict):
35
- config.decoder_config = PretrainedConfig.from_dict(config.decoder_config)
36
-
37
- self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
38
- MODEL_ID,
39
- config=config,
40
- torch_dtype=dtype,
41
- device_map="auto",
42
- trust_remote_code=True,
43
- low_cpu_mem_usage=True,
44
  )
45
-
46
- self.processor = AutoProcessor.from_pretrained(
47
- MODEL_ID,
48
- trust_remote_code=True,
49
  )
50
 
51
- def _load_image(self, image_ref):
52
- if image_ref is None:
53
- raise ValueError("Please provide `inputs.image_url` or `inputs.image_base64`.")
54
-
55
- if isinstance(image_ref, str) and image_ref.startswith("http"):
56
- resp = requests.get(image_ref, timeout=30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  resp.raise_for_status()
58
- return Image.open(BytesIO(resp.content)).convert("RGB")
59
-
60
- if isinstance(image_ref, str) and image_ref.startswith("data:image"):
61
- _, b64data = image_ref.split(",", 1)
62
- return Image.open(BytesIO(base64.b64decode(b64data))).convert("RGB")
 
 
63
 
64
- return Image.open(image_ref).convert("RGB")
 
 
 
65
 
66
  def __call__(self, data):
67
  payload = data.get("inputs", {}) or {}
68
 
69
- prompt = payload.get("prompt", "Please analyze this image and infer its location.")
70
  image_url = payload.get("image_url")
71
  image_base64 = payload.get("image_base64")
72
- max_new_tokens = int(payload.get("max_new_tokens", 256))
73
-
74
- image = self._load_image(image_url or image_base64)
75
-
76
- messages = [
77
- {
78
- "role": "user",
79
- "content": [
80
- {"type": "image"},
81
- {"type": "text", "text": prompt},
82
- ],
83
- }
84
- ]
85
-
86
- text = self.processor.apply_chat_template(
87
- messages,
88
- tokenize=False,
89
- add_generation_prompt=True,
90
  )
 
91
 
92
- model_inputs = self.processor(
93
- text=[text],
94
- images=[image],
95
- return_tensors="pt",
96
- ).to(self.model.device)
97
 
98
- with torch.no_grad():
99
- output_ids = self.model.generate(
100
- **model_inputs,
101
- max_new_tokens=max_new_tokens,
 
 
 
 
 
102
  )
103
 
104
- generated_ids = [
105
- out_ids[len(in_ids):]
106
- for in_ids, out_ids in zip(model_inputs.input_ids, output_ids)
107
- ]
108
 
109
- output_text = self.processor.batch_decode(
110
- generated_ids,
111
- skip_special_tokens=True,
112
- clean_up_tokenization_spaces=True,
113
- )[0]
114
 
115
- return {"generated_text": output_text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
  import base64
4
+ import tempfile
5
  from io import BytesIO
6
 
7
  import requests
 
8
  from PIL import Image
9
+ from swift.llm import PtEngine, RequestConfig, get_model_tokenizer, get_template, InferRequest
10
+
 
 
 
 
11
 
12
  MODEL_ID = "ghost233lism/GeoAgent"
13
 
14
 
15
  class EndpointHandler:
16
  def __init__(self, path=""):
17
+ self.model_path = MODEL_ID
18
+ self.max_new_tokens = 2048
19
+ self.engine = None
20
+ self.template = None
21
+ self._load_model()
22
+
23
+ def _load_model(self):
24
+ model, tokenizer = get_model_tokenizer(self.model_path, model_type="qwen2_5_vl")
25
+ template_type = model.model_meta.template
26
+ self.template = get_template(
27
+ template_type,
28
+ tokenizer,
29
+ default_system=self._system_prompt(),
 
 
 
 
 
 
 
 
 
 
 
 
30
  )
31
+ self.engine = PtEngine.from_model_template(
32
+ model,
33
+ self.template,
34
+ max_batch_size=1,
35
  )
36
 
37
+ @staticmethod
38
+ def _system_prompt():
39
+ return """You are an expert with rich experience in the field of geolocation, skilled at accurately locating the geographic location of images through various clues in the images, such as traffic signs, architectural styles, natural landscapes, etc. At the same time, you are also a mentor in building the chain of thought, able to organize complex ideas into clear and standardized patterns.
40
+ You possess knowledge in multiple disciplines such as geography, cartography, transportation, and architecture, and are able to identify the characteristics of different countries, regions, and locations. At the same time, you have the ability to analyze logic and construct a chain of thought. Task: Output the thought chain and final answer based on the image input by the user. The thought chain includes:
41
+ Country Identification/Regional Guess/Precise Localization.
42
+
43
+ Possible clues include: National clues: (Example: traffic sign shape/color, language and text, driving direction, architectural style, vegetation and climate characteristics, etc.)
44
+
45
+ Regional clues: (logo/enterprise, topography, vegetation type, regional traffic signs, dialect/spelling, license plate style, area code/postal code, infrastructure features, etc.)
46
+ Accurate positioning: (road sign text, street name, house number, landmark building, river and lake water system, place attributes such as park/city/commercial district, shop name and storefront, etc.)
47
+
48
+ Do not output objects that do not exist in the image.
49
+
50
+ Output strictly in JSON format:
51
+ {
52
+ "ChainOfThought": {
53
+ "CountryIdentification": {
54
+ "Clues": [],
55
+ "Reasoning": "",
56
+ "Conclusion": "",
57
+ "Uncertainty": ""
58
+ },
59
+ "RegionalGuess": {
60
+ "Clues": [],
61
+ "Reasoning": "",
62
+ "Conclusion": "",
63
+ "Uncertainty": ""
64
+ },
65
+ "PreciseLocalization": {
66
+ "Clues": [],
67
+ "Reasoning": "",
68
+ "Conclusion": "",
69
+ "Uncertainty": ""
70
+ }
71
+ },
72
+ "FinalAnswer": "Country; Region; Specific Location"
73
+ }"""
74
+
75
+ def _save_temp_image(self, image_url=None, image_base64=None):
76
+ if image_url:
77
+ resp = requests.get(image_url, timeout=30)
78
  resp.raise_for_status()
79
+ img = Image.open(BytesIO(resp.content)).convert("RGB")
80
+ elif image_base64:
81
+ if image_base64.startswith("data:image"):
82
+ _, image_base64 = image_base64.split(",", 1)
83
+ img = Image.open(BytesIO(base64.b64decode(image_base64))).convert("RGB")
84
+ else:
85
+ raise ValueError("Please provide `inputs.image_url` or `inputs.image_base64`.")
86
 
87
+ tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
88
+ img.save(tmp.name, format="JPEG")
89
+ tmp.close()
90
+ return tmp.name
91
 
92
  def __call__(self, data):
93
  payload = data.get("inputs", {}) or {}
94
 
 
95
  image_url = payload.get("image_url")
96
  image_base64 = payload.get("image_base64")
97
+ prompt = payload.get(
98
+ "prompt",
99
+ "Based on the image, tell me the specific location and your thinking process",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  )
101
+ max_new_tokens = int(payload.get("max_new_tokens", self.max_new_tokens))
102
 
103
+ image_path = self._save_temp_image(image_url=image_url, image_base64=image_base64)
 
 
 
 
104
 
105
+ try:
106
+ infer_request = InferRequest(
107
+ messages=[
108
+ {
109
+ "role": "user",
110
+ "content": f"<image>{prompt}",
111
+ }
112
+ ],
113
+ images=[image_path],
114
  )
115
 
116
+ request_config = RequestConfig(max_tokens=max_new_tokens)
 
 
 
117
 
118
+ resp = self.engine.infer([infer_request], request_config=request_config)
119
+ result = resp[0]
 
 
 
120
 
121
+ text = ""
122
+ if hasattr(result, "choices") and result.choices:
123
+ choice = result.choices[0]
124
+ if hasattr(choice, "message") and hasattr(choice.message, "content"):
125
+ text = choice.message.content
126
+ elif hasattr(choice, "text"):
127
+ text = choice.text
128
+
129
+ return {
130
+ "generated_text": text,
131
+ "raw_response": str(result),
132
+ }
133
+ finally:
134
+ if os.path.exists(image_path):
135
+ os.remove(image_path)