File size: 11,926 Bytes
10e9b7d
83ed090
 
 
cbcef54
83ed090
 
10e9b7d
eccf8e4
3c4371f
83ed090
cbcef54
10e9b7d
e2b6467
 
3db6293
e80aab9
cbcef54
83ed090
cbcef54
e2b6467
83ed090
 
 
 
 
 
 
cbcef54
 
83ed090
 
 
 
 
 
 
e2b6467
83ed090
 
cbcef54
 
 
 
 
 
 
 
 
 
 
 
e2b6467
cbcef54
 
e2b6467
 
 
 
 
 
cbcef54
 
83ed090
 
31243f4
 
83ed090
cbcef54
 
83ed090
e2b6467
4021bf3
83ed090
 
 
 
 
cbcef54
 
 
 
83ed090
cbcef54
83ed090
cbcef54
e2b6467
cbcef54
 
83ed090
cbcef54
 
 
 
 
83ed090
cbcef54
e2b6467
cbcef54
 
83ed090
cbcef54
 
 
 
83ed090
cbcef54
83ed090
cbcef54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2b6467
 
cbcef54
83ed090
cbcef54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83ed090
cbcef54
83ed090
cbcef54
 
 
83ed090
 
 
 
 
 
e2b6467
83ed090
cbcef54
 
 
 
 
 
83ed090
cbcef54
83ed090
cbcef54
83ed090
cbcef54
83ed090
cbcef54
 
 
 
e80aab9
cbcef54
 
e80aab9
cbcef54
 
 
 
 
 
e80aab9
cbcef54
 
 
 
 
 
 
e80aab9
cbcef54
 
e80aab9
e2b6467
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import os
import re
import base64
import mimetypes
import subprocess
from pathlib import Path

import gradio as gr
import requests
import pandas as pd
from openai import OpenAI
from youtube_transcript_api import YouTubeTranscriptApi

print("BOOT: imports loaded", flush=True)

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4.1-mini")
TRANSCRIBE_MODEL = os.getenv("TRANSCRIBE_MODEL", "gpt-4o-mini-transcribe")
LLM_API_KEY = os.getenv("LLM_API_KEY", "")
TEST_MODE = os.getenv("TEST_MODE", "1") == "1"   # 1 = random-question, 0 = full evaluation


def to_data_url(file_path: str) -> str:
    mime, _ = mimetypes.guess_type(file_path)
    if not mime:
        mime = "application/octet-stream"
    with open(file_path, "rb") as f:
        encoded = base64.b64encode(f.read()).decode("utf-8")
    return f"data:{mime};base64,{encoded}"


def clean_final_answer(text: str) -> str:
    if not text:
        return ""
    text = text.strip()
    text = re.sub(r"^\s*(final answer|answer)\s*[:\-]\s*", "", text, flags=re.I)
    return text.strip().strip('"').strip("'")


def extract_youtube_id(text: str) -> str | None:
    patterns = [
        r"youtube\.com/watch\?v=([A-Za-z0-9_-]{11})",
        r"youtu\.be/([A-Za-z0-9_-]{11})",
    ]
    for pattern in patterns:
        m = re.search(pattern, text)
        if m:
            return m.group(1)
    return None


def answer_rules(question: str) -> str:
    return (
        "Return ONLY the final answer.\n"
        "Do not explain.\n"
        "Do not include reasoning.\n"
        "Do not say FINAL ANSWER.\n"
        "Match the required format exactly.\n"
        "If the question asks for a comma-separated list, return only that list.\n"
        "If it asks for sorted/alphabetical output, obey exactly.\n"
        f"\nQUESTION:\n{question}"
    )


class BasicAgent:
    def __init__(self):
        if not LLM_API_KEY:
            raise ValueError("Missing LLM_API_KEY secret.")
        self.client = OpenAI(api_key=LLM_API_KEY)
        self.api_url = DEFAULT_API_URL
        print(f"BOOT: agent initialized with model={MODEL_NAME}", flush=True)

    def download_task_file(self, task_id: str, file_name: str) -> str | None:
        if not file_name:
            return None
        url = f"{self.api_url}/files/{task_id}"
        r = requests.get(url, timeout=60)
        r.raise_for_status()
        suffix = Path(file_name).suffix
        local_path = f"/tmp/{task_id}{suffix}"
        with open(local_path, "wb") as f:
            f.write(r.content)
        return local_path

    def ask_plain(self, question: str, extra_context: str = "", image_path: str | None = None) -> str:
        content = [{"type": "input_text", "text": answer_rules(question) + "\n\n" + extra_context}]
        if image_path:
            content.append({"type": "input_image", "image_url": to_data_url(image_path)})

        response = self.client.responses.create(
            model=MODEL_NAME,
            input=[{"role": "user", "content": content}],
        )
        return clean_final_answer(response.output_text)

    def ask_web(self, question: str, extra_context: str = "") -> str:
        prompt = answer_rules(question)
        if extra_context:
            prompt += "\n\nCONTEXT:\n" + extra_context

        response = self.client.responses.create(
            model=MODEL_NAME,
            tools=[{"type": "web_search"}],
            input=prompt,
        )
        return clean_final_answer(response.output_text)

    def transcribe_audio(self, file_path: str) -> str:
        with open(file_path, "rb") as audio_file:
            transcript = self.client.audio.transcriptions.create(
                model=TRANSCRIBE_MODEL,
                file=audio_file,
            )
        return getattr(transcript, "text", "") or ""

    def get_youtube_transcript(self, question: str) -> str | None:
        video_id = extract_youtube_id(question)
        if not video_id:
            return None
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=["en"])
            return " ".join(chunk["text"] for chunk in transcript)
        except Exception as e:
            print(f"YouTube transcript failed: {e}", flush=True)
            return None

    def summarize_excel(self, file_path: str) -> str:
        blocks = []
        xls = pd.ExcelFile(file_path)
        for sheet_name in xls.sheet_names[:5]:
            df = pd.read_excel(file_path, sheet_name=sheet_name)
            blocks.append(f"SHEET: {sheet_name}")
            blocks.append("COLUMNS: " + ", ".join(map(str, df.columns.tolist())))
            blocks.append("ROWS:")
            blocks.append(df.to_csv(index=False))
            blocks.append("")
        return "\n".join(blocks)[:50000]

    def execute_python_file(self, file_path: str) -> str:
        result = subprocess.run(
            ["python", file_path],
            capture_output=True,
            text=True,
            timeout=30,
        )
        return f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"

    def read_text_file(self, file_path: str) -> str:
        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
            return f.read()

    def __call__(self, task: dict) -> str:
        task_id = task.get("task_id", "")
        question = task.get("question", "")
        file_name = task.get("file_name", "") or ""

        print(f"SOLVING task={task_id} file={file_name}", flush=True)

        yt_transcript = self.get_youtube_transcript(question)
        if yt_transcript:
            return self.ask_plain(
                question,
                extra_context=f"YOUTUBE TRANSCRIPT:\n{yt_transcript[:40000]}",
            )

        local_file = self.download_task_file(task_id, file_name) if file_name else None
        if local_file:
            ext = Path(local_file).suffix.lower()

            if ext in {".mp3", ".wav", ".m4a", ".mpeg", ".mp4", ".webm"}:
                transcript = self.transcribe_audio(local_file)
                return self.ask_plain(
                    question,
                    extra_context=f"AUDIO TRANSCRIPT:\n{transcript[:30000]}",
                )

            if ext in {".png", ".jpg", ".jpeg", ".webp"}:
                return self.ask_plain(question, image_path=local_file)

            if ext in {".xlsx", ".xls"}:
                sheet_dump = self.summarize_excel(local_file)
                return self.ask_plain(
                    question,
                    extra_context=f"SPREADSHEET CONTENT:\n{sheet_dump}",
                )

            if ext == ".py":
                code_text = self.read_text_file(local_file)
                exec_text = self.execute_python_file(local_file)
                return self.ask_plain(
                    question,
                    extra_context=f"PYTHON FILE:\n{code_text}\n\nEXECUTION RESULT:\n{exec_text}",
                )

            text_data = self.read_text_file(local_file)
            return self.ask_plain(question, extra_context=text_data[:40000])

        return self.ask_web(question)


def run_and_submit_all(profile: gr.OAuthProfile | None):
    space_id = os.getenv("SPACE_ID", "")

    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}", flush=True)
    else:
        print("User not logged in.", flush=True)
        return "Please login to Hugging Face first.", None

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Agent init error: {e}", flush=True)
        return f"Error initializing agent: {e}", None

    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

    try:
        if TEST_MODE:
            print("TEST_MODE=1 -> fetching /random-question", flush=True)
            response = requests.get(f"{api_url}/random-question", timeout=30)
            response.raise_for_status()
            questions_data = [response.json()]
        else:
            print("TEST_MODE=0 -> fetching /questions", flush=True)
            response = requests.get(questions_url, timeout=30)
            response.raise_for_status()
            questions_data = response.json()

        if not questions_data:
            return "No questions returned by API.", None

        print(f"Fetched {len(questions_data)} questions.", flush=True)
    except Exception as e:
        print(f"Question fetch error: {e}", flush=True)
        return f"Error fetching questions: {e}", None

    results_log = []
    answers_payload = []

    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")
        if not task_id or question_text is None:
            continue

        try:
            submitted_answer = agent(item)
            answers_payload.append({
                "task_id": task_id,
                "submitted_answer": submitted_answer
            })
            results_log.append({
                "Task ID": task_id,
                "Question": question_text,
                "File": item.get("file_name", ""),
                "Submitted Answer": submitted_answer
            })
        except Exception as e:
            print(f"Task error {task_id}: {e}", flush=True)
            results_log.append({
                "Task ID": task_id,
                "Question": question_text,
                "File": item.get("file_name", ""),
                "Submitted Answer": f"AGENT ERROR: {e}"
            })

    if TEST_MODE:
        return "Test mode finished. Check the answer table below before running full evaluation.", pd.DataFrame(results_log)

    if not answers_payload:
        return "Agent produced no answers.", pd.DataFrame(results_log)

    submission_data = {
        "username": username.strip(),
        "agent_code": agent_code,
        "answers": answers_payload
    }

    try:
        response = requests.post(submit_url, json=submission_data, timeout=120)
        response.raise_for_status()
        result_data = response.json()

        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        return final_status, pd.DataFrame(results_log)

    except requests.exceptions.HTTPError as e:
        detail = f"Server responded with status {e.response.status_code}."
        try:
            detail += f" Detail: {e.response.json()}"
        except Exception:
            detail += f" Response: {e.response.text[:500]}"
        return f"Submission failed: {detail}", pd.DataFrame(results_log)

    except Exception as e:
        return f"Submission failed: {e}", pd.DataFrame(results_log)


with gr.Blocks() as demo:
    gr.Markdown("# Basic Agent Evaluation Runner")
    gr.Markdown(
        """
        1. Login with Hugging Face.
        2. In TEST_MODE=1, this runs one random question only.
        3. Change TEST_MODE=0 for full evaluation and submission.
        """
    )

    gr.LoginButton()
    run_button = gr.Button("Run Evaluation & Submit All Answers")
    status_output = gr.Textbox(label="Run Status / Submission Result", lines=6, interactive=False)
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    run_button.click(
        fn=run_and_submit_all,
        outputs=[status_output, results_table]
    )

print("BOOT: gradio blocks created", flush=True)

if __name__ == "__main__":
    print("BOOT: launching gradio", flush=True)
    port = int(os.environ.get("PORT", "7860"))
    demo.launch(server_name="0.0.0.0", server_port=port, show_error=True)