Spaces:
Sleeping
Sleeping
Update tools/final_answer.py
Browse files- tools/final_answer.py +9 -49
tools/final_answer.py
CHANGED
|
@@ -1,54 +1,14 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
from typing import Optional, Union, Tuple
|
| 4 |
-
from PIL import Image
|
| 5 |
-
from smolagents import Tool
|
| 6 |
|
| 7 |
class FinalAnswerTool(Tool):
|
| 8 |
name = "final_answer"
|
| 9 |
-
description = "Provides a final answer
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
'image_path': {'type': 'string', 'description': 'Path to a generated image file', 'nullable': True}
|
| 14 |
-
}
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def forward(
|
| 19 |
-
self,
|
| 20 |
-
text: Optional[str] = None,
|
| 21 |
-
image_path: Optional[str] = None
|
| 22 |
-
) -> Union[str, Image.Image, Tuple[Image.Image, str]]:
|
| 23 |
-
|
| 24 |
-
if image_path and os.path.exists(image_path):
|
| 25 |
-
# Convert .webp to .png (since some frontends don't support webp well)
|
| 26 |
-
if image_path.lower().endswith(".webp"):
|
| 27 |
-
try:
|
| 28 |
-
img = Image.open(image_path).convert("RGB")
|
| 29 |
-
temp_dir = os.path.dirname(image_path) or "/tmp"
|
| 30 |
-
os.makedirs(temp_dir, exist_ok=True)
|
| 31 |
-
|
| 32 |
-
base_name = os.path.basename(image_path)
|
| 33 |
-
name_without_ext = os.path.splitext(base_name)[0]
|
| 34 |
-
temp_png_path = os.path.join(
|
| 35 |
-
temp_dir,
|
| 36 |
-
f"{name_without_ext}_{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}.png"
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
img.save(temp_png_path, "PNG")
|
| 40 |
-
image_path = temp_png_path
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"[ERROR] Failed to convert image {image_path}: {e}")
|
| 43 |
-
|
| 44 |
-
img = Image.open(image_path)
|
| 45 |
-
|
| 46 |
-
if text:
|
| 47 |
-
# Return tuple if both text + image
|
| 48 |
-
return (img, text)
|
| 49 |
-
else:
|
| 50 |
-
# Return only image
|
| 51 |
-
return img
|
| 52 |
-
|
| 53 |
-
# Only text case
|
| 54 |
-
return text
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
class FinalAnswerTool(Tool):
|
| 5 |
name = "final_answer"
|
| 6 |
+
description = "Provides a final answer to the given problem."
|
| 7 |
+
inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
|
| 8 |
+
output_type = "any"
|
| 9 |
|
| 10 |
+
def forward(self, answer: Any) -> Any:
|
| 11 |
+
return answer
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
def __init__(self, *args, **kwargs):
|
| 14 |
+
self.is_initialized = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|