Update handler.py
Browse files- handler.py +36 -39
handler.py
CHANGED
@@ -1,12 +1,12 @@
|
|
1 |
-
from typing import Dict,
|
2 |
import torch
|
3 |
from transformers import LlavaNextProcessor, LlavaNextForConditionalGeneration, BitsAndBytesConfig
|
4 |
from PIL import Image
|
5 |
import requests
|
6 |
from io import BytesIO
|
7 |
-
import
|
8 |
|
9 |
-
class EndpointHandler
|
10 |
def __init__(self, path=""):
|
11 |
# Configuraci贸 de la quantitzaci贸
|
12 |
quantization_config = BitsAndBytesConfig(
|
@@ -23,29 +23,40 @@ class EndpointHandler():
|
|
23 |
device_map="auto"
|
24 |
)
|
25 |
|
26 |
-
def __call__(self, data: Dict[str, Any]) ->
|
|
|
|
|
|
|
27 |
inputs = data.get("inputs")
|
28 |
if not inputs:
|
29 |
-
|
|
|
30 |
|
31 |
image_url = inputs.get("url")
|
|
|
32 |
prompt = inputs.get("prompt")
|
33 |
-
|
34 |
-
if not
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
"
|
40 |
-
"
|
41 |
-
|
42 |
-
}
|
43 |
|
44 |
try:
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
if image.format == 'PNG':
|
|
|
49 |
image = image.convert('RGB')
|
50 |
buffer = BytesIO()
|
51 |
image.save(buffer, format="JPEG")
|
@@ -53,32 +64,18 @@ class EndpointHandler():
|
|
53 |
image = Image.open(buffer)
|
54 |
|
55 |
except Exception as e:
|
56 |
-
|
57 |
-
|
58 |
-
return debug_info
|
59 |
|
60 |
try:
|
|
|
61 |
inputs = self.processor(prompt, image, return_tensors="pt").to("cuda")
|
62 |
output = self.model.generate(**inputs, max_new_tokens=100)
|
63 |
result = self.processor.decode(output[0], skip_special_tokens=True)
|
64 |
-
|
65 |
-
|
66 |
-
sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)
|
67 |
-
return sorted_scores
|
68 |
|
69 |
except Exception as e:
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
def extract_scores(self, response):
|
75 |
-
scores = {}
|
76 |
-
result_part = response.split("[/INST]")[-1].strip()
|
77 |
-
pattern = re.compile(r'(\d+)\.\s*(.*?):\s*(\d+)')
|
78 |
-
matches = pattern.findall(result_part)
|
79 |
-
for match in matches:
|
80 |
-
category_number = int(match[0])
|
81 |
-
category_name = match[1].strip()
|
82 |
-
score = int(match[2])
|
83 |
-
scores[category_name] = score
|
84 |
-
return scores
|
|
|
1 |
+
from typing import Dict, Any
|
2 |
import torch
|
3 |
from transformers import LlavaNextProcessor, LlavaNextForConditionalGeneration, BitsAndBytesConfig
|
4 |
from PIL import Image
|
5 |
import requests
|
6 |
from io import BytesIO
|
7 |
+
import base64
|
8 |
|
9 |
+
class EndpointHandler:
|
10 |
def __init__(self, path=""):
|
11 |
# Configuraci贸 de la quantitzaci贸
|
12 |
quantization_config = BitsAndBytesConfig(
|
|
|
23 |
device_map="auto"
|
24 |
)
|
25 |
|
26 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
27 |
+
logs = []
|
28 |
+
logs.append("Iniciant processament de la petici贸.")
|
29 |
+
|
30 |
inputs = data.get("inputs")
|
31 |
if not inputs:
|
32 |
+
logs.append("Format d'entrada inv脿lid. Manca la clau 'inputs'.")
|
33 |
+
return {"error": "Invalid input format. 'inputs' key is missing.", "logs": logs}
|
34 |
|
35 |
image_url = inputs.get("url")
|
36 |
+
image_data = inputs.get("image_data")
|
37 |
prompt = inputs.get("prompt")
|
38 |
+
|
39 |
+
if not prompt:
|
40 |
+
logs.append("S'ha de proporcionar 'prompt' en 'inputs'.")
|
41 |
+
return {"error": "The 'prompt' must be provided in 'inputs'.", "logs": logs}
|
42 |
+
|
43 |
+
if not image_url and not image_data:
|
44 |
+
logs.append("S'ha de proporcionar 'url' o 'image_data' en 'inputs'.")
|
45 |
+
return {"error": "Either 'url' or 'image_data' must be provided in 'inputs'.", "logs": logs}
|
46 |
+
|
47 |
+
logs.append(f"Processant entrada: url={image_url}, image_data={'present' if image_data else 'absent'}, prompt={prompt}")
|
48 |
|
49 |
try:
|
50 |
+
if image_url:
|
51 |
+
logs.append(f"Carregant imatge des de URL: {image_url}")
|
52 |
+
response = requests.get(image_url, stream=True)
|
53 |
+
image = Image.open(response.raw)
|
54 |
+
elif image_data:
|
55 |
+
logs.append("Carregant imatge des de dades d'imatge en brut.")
|
56 |
+
image = Image.open(BytesIO(base64.b64decode(image_data)))
|
57 |
|
58 |
if image.format == 'PNG':
|
59 |
+
logs.append("Convertint imatge PNG a JPG.")
|
60 |
image = image.convert('RGB')
|
61 |
buffer = BytesIO()
|
62 |
image.save(buffer, format="JPEG")
|
|
|
64 |
image = Image.open(buffer)
|
65 |
|
66 |
except Exception as e:
|
67 |
+
logs.append(f"Error carregant imatge: {str(e)}")
|
68 |
+
return {"error": str(e), "logs": logs}
|
|
|
69 |
|
70 |
try:
|
71 |
+
logs.append("Processant imatge amb el model.")
|
72 |
inputs = self.processor(prompt, image, return_tensors="pt").to("cuda")
|
73 |
output = self.model.generate(**inputs, max_new_tokens=100)
|
74 |
result = self.processor.decode(output[0], skip_special_tokens=True)
|
75 |
+
logs.append("Processament complet.")
|
76 |
+
return {"input_prompt": prompt, "model_output": result, "logs": logs}
|
|
|
|
|
77 |
|
78 |
except Exception as e:
|
79 |
+
logs.append(f"Error processant el model: {str(e)}")
|
80 |
+
return {"error": str(e), "logs": logs}
|
81 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|