Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,44 +4,51 @@ import os
|
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
-
# System prompt
|
| 11 |
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question.
|
| 12 |
-
Report your thoughts, and finish your answer with just the answer — no prefixes like "FINAL ANSWER
|
| 13 |
Your answer should be a number OR as few words as possible OR a comma-separated list of numbers and/or strings.
|
| 14 |
If you're asked for a number, don’t use commas or units like $ or %, unless specified.
|
| 15 |
If you're asked for a string, don’t use articles or abbreviations (e.g. for cities), and write digits in plain text unless told otherwise."""
|
| 16 |
|
| 17 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 18 |
|
| 19 |
-
#
|
|
|
|
|
|
|
|
|
|
| 20 |
class MyAgent:
|
| 21 |
def __init__(self):
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
|
| 43 |
# Main evaluation function
|
| 44 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 45 |
space_id = os.getenv("SPACE_ID")
|
| 46 |
|
| 47 |
if profile:
|
|
@@ -66,6 +73,30 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 66 |
except Exception as e:
|
| 67 |
return f"Error fetching questions: {e}", None
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
results_log = []
|
| 70 |
answers_payload = []
|
| 71 |
|
|
@@ -75,9 +106,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 75 |
if not task_id or question_text is None:
|
| 76 |
continue
|
| 77 |
try:
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
except Exception as e:
|
| 82 |
results_log.append({
|
| 83 |
"Task ID": task_id,
|
|
@@ -116,19 +152,26 @@ with gr.Blocks() as demo:
|
|
| 116 |
**Instructions:**
|
| 117 |
1. Clone this space and configure your Gemini API key.
|
| 118 |
2. Log in to Hugging Face.
|
| 119 |
-
3.
|
|
|
|
| 120 |
""")
|
| 121 |
|
| 122 |
gr.LoginButton()
|
|
|
|
|
|
|
|
|
|
| 123 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 124 |
status_output = gr.Textbox(label="Submission Result", lines=5, interactive=False)
|
| 125 |
results_table = gr.DataFrame(label="Results", wrap=True)
|
| 126 |
|
| 127 |
-
run_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
if __name__ == "__main__":
|
| 130 |
print("🔧 App starting...")
|
| 131 |
demo.launch(debug=True, share=False)
|
| 132 |
|
| 133 |
|
| 134 |
-
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import pandas as pd
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import base64
|
| 9 |
+
import io
|
| 10 |
|
| 11 |
+
import google.generativeai as genai
|
| 12 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 13 |
|
| 14 |
+
# System prompt used by the agent
|
| 15 |
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question.
|
| 16 |
+
Report your thoughts, and finish your answer with just the answer — no prefixes like \"FINAL ANSWER:\".
|
| 17 |
Your answer should be a number OR as few words as possible OR a comma-separated list of numbers and/or strings.
|
| 18 |
If you're asked for a number, don’t use commas or units like $ or %, unless specified.
|
| 19 |
If you're asked for a string, don’t use articles or abbreviations (e.g. for cities), and write digits in plain text unless told otherwise."""
|
| 20 |
|
| 21 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 22 |
|
| 23 |
+
# Load GEMINI_API_KEY from environment
|
| 24 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 25 |
+
|
| 26 |
+
# Agent wrapper
|
| 27 |
class MyAgent:
|
| 28 |
def __init__(self):
|
| 29 |
+
model = LiteLLMModel(model_id="gemini/gemini-1.5-flash", api_key=GEMINI_API_KEY)
|
| 30 |
+
self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)
|
| 31 |
+
|
| 32 |
+
def __call__(self, question: str, code: str | None = None, excel_df: pd.DataFrame | None = None, image: Image.Image | None = None) -> str:
|
| 33 |
+
if excel_df is not None:
|
| 34 |
+
preview = excel_df.head().to_csv(index=False)
|
| 35 |
+
context = f"This is a preview of the attached Excel sales data:\n\n{preview}"
|
| 36 |
+
prompt = f"{question}\n\n{context}"
|
| 37 |
+
return self.agent.run(prompt)
|
| 38 |
+
elif image is not None:
|
| 39 |
+
buffered = io.BytesIO()
|
| 40 |
+
image.save(buffered, format="JPEG")
|
| 41 |
+
img_b64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 42 |
+
prompt = f"{question}\n\nThis is the attached image (base64 JPEG):\n\n{img_b64}"
|
| 43 |
+
return self.agent.run(prompt)
|
| 44 |
+
elif code:
|
| 45 |
+
formatted = f"{question}\n\nThoughts: Let's analyze the attached code.\nCode:\n```py\n{code}\n```<end_code>"
|
| 46 |
+
return self.agent.run(formatted)
|
| 47 |
+
else:
|
| 48 |
+
return self.agent.run(question)
|
| 49 |
|
| 50 |
# Main evaluation function
|
| 51 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None, uploaded_code: list[gr.File] | None, uploaded_excel: list[gr.File] | None, uploaded_image: list[gr.File] | None):
|
| 52 |
space_id = os.getenv("SPACE_ID")
|
| 53 |
|
| 54 |
if profile:
|
|
|
|
| 73 |
except Exception as e:
|
| 74 |
return f"Error fetching questions: {e}", None
|
| 75 |
|
| 76 |
+
uploaded_code_str = ""
|
| 77 |
+
if uploaded_code:
|
| 78 |
+
try:
|
| 79 |
+
uploaded_file = uploaded_code[0]
|
| 80 |
+
uploaded_code_str = uploaded_file.read().decode("utf-8")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
uploaded_code_str = f"# Failed to load uploaded code: {e}"
|
| 83 |
+
|
| 84 |
+
uploaded_excel_df = None
|
| 85 |
+
if uploaded_excel:
|
| 86 |
+
try:
|
| 87 |
+
uploaded_excel_df = pd.read_excel(uploaded_excel[0].name)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Error reading Excel: {e}")
|
| 90 |
+
uploaded_excel_df = None
|
| 91 |
+
|
| 92 |
+
uploaded_image_obj = None
|
| 93 |
+
if uploaded_image:
|
| 94 |
+
try:
|
| 95 |
+
uploaded_image_obj = Image.open(uploaded_image[0].name)
|
| 96 |
+
except Exception as e:
|
| 97 |
+
print(f"Error loading image: {e}")
|
| 98 |
+
uploaded_image_obj = None
|
| 99 |
+
|
| 100 |
results_log = []
|
| 101 |
answers_payload = []
|
| 102 |
|
|
|
|
| 106 |
if not task_id or question_text is None:
|
| 107 |
continue
|
| 108 |
try:
|
| 109 |
+
answer = agent(
|
| 110 |
+
question_text,
|
| 111 |
+
uploaded_code_str if "code" in question_text.lower() else None,
|
| 112 |
+
uploaded_excel_df if "excel" in question_text.lower() or "spreadsheet" in question_text.lower() else None,
|
| 113 |
+
uploaded_image_obj if "image" in question_text.lower() or "photo" in question_text.lower() or "jpg" in question_text.lower() else None
|
| 114 |
+
)
|
| 115 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 116 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})
|
| 117 |
except Exception as e:
|
| 118 |
results_log.append({
|
| 119 |
"Task ID": task_id,
|
|
|
|
| 152 |
**Instructions:**
|
| 153 |
1. Clone this space and configure your Gemini API key.
|
| 154 |
2. Log in to Hugging Face.
|
| 155 |
+
3. Optionally upload Python code, Excel file, or image used by the questions.
|
| 156 |
+
4. Run your agent on evaluation tasks and submit answers.
|
| 157 |
""")
|
| 158 |
|
| 159 |
gr.LoginButton()
|
| 160 |
+
code_upload = gr.File(label="Upload Python code file", file_types=[".py"])
|
| 161 |
+
excel_upload = gr.File(label="Upload Excel file", file_types=[".xls", ".xlsx"])
|
| 162 |
+
image_upload = gr.File(label="Upload Image file", file_types=[".jpg", ".jpeg"])
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
status_output = gr.Textbox(label="Submission Result", lines=5, interactive=False)
|
| 165 |
results_table = gr.DataFrame(label="Results", wrap=True)
|
| 166 |
|
| 167 |
+
run_button.click(
|
| 168 |
+
fn=run_and_submit_all,
|
| 169 |
+
inputs=[gr.OAuthProfile(), code_upload, excel_upload, image_upload],
|
| 170 |
+
outputs=[status_output, results_table]
|
| 171 |
+
)
|
| 172 |
|
| 173 |
if __name__ == "__main__":
|
| 174 |
print("🔧 App starting...")
|
| 175 |
demo.launch(debug=True, share=False)
|
| 176 |
|
| 177 |
|
|
|