erdikent commited on
Commit
0ff6376
ยท
verified ยท
1 Parent(s): 0b65a3d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -98
app.py CHANGED
@@ -1,107 +1,82 @@
1
 
2
-
3
- import os
4
  import gradio as gr
 
 
 
5
  import requests
6
- import pandas as pd
7
-
8
-
9
-
10
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
-
12
-
13
- class SmartAgent:
14
- def __init__(self):
15
- self.agent = HfAgent("https://api-inference.huggingface.co/chat/agent")
16
- print("SmartAgent initialized with Hugging Face tools.")
17
-
18
- def __call__(self, question: str) -> str:
19
- print(f"[SmartAgent] Received question: {question[:100]}")
20
- try:
21
- result = self.agent.run(question)
22
- print(f"[SmartAgent] Agent result: {result}")
23
- return str(result)
24
- except Exception as e:
25
- print(f"[SmartAgent] Error: {e}")
26
- return f"Agent error: {e}"
27
-
28
-
29
- def run_and_submit_all(profile: gr.OAuthProfile | None):
30
- space_id = os.getenv("SPACE_ID")
31
- if profile:
32
- username = f"{profile.username}"
33
- else:
34
- return "Please Login to Hugging Face with the button.", None
35
-
36
- api_url = DEFAULT_API_URL
37
- questions_url = f"{api_url}/questions"
38
- submit_url = f"{api_url}/submit"
39
-
40
- try:
41
- agent = SmartAgent()
42
- except Exception as e:
43
- return f"Error initializing agent: {e}", None
44
-
45
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
46
-
47
- try:
48
- response = requests.get(questions_url, timeout=15)
49
- response.raise_for_status()
50
- questions_data = response.json()
51
- except Exception as e:
52
- return f"Error fetching questions: {e}", None
53
-
54
- results_log = []
55
- answers_payload = []
56
- for item in questions_data:
57
- task_id = item.get("task_id")
58
- question_text = item.get("question")
59
- if not task_id or question_text is None:
60
- continue
61
- try:
62
- submitted_answer = agent(question_text)
63
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
64
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
65
- except Exception as e:
66
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
67
-
68
- submission_data = {
69
- "username": username.strip(),
70
- "agent_code": agent_code,
71
- "answers": answers_payload
72
- }
73
-
74
  try:
75
- response = requests.post(submit_url, json=submission_data, timeout=60)
76
- response.raise_for_status()
77
- result_data = response.json()
78
- final_status = (
79
- f"Submission Successful!\n"
80
- f"User: {result_data.get('username')}\n"
81
- f"Score: {result_data.get('score', 'N/A')}%\n"
82
- f"Correct: {result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')}\n"
83
- f"Message: {result_data.get('message', 'No message received.')}"
84
- )
85
- return final_status, pd.DataFrame(results_log)
86
  except Exception as e:
87
- return f"Submission failed: {e}", pd.DataFrame(results_log)
88
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  with gr.Blocks() as demo:
90
- gr.Markdown("# Smart AI Agent (Web, Image, Video, and QA Support)")
91
- gr.Markdown("""
92
- This agent can:
93
- - Answer complex questions
94
- - Perform web searches
95
- - Explain images or videos from URLs
 
96
 
97
- Please login and run the evaluation to test the agent.
98
- """)
99
- gr.LoginButton()
100
- run_button = gr.Button("Run Evaluation & Submit All Answers")
101
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
102
- results_table = gr.DataFrame(label="Questions and Agent Answers")
103
 
104
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
105
 
106
- if __name__ == "__main__":
107
- demo.launch(debug=True, share=False)
 
1
 
 
 
2
  import gradio as gr
3
+ from duckduckgo_search import DDGS
4
+ from transformers import pipeline
5
+ from PIL import Image
6
  import requests
7
+ from bs4 import BeautifulSoup
8
+ import re
9
+ import torch
10
+ from io import BytesIO
11
+
12
+ # Pipelines
13
+ qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
14
+ caption_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
15
+ summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
16
+
17
+ # Utils
18
+ def search_web(query, max_results=3):
19
+ with DDGS() as ddgs:
20
+ results = ddgs.text(query, max_results=max_results)
21
+ return "\n\n".join([f"**{r['title']}**\n{r['body']}\n{r['href']}" for r in results])
22
+
23
+ def explain_image(img):
24
+ return caption_pipeline(img)[0]['generated_text']
25
+
26
+ def extract_text_from_url(url):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
+ res = requests.get(url, timeout=5)
29
+ soup = BeautifulSoup(res.text, 'html.parser')
30
+ # Remove scripts/styles
31
+ for script in soup(["script", "style"]): script.extract()
32
+ text = soup.get_text(separator=' ')
33
+ clean_text = re.sub(r'\s+', ' ', text)
34
+ return clean_text[:3000] # Limit to 3000 characters
 
 
 
 
35
  except Exception as e:
36
+ return f"Failed to extract text: {str(e)}"
37
+
38
+ def summarize_url(url):
39
+ text = extract_text_from_url(url)
40
+ if len(text) > 100:
41
+ summary = summarizer(text[:1024])[0]['summary_text']
42
+ return summary
43
+ return "Not enough text to summarize."
44
+
45
+ # Main Agent Function
46
+ def ai_agent(input_text, image=None, url=None):
47
+ results = []
48
+
49
+ # Process Image
50
+ if image:
51
+ results.append("๐Ÿ–ผ๏ธ **Image Explanation:**\n" + explain_image(image))
52
+
53
+ # Process URL
54
+ if url:
55
+ if "youtube.com" in url or "youtu.be" in url:
56
+ results.append("๐Ÿ“น **Video URL detected.** Currently only summaries of page content are available.")
57
+ results.append("๐Ÿ”— **Webpage Summary:**\n" + summarize_url(url))
58
+
59
+ # Web search for complex questions
60
+ if input_text:
61
+ if len(input_text.split()) > 10: # assume complex
62
+ web_results = search_web(input_text)
63
+ results.append("๐Ÿ” **Web Search Results:**\n" + web_results)
64
+ else:
65
+ results.append("๐Ÿง  **Answer:**\n" + search_web(input_text))
66
+
67
+ return "\n\n---\n\n".join(results)
68
+
69
+ # Gradio UI
70
  with gr.Blocks() as demo:
71
+ gr.Markdown("## ๐ŸŒ๐Ÿง  Multi-Modal AI Agent (Web + Image + URL)")
72
+ with gr.Row():
73
+ input_text = gr.Textbox(label="Ask a Question", lines=2, placeholder="E.g. What are the latest AI trends?")
74
+ image = gr.Image(type="pil", label="Upload an Image (optional)")
75
+ url = gr.Textbox(label="Provide a URL (optional)", placeholder="https://example.com")
76
+ submit = gr.Button("Get Answer")
77
+ output = gr.Markdown()
78
 
79
+ submit.click(fn=ai_agent, inputs=[input_text, image, url], outputs=output)
 
 
 
 
 
80
 
81
+ demo.launch()
82