Spaces:
Sleeping
Sleeping
final answer to display image
Browse files- tools/final_answer.py +44 -1
tools/final_answer.py
CHANGED
@@ -1,5 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from typing import Any, Optional
|
2 |
from smolagents.tools import Tool
|
|
|
|
|
|
|
3 |
|
4 |
class FinalAnswerTool(Tool):
|
5 |
name = "final_answer"
|
@@ -8,7 +26,32 @@ class FinalAnswerTool(Tool):
|
|
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
|
|
|
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
|
15 |
+
|
16 |
from typing import Any, Optional
|
17 |
from smolagents.tools import Tool
|
18 |
+
import base64
|
19 |
+
from pathlib import Path
|
20 |
+
import mimetypes
|
21 |
|
22 |
class FinalAnswerTool(Tool):
|
23 |
name = "final_answer"
|
|
|
26 |
output_type = "any"
|
27 |
|
28 |
def forward(self, answer: Any) -> Any:
|
29 |
+
# Check if the answer is an image path (specific to gradio temp directories)
|
30 |
+
if isinstance(answer, str) and '/tmp/gradio/' in answer:
|
31 |
+
try:
|
32 |
+
# Read the image file as binary
|
33 |
+
img_path = Path(answer)
|
34 |
+
if img_path.exists():
|
35 |
+
with open(img_path, 'rb') as img_file:
|
36 |
+
img_data = img_file.read()
|
37 |
+
|
38 |
+
# Determine the MIME type
|
39 |
+
mime_type = mimetypes.guess_type(answer)[0] or 'image/webp'
|
40 |
+
|
41 |
+
# Return both the original path and the image data
|
42 |
+
return {
|
43 |
+
"type": "image",
|
44 |
+
"path": answer,
|
45 |
+
"mime_type": mime_type,
|
46 |
+
"data": img_data
|
47 |
+
}
|
48 |
+
else:
|
49 |
+
return f"Image was generated but could not be accessed at: {answer}"
|
50 |
+
except Exception as e:
|
51 |
+
return f"Error processing image: {str(e)}"
|
52 |
+
|
53 |
+
# Return the original answer for non-image responses
|
54 |
return answer
|
55 |
|
56 |
def __init__(self, *args, **kwargs):
|
57 |
+
self.is_initialized = False
|