kpbotla commited on
Commit
458d66b
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files

for final project

Files changed (1) hide show
  1. app.py +66 -1
app.py CHANGED
@@ -4,12 +4,22 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
 
 
 
 
 
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
@@ -19,6 +29,59 @@ class BasicAgent:
19
  print(f"Agent returning fixed answer: {fixed_answer}")
20
  return fixed_answer
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -40,7 +103,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
 
 
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
 
4
  import inspect
5
  import pandas as pd
6
 
7
+
8
+ from duckduckgo_search import ddg
9
+ from transformers import pipeline
10
+ from newspaper import Article
11
+ import hashlib, datetime
12
+
13
+
14
  # (Keep Constants as is)
15
  # --- Constants ---
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
18
  # --- Basic Agent Definition ---
19
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
20
+ # Summarization pipeline (load once)
21
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
22
+
23
  class BasicAgent:
24
  def __init__(self):
25
  print("BasicAgent initialized.")
 
29
  print(f"Agent returning fixed answer: {fixed_answer}")
30
  return fixed_answer
31
 
32
+
33
+ class SmartResearchAgent:
34
+ def __init__(self):
35
+ print("SmartResearchAgent initialized.")
36
+
37
+ def search_web(self, query: str) -> str:
38
+ results = ddg(query, max_results=3)
39
+ if not results:
40
+ return "No results found."
41
+ return "\n".join(f"{i+1}. {r['title']}: {r['href']}" for i, r in enumerate(results))
42
+
43
+ def summarize(self, input_text: str) -> str:
44
+ if input_text.startswith("http"):
45
+ try:
46
+ article = Article(input_text)
47
+ article.download()
48
+ article.parse()
49
+ input_text = article.text
50
+ except Exception as e:
51
+ return f"Error processing article: {e}"
52
+ summary = summarizer(input_text, max_length=130, min_length=30, do_sample=False)
53
+ return summary[0]['summary_text']
54
+
55
+ def generate_citation(self, source: str) -> str:
56
+ citation_id = hashlib.md5(source.encode()).hexdigest()[:6]
57
+ year = datetime.datetime.now().year
58
+ return f"@article{{cite{citation_id}, title={{\"Research Article\"}}, author={{Unknown}}, journal={{Online Source}}, year={{ {year} }}, url={{ {source} }} }}"
59
+
60
+ def __call__(self, question: str) -> str:
61
+ print(f"Received question: {question}")
62
+
63
+ if "summarize" in question.lower():
64
+ return self.summarize(question.replace("summarize", "", 1).strip())
65
+
66
+ elif "cite" in question.lower() or "citation" in question.lower():
67
+ return self.generate_citation(question.split()[-1])
68
+
69
+ elif "search" in question.lower():
70
+ return self.search_web(question.replace("search", "", 1).strip())
71
+
72
+ else:
73
+ # Default: web search + summarization
74
+ web_result = self.search_web(question)
75
+ if "http" in web_result:
76
+ first_url = next((line.split(": ", 1)[-1] for line in web_result.splitlines() if line.startswith("1.")), None)
77
+ if first_url:
78
+ summary = self.summarize(first_url)
79
+ citation = self.generate_citation(first_url)
80
+ return f"Summary:\n{summary}\n\nCitation:\n{citation}"
81
+ return web_result
82
+
83
+
84
+
85
  def run_and_submit_all( profile: gr.OAuthProfile | None):
86
  """
87
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
103
 
104
  # 1. Instantiate Agent ( modify this part to create your agent)
105
  try:
106
+ #agent = BasicAgent()
107
+ agent = SmartResearchAgent()
108
+
109
  except Exception as e:
110
  print(f"Error instantiating agent: {e}")
111
  return f"Error initializing agent: {e}", None