STARX33 commited on
Commit
0c05b5e
·
verified ·
1 Parent(s): 72b3523

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -30
app.py CHANGED
@@ -5,61 +5,67 @@ import pandas as pd
5
  from datetime import datetime
6
  from typing import Optional
7
  from smolagents import CodeAgent, HfApiModel, tool
 
 
 
8
 
9
  # === Tool 1: Current Time Tool ===
10
  @tool
11
  def get_current_time_in_timezone(timezone: Optional[str] = None) -> str:
12
- """
13
- Returns the current time. If a timezone is provided, it is noted in the message.
14
- Args:
15
- timezone: An optional timezone name or location.
16
- Returns:
17
- A string with the current time.
18
- """
19
  now = datetime.utcnow()
20
  if timezone:
21
  return f"The current time in {timezone} is approximately {now.strftime('%Y-%m-%d %H:%M:%S')} UTC."
22
- return f"The current UTC time is {now.strftime('%Y-%m-%d %H:%M:%S')}."
23
 
24
  # === Tool 2: CSV Parsing Tool ===
25
  @tool
26
  def parse_csv(file_path: str) -> str:
27
- """
28
- Parses a CSV file and returns the first few rows.
29
- Args:
30
- file_path: Path to the CSV file to be parsed.
31
- Returns:
32
- A preview of the first rows.
33
- """
34
  df = pd.read_csv(file_path)
35
  return df.head(5).to_string(index=False)
36
 
37
  # === Tool 3: Audio Transcription Tool ===
38
  @tool
39
  def transcribe_audio(audio_path: str) -> str:
40
- """
41
- Transcribes spoken words in an audio file.
42
- Args:
43
- audio_path: Path to the .mp3 or .wav file.
44
- Returns:
45
- A transcription of the audio.
46
- """
47
  import whisper
48
  model = whisper.load_model("base")
49
  result = model.transcribe(audio_path)
50
  return result.get("text", "No transcription result.")
51
 
52
- # === Constants ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
54
 
55
- # === Agent Definition ===
56
  class BasicAgent:
57
  def __init__(self):
58
  model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
59
  self.agent = CodeAgent(
60
  model=model,
61
- tools=[get_current_time_in_timezone, parse_csv, transcribe_audio],
62
- add_base_tools=True, # Includes vision and web search
63
  max_steps=6,
64
  name="EvalAgent",
65
  description="Certification agent using vision, search, time, audio, and csv tools"
@@ -69,12 +75,10 @@ class BasicAgent:
69
  def __call__(self, question: str) -> str:
70
  response = self.agent.run(question)
71
  if "Final Answer:" not in response:
72
- # Add fallback final answer if missing
73
  last_line = response.strip().split("\n")[-1]
74
  response += f"\nFinal Answer: {last_line}"
75
  return response
76
 
77
- # === Evaluation Logic ===
78
  def run_and_submit_all(profile: gr.OAuthProfile | None):
79
  space_id = os.getenv("SPACE_ID")
80
 
@@ -146,13 +150,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
146
  f"Overall Score: {result_data.get('score', 'N/A')}% "
147
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
148
  f"Message: {result_data.get('message', 'No message received.')}"
149
-
150
  )
151
  return final_status, pd.DataFrame(results_log)
152
  except Exception as e:
153
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
154
 
155
- # === Gradio UI ===
156
  with gr.Blocks() as demo:
157
  gr.Markdown("# Basic Agent Evaluation Runner")
158
  gr.Markdown("""
 
5
  from datetime import datetime
6
  from typing import Optional
7
  from smolagents import CodeAgent, HfApiModel, tool
8
+ from duckduckgo_search import DDGS
9
+ from PIL import Image
10
+ import markdownify
11
 
12
  # === Tool 1: Current Time Tool ===
13
  @tool
14
  def get_current_time_in_timezone(timezone: Optional[str] = None) -> str:
 
 
 
 
 
 
 
15
  now = datetime.utcnow()
16
  if timezone:
17
  return f"The current time in {timezone} is approximately {now.strftime('%Y-%m-%d %H:%M:%S')} UTC."
18
+ return f"The current UTC time is {now.strftime('%Y-%m-%d %H:%M:%S')}"
19
 
20
  # === Tool 2: CSV Parsing Tool ===
21
  @tool
22
  def parse_csv(file_path: str) -> str:
 
 
 
 
 
 
 
23
  df = pd.read_csv(file_path)
24
  return df.head(5).to_string(index=False)
25
 
26
  # === Tool 3: Audio Transcription Tool ===
27
  @tool
28
  def transcribe_audio(audio_path: str) -> str:
 
 
 
 
 
 
 
29
  import whisper
30
  model = whisper.load_model("base")
31
  result = model.transcribe(audio_path)
32
  return result.get("text", "No transcription result.")
33
 
34
+ # === Tool 4: Web Search Tool ===
35
+ @tool
36
+ def duckduckgo_search(query: str) -> str:
37
+ results = []
38
+ with DDGS() as ddgs:
39
+ for r in ddgs.text(query):
40
+ results.append(f"{r['title']} - {r['href']}")
41
+ if len(results) >= 3:
42
+ break
43
+ return "\n".join(results) if results else "No results found."
44
+
45
+ # === Tool 5: Image Captioning Tool ===
46
+ @tool
47
+ def describe_image_with_blip(image_path: str) -> str:
48
+ from transformers import BlipProcessor, BlipForConditionalGeneration
49
+ import torch
50
+
51
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
52
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
53
+
54
+ raw_image = Image.open(image_path).convert('RGB')
55
+ inputs = processor(raw_image, return_tensors="pt")
56
+ out = model.generate(**inputs)
57
+ caption = processor.decode(out[0], skip_special_tokens=True)
58
+ return caption
59
+
60
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
61
 
 
62
  class BasicAgent:
63
  def __init__(self):
64
  model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
65
  self.agent = CodeAgent(
66
  model=model,
67
+ tools=[get_current_time_in_timezone, parse_csv, transcribe_audio, duckduckgo_search, describe_image_with_blip],
68
+ add_base_tools=False,
69
  max_steps=6,
70
  name="EvalAgent",
71
  description="Certification agent using vision, search, time, audio, and csv tools"
 
75
  def __call__(self, question: str) -> str:
76
  response = self.agent.run(question)
77
  if "Final Answer:" not in response:
 
78
  last_line = response.strip().split("\n")[-1]
79
  response += f"\nFinal Answer: {last_line}"
80
  return response
81
 
 
82
  def run_and_submit_all(profile: gr.OAuthProfile | None):
83
  space_id = os.getenv("SPACE_ID")
84
 
 
150
  f"Overall Score: {result_data.get('score', 'N/A')}% "
151
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
152
  f"Message: {result_data.get('message', 'No message received.')}"
 
153
  )
154
  return final_status, pd.DataFrame(results_log)
155
  except Exception as e:
156
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
157
 
 
158
  with gr.Blocks() as demo:
159
  gr.Markdown("# Basic Agent Evaluation Runner")
160
  gr.Markdown("""