Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,18 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from huggingface_hub import InferenceClient
|
| 6 |
from duckduckgo_search import DDGS
|
| 7 |
import wikipediaapi
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# ==== CONFIG ====
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 12 |
|
| 13 |
CONVERSATIONAL_MODELS = [
|
| 14 |
"deepseek-ai/DeepSeek-LLM",
|
|
@@ -18,25 +22,94 @@ CONVERSATIONAL_MODELS = [
|
|
| 18 |
|
| 19 |
wiki_api = wikipediaapi.Wikipedia(language="en", user_agent="SmartAgent/1.0 (chockqoteewy@gmail.com)")
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# ==== SEARCH TOOLS ====
|
| 22 |
def duckduckgo_search(query):
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
def wikipedia_search(query):
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
def
|
| 32 |
-
last_error =
|
| 33 |
for model_id in CONVERSATIONAL_MODELS:
|
| 34 |
try:
|
| 35 |
hf_client = InferenceClient(model_id, token=HF_TOKEN)
|
| 36 |
-
# Try conversational
|
| 37 |
if hasattr(hf_client, "conversational"):
|
| 38 |
result = hf_client.conversational(
|
| 39 |
-
messages=[{"role": "user", "content":
|
| 40 |
max_new_tokens=384,
|
| 41 |
)
|
| 42 |
if isinstance(result, dict) and "generated_text" in result:
|
|
@@ -47,79 +120,97 @@ def hf_chat_model(question):
|
|
| 47 |
return result
|
| 48 |
else:
|
| 49 |
continue
|
| 50 |
-
|
| 51 |
-
result = hf_client.text_generation(question, max_new_tokens=384)
|
| 52 |
if isinstance(result, dict) and "generated_text" in result:
|
| 53 |
return result["generated_text"]
|
| 54 |
elif isinstance(result, str):
|
| 55 |
return result
|
| 56 |
except Exception as e:
|
| 57 |
last_error = f"{model_id}: {e}"
|
| 58 |
-
continue
|
| 59 |
-
return f"HF LLM error: {last_error or 'All models failed.'}"
|
| 60 |
-
|
| 61 |
-
def try_parse_vegetable_list(question):
|
| 62 |
-
if "vegetable" in question.lower():
|
| 63 |
-
# Heuristic: find list in question, extract vegetables only
|
| 64 |
-
import re
|
| 65 |
-
food_match = re.findall(r"list\s+.*?:\s*([a-zA-Z0-9,\s\-]+)", question)
|
| 66 |
-
food_str = food_match[0] if food_match else ""
|
| 67 |
-
foods = [f.strip().lower() for f in food_str.split(",") if f.strip()]
|
| 68 |
-
# Simple vegtable classifier (expand this list as needed)
|
| 69 |
-
vegetables = set(["acorns", "broccoli", "celery", "green beans", "lettuce", "peanuts", "sweet potatoes", "zucchini", "corn", "bell pepper"])
|
| 70 |
-
veg_list = sorted([f for f in foods if f in vegetables])
|
| 71 |
-
if veg_list:
|
| 72 |
-
return ", ".join(veg_list)
|
| 73 |
return None
|
| 74 |
|
| 75 |
-
def
|
| 76 |
-
#
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# If your UI supports uploads, read the file, parse food vs. drinks and sum.
|
| 87 |
-
return "$12562.20"
|
| 88 |
-
return None
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
# ==== SMART AGENT ====
|
| 97 |
class SmartAgent:
|
| 98 |
def __init__(self):
|
| 99 |
pass
|
| 100 |
|
| 101 |
-
def __call__(self, question: str
|
| 102 |
-
# 1.
|
| 103 |
-
|
| 104 |
-
if
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
# ==== SUBMISSION LOGIC ====
|
| 125 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
| 5 |
import pandas as pd
|
| 6 |
from huggingface_hub import InferenceClient
|
| 7 |
from duckduckgo_search import DDGS
|
| 8 |
import wikipediaapi
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
import pdfplumber
|
| 11 |
|
| 12 |
# ==== CONFIG ====
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 15 |
+
GROK_API_KEY = os.getenv("GROK_API_KEY") or "xai-AyJXz3OAAMuQiOrPzPptUWTmsEyI9vywPpbV19S1nCpXXKWoKLqOoGc61RazPPui2fx4Ekb1durXccqz"
|
| 16 |
|
| 17 |
CONVERSATIONAL_MODELS = [
|
| 18 |
"deepseek-ai/DeepSeek-LLM",
|
|
|
|
| 22 |
|
| 23 |
wiki_api = wikipediaapi.Wikipedia(language="en", user_agent="SmartAgent/1.0 (chockqoteewy@gmail.com)")
|
| 24 |
|
| 25 |
+
# ==== UTILITY: Link/file detection ====
|
| 26 |
+
def extract_links(text):
|
| 27 |
+
url_pattern = re.compile(r'(https?://[^\s\)\],]+)')
|
| 28 |
+
return url_pattern.findall(text)
|
| 29 |
+
|
| 30 |
+
def download_file(url, out_dir="tmp_files"):
|
| 31 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 32 |
+
filename = url.split("/")[-1].split("?")[0]
|
| 33 |
+
local_path = os.path.join(out_dir, filename)
|
| 34 |
+
try:
|
| 35 |
+
r = requests.get(url, timeout=20)
|
| 36 |
+
r.raise_for_status()
|
| 37 |
+
with open(local_path, "wb") as f:
|
| 38 |
+
f.write(r.content)
|
| 39 |
+
return local_path
|
| 40 |
+
except Exception:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
# ==== File/Link Analyzers ====
|
| 44 |
+
def analyze_file(file_path):
|
| 45 |
+
if file_path.endswith((".xlsx", ".xls")):
|
| 46 |
+
try:
|
| 47 |
+
df = pd.read_excel(file_path)
|
| 48 |
+
return f"Excel summary: {df.head().to_markdown(index=False)}"
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return f"Excel error: {e}"
|
| 51 |
+
elif file_path.endswith(".csv"):
|
| 52 |
+
try:
|
| 53 |
+
df = pd.read_csv(file_path)
|
| 54 |
+
return f"CSV summary: {df.head().to_markdown(index=False)}"
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return f"CSV error: {e}"
|
| 57 |
+
elif file_path.endswith(".pdf"):
|
| 58 |
+
try:
|
| 59 |
+
with pdfplumber.open(file_path) as pdf:
|
| 60 |
+
first_page = pdf.pages[0].extract_text()
|
| 61 |
+
return f"PDF text sample: {first_page[:1000]}"
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return f"PDF error: {e}"
|
| 64 |
+
elif file_path.endswith(".txt"):
|
| 65 |
+
try:
|
| 66 |
+
with open(file_path, encoding='utf-8') as f:
|
| 67 |
+
txt = f.read()
|
| 68 |
+
return f"TXT file sample: {txt[:1000]}"
|
| 69 |
+
except Exception as e:
|
| 70 |
+
return f"TXT error: {e}"
|
| 71 |
+
else:
|
| 72 |
+
return f"Unsupported file type: {file_path}"
|
| 73 |
+
|
| 74 |
+
def analyze_webpage(url):
|
| 75 |
+
try:
|
| 76 |
+
r = requests.get(url, timeout=15)
|
| 77 |
+
soup = BeautifulSoup(r.text, "lxml")
|
| 78 |
+
title = soup.title.string if soup.title else "No title"
|
| 79 |
+
paragraphs = [p.get_text() for p in soup.find_all("p")]
|
| 80 |
+
article_sample = "\n".join(paragraphs[:5])
|
| 81 |
+
return f"Webpage Title: {title}\nContent sample:\n{article_sample[:1200]}"
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return f"Webpage error: {e}"
|
| 84 |
+
|
| 85 |
# ==== SEARCH TOOLS ====
|
| 86 |
def duckduckgo_search(query):
|
| 87 |
+
try:
|
| 88 |
+
with DDGS() as ddgs:
|
| 89 |
+
results = [r for r in ddgs.text(query, max_results=3)]
|
| 90 |
+
bodies = [r.get("body", "") for r in results if r.get("body")]
|
| 91 |
+
return "\n".join(bodies) if bodies else None
|
| 92 |
+
except Exception:
|
| 93 |
+
return None
|
| 94 |
|
| 95 |
def wikipedia_search(query):
|
| 96 |
+
try:
|
| 97 |
+
page = wiki_api.page(query)
|
| 98 |
+
if page.exists() and page.summary:
|
| 99 |
+
return page.summary
|
| 100 |
+
except Exception:
|
| 101 |
+
return None
|
| 102 |
+
return None
|
| 103 |
|
| 104 |
+
def llm_conversational(query):
|
| 105 |
+
last_error = None
|
| 106 |
for model_id in CONVERSATIONAL_MODELS:
|
| 107 |
try:
|
| 108 |
hf_client = InferenceClient(model_id, token=HF_TOKEN)
|
| 109 |
+
# Try conversational if available, else fallback to text_generation
|
| 110 |
if hasattr(hf_client, "conversational"):
|
| 111 |
result = hf_client.conversational(
|
| 112 |
+
messages=[{"role": "user", "content": query}],
|
| 113 |
max_new_tokens=384,
|
| 114 |
)
|
| 115 |
if isinstance(result, dict) and "generated_text" in result:
|
|
|
|
| 120 |
return result
|
| 121 |
else:
|
| 122 |
continue
|
| 123 |
+
result = hf_client.text_generation(query, max_new_tokens=384)
|
|
|
|
| 124 |
if isinstance(result, dict) and "generated_text" in result:
|
| 125 |
return result["generated_text"]
|
| 126 |
elif isinstance(result, str):
|
| 127 |
return result
|
| 128 |
except Exception as e:
|
| 129 |
last_error = f"{model_id}: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
return None
|
| 131 |
|
| 132 |
+
def is_coding_question(text):
|
| 133 |
+
# Basic heuristic: mentions code, function, "python", code blocks, etc.
|
| 134 |
+
code_terms = [
|
| 135 |
+
"python", "java", "c++", "code", "function", "write a", "script", "algorithm",
|
| 136 |
+
"bug", "traceback", "error", "output", "compile", "debug"
|
| 137 |
+
]
|
| 138 |
+
if any(term in text.lower() for term in code_terms):
|
| 139 |
+
return True
|
| 140 |
+
if re.search(r"```.+```", text, re.DOTALL):
|
| 141 |
+
return True
|
| 142 |
+
return False
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
def grok_completion(question, system_prompt=None):
|
| 145 |
+
url = "https://api.x.ai/v1/chat/completions"
|
| 146 |
+
headers = {
|
| 147 |
+
"Content-Type": "application/json",
|
| 148 |
+
"Authorization": f"Bearer {GROK_API_KEY}"
|
| 149 |
+
}
|
| 150 |
+
payload = {
|
| 151 |
+
"messages": [
|
| 152 |
+
{"role": "system", "content": system_prompt or "You are a helpful coding and research assistant."},
|
| 153 |
+
{"role": "user", "content": question}
|
| 154 |
+
],
|
| 155 |
+
"model": "grok-3-latest",
|
| 156 |
+
"stream": False,
|
| 157 |
+
"temperature": 0
|
| 158 |
+
}
|
| 159 |
+
try:
|
| 160 |
+
r = requests.post(url, headers=headers, json=payload, timeout=45)
|
| 161 |
+
r.raise_for_status()
|
| 162 |
+
data = r.json()
|
| 163 |
+
# Extract assistant's reply
|
| 164 |
+
return data['choices'][0]['message']['content']
|
| 165 |
+
except Exception as e:
|
| 166 |
+
return None
|
| 167 |
|
| 168 |
# ==== SMART AGENT ====
|
| 169 |
class SmartAgent:
|
| 170 |
def __init__(self):
|
| 171 |
pass
|
| 172 |
|
| 173 |
+
def __call__(self, question: str) -> str:
|
| 174 |
+
# 1. Handle file/link
|
| 175 |
+
links = extract_links(question)
|
| 176 |
+
if links:
|
| 177 |
+
results = []
|
| 178 |
+
for url in links:
|
| 179 |
+
if re.search(r"\.xlsx|\.xls|\.csv|\.pdf|\.txt", url):
|
| 180 |
+
local = download_file(url)
|
| 181 |
+
if local:
|
| 182 |
+
file_analysis = analyze_file(local)
|
| 183 |
+
results.append(f"File ({url}):\n{file_analysis}")
|
| 184 |
+
else:
|
| 185 |
+
results.append(analyze_webpage(url))
|
| 186 |
+
if results:
|
| 187 |
+
return "\n\n".join(results)
|
| 188 |
+
|
| 189 |
+
# 2. Coding or algorithmic problems? Try Grok FIRST
|
| 190 |
+
if is_coding_question(question):
|
| 191 |
+
grok_response = grok_completion(question)
|
| 192 |
+
if grok_response:
|
| 193 |
+
return f"[Grok] {grok_response}"
|
| 194 |
+
|
| 195 |
+
# 3. DuckDuckGo for web knowledge
|
| 196 |
+
result = duckduckgo_search(question)
|
| 197 |
+
if result:
|
| 198 |
+
return result
|
| 199 |
+
# 4. Wikipedia for encyclopedic queries
|
| 200 |
+
result = wikipedia_search(question)
|
| 201 |
+
if result:
|
| 202 |
+
return result
|
| 203 |
+
# 5. Grok again for hard/reasoning/general (if not already tried)
|
| 204 |
+
if not is_coding_question(question):
|
| 205 |
+
grok_response = grok_completion(question)
|
| 206 |
+
if grok_response:
|
| 207 |
+
return f"[Grok] {grok_response}"
|
| 208 |
+
|
| 209 |
+
# 6. Fallback to LLM conversational
|
| 210 |
+
result = llm_conversational(question)
|
| 211 |
+
if result:
|
| 212 |
+
return result
|
| 213 |
+
return "No answer could be found by available tools."
|
| 214 |
|
| 215 |
# ==== SUBMISSION LOGIC ====
|
| 216 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|