Spaces:
Sleeping
Sleeping
auth
Browse filesFiles changed (5)
- .gitignore+4-1
- config.py+11
- evaluation.py+11-1
- hf_agent.py+265-2
- requirements.txt+5-1
123venv/.env__pycache__/123456venv/.env__pycache__/.cursorrules/.cursor/
13 unmodified lines14151617181915 unmodified lines35363738394013 unmodified lines"temperature": 0.7,"max_new_tokens": 256, # Reduced to prevent over-generation"top_p": 1.0,}# --- System Prompts ---15 unmodified lines"When users ask for current/recent information, acknowledge this limitation clearly and provide specific, actionable guidance on where they can find this information themselves. ""Be direct and helpful about the best sources for their query."),"evaluation": ("You are participating in the GAIA evaluation. ""Provide accurate, comprehensive, and concise answers. Focus on the task at hand."13 unmodified lines14151617181920212223242515 unmodified lines414243444546474849505113 unmodified lines"temperature": 0.7,"max_new_tokens": 256, # Reduced to prevent over-generation"top_p": 1.0,"enable_web_search": True, # Enable/disable web search functionality"max_search_results": 5, # Maximum number of search results to return"search_timeout": 10, # Timeout for web search requests in seconds"enable_article_extraction": True, # Enable/disable article content extraction"max_articles_to_read": 3, # Maximum number of articles to read full content"max_article_length": 2000, # Maximum length of extracted article content}# --- System Prompts ---15 unmodified lines"When users ask for current/recent information, acknowledge this limitation clearly and provide specific, actionable guidance on where they can find this information themselves. ""Be direct and helpful about the best sources for their query."),"web_search_with_content": ("You have been provided with current web search results that include extracted article content. ""Synthesize the information from the articles to provide a comprehensive answer to the user's question. ""Cite specific sources when mentioning information. Be accurate and informative."),"evaluation": ("You are participating in the GAIA evaluation. ""Provide accurate, comprehensive, and concise answers. Focus on the task at hand."
93 unmodified lines9495969798993 unmodified lines10310410510610710810993 unmodified lines<span style='color:#555'>- **Free models only** (no OpenAI)- Handles all question types and file attachments- Beautiful, modern UI- Robust agentic flows for GAIA evaluation3 unmodified lines**Instructions:**1. Login with your Hugging Face account.2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images).3. Or run the full GAIA evaluation and submit your answers.""")if not ON_SPACES:gr.Markdown("<span style='color:red'><b>Warning:</b> OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.</span>")93 unmodified lines9495969798991001011023 unmodified lines10610710810911011111211311411511611711811993 unmodified lines<span style='color:#555'>- **Free models only** (no OpenAI)- **Real-time web search** with DuckDuckGo integration- **Article content extraction** - reads full articles from search results- **Intelligent synthesis** - combines information from multiple sources- Handles all question types and file attachments- Beautiful, modern UI- Robust agentic flows for GAIA evaluation3 unmodified lines**Instructions:**1. Login with your Hugging Face account.2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images).3. **Web Search**: Ask for latest news, current information, or real-time data.4. **Article Extraction**: Use keywords like "detailed", "full analysis", or "comprehensive" for in-depth article reading.5. Or run the full GAIA evaluation and submit your answers.**Search Tips:**- For quick results: "brief news about X" or "quick summary of Y"- For detailed analysis: "comprehensive report on X" or "detailed analysis of Y"- For news: "latest news in [location]" automatically extracts article content""")if not ON_SPACES:gr.Markdown("<span style='color:red'><b>Warning:</b> OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.</span>")
5 unmodified lines678910112 unmodified lines14151617181960 unmodified lines80818283848573 unmodified lines15916016116216316419 unmodified lines1841851861871881891901915 unmodified linesfrom docx import Documentfrom PIL import Imageimport ioclass HuggingFaceAgent:def __init__(self):2 unmodified linesself.code = pipeline("text2text-generation", model=self.config["code_model"], max_new_tokens=self.config["max_new_tokens"])# Retrieval pipeline can be added here if neededself.supported_file_types = get_supported_file_types()def extract_file_context(self, files):context = []60 unmodified linesreturn web_score >= 1 or temporal_score >= 1def clean_response(self, generated_text, input_text):"""Clean the generated response by removing the input prompt"""# Remove the input text from the beginning if present73 unmodified lineselse:return "I cannot access real-time information from the internet. For current data, please use a search engine or visit relevant official websites."def __call__(self, question, files=None):context = ""if files:19 unmodified linesreturn self.clean_response(generated_text, input_text)elif self.needs_web_search(question):# Handle web search requests with specific guidancereturn self.get_web_search_guidance(question)elif self.is_math_or_code(question):# Handle math/code questions5 unmodified lines678910111213141516172 unmodified lines2021222324252660 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119273 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438519 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534545 unmodified linesfrom docx import Documentfrom PIL import Imageimport iofrom ddgs import DDGSfrom newspaper import Articlefrom bs4 import BeautifulSoupimport requestsfrom urllib.parse import urljoin, urlparseimport timeclass HuggingFaceAgent:def __init__(self):2 unmodified linesself.code = pipeline("text2text-generation", model=self.config["code_model"], max_new_tokens=self.config["max_new_tokens"])# Retrieval pipeline can be added here if neededself.supported_file_types = get_supported_file_types()self.ddgs = DDGS()def extract_file_context(self, files):context = []60 unmodified linesreturn web_score >= 1 or temporal_score >= 1def perform_web_search(self, query, max_results=None):"""Perform web search using DuckDuckGo and optionally extract article content"""if max_results is None:max_results = self.config.get("max_search_results", 5)try:# Improve query processing for better resultscleaned_query = query.lower().strip()# Remove search-related terms but preserve important contextsearch_terms_to_remove = ["search", "find", "look up", "get"]for term in search_terms_to_remove:if cleaned_query.startswith(term):cleaned_query = cleaned_query[len(term):].strip()# Handle specific patterns for better resultsif "news" in cleaned_query:if "vilnius" in cleaned_query or "lithuania" in cleaned_query:cleaned_query = "Vilnius Lithuania news"elif "latest news" in cleaned_query:cleaned_query = cleaned_query.replace("latest", "").strip() + " news today"elif "weather" in cleaned_query:# Extract location for weather queriesif "in " in cleaned_query:location = cleaned_query.split("in ")[-1].strip()cleaned_query = f"weather {location} today"# Ensure we have a meaningful queryif not cleaned_query or len(cleaned_query.strip()) < 3:cleaned_query = query # fallback to original# Add timeout handlingtimeout = self.config.get("search_timeout", 10)results = self.ddgs.text(cleaned_query, max_results=max_results)if not results:return "No search results found for your query. Try rephrasing or being more specific."# Check if article extraction is enabled and recommended for this queryextract_articles = (self.config.get("enable_article_extraction", True) andself.should_extract_articles(query))if extract_articles:# Extract URLs for article readingurls = [result.get('href', '') for result in results if result.get('href')]max_articles = self.config.get("max_articles_to_read", 3)# Extract article contentarticles = self.extract_multiple_articles(urls, max_articles)# Format results with article contentformatted_results = []for i, (result, article) in enumerate(zip(results, articles), 1):title = result.get('title', 'No title')snippet = result.get('body', 'No description')url = result.get('href', '')if len(snippet) > 150:snippet = snippet[:150] + "..."result_text = f"**{i}. {title}**\n{snippet}\nSource: {url}"# Add extracted article content if successfulif article['success'] and i <= max_articles:result_text += f"\n\n**Article Content:**\n{article['content']}"elif i <= max_articles:result_text += f"\n\n**Article Content:** {article['content']}"formatted_results.append(result_text)search_summary = f"Found {len(results)} results for '{cleaned_query}' (extracted content from first {min(max_articles, len(results))} articles):\n\n"return search_summary + "\n\n" + "="*80 + "\n\n".join(formatted_results)else:# Standard search results without article extractionformatted_results = []for i, result in enumerate(results, 1):title = result.get('title', 'No title')snippet = result.get('body', 'No description')url = result.get('href', '')# Limit snippet lengthif len(snippet) > 200:snippet = snippet[:200] + "..."formatted_results.append(f"**{i}. {title}**\n{snippet}\nSource: {url}")search_summary = f"Found {len(results)} results for '{cleaned_query}':\n\n"return search_summary + "\n\n".join(formatted_results)except Exception as e:error_msg = str(e).lower()if "timeout" in error_msg or "connection" in error_msg:return "Web search timed out or connection failed. Please try again later."elif "rate limit" in error_msg:return "Search rate limit exceeded. Please wait a moment and try again."else:return f"Web search encountered an error. Please try rephrasing your query."def clean_response(self, generated_text, input_text):"""Clean the generated response by removing the input prompt"""# Remove the input text from the beginning if present73 unmodified lineselse:return "I cannot access real-time information from the internet. For current data, please use a search engine or visit relevant official websites."def extract_article_content(self, url, max_length=2000):"""Extract article content from a URL"""try:# First try with newspaper3k (best for news articles)article = Article(url)article.download()article.parse()if article.text and len(article.text.strip()) > 100:content = article.text.strip()title = article.title or "Article"# Limit content lengthif len(content) > max_length:content = content[:max_length] + "..."return {"title": title,"content": content,"success": True}except Exception as e:pass# Fallback: try with BeautifulSouptry:headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.content, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style", "nav", "footer", "header", "aside"]):script.decompose()# Try to find main contentcontent_selectors = ['article', '.article-content', '.post-content', '.entry-content','.content', '#content', 'main', '.main-content', 'p']content = ""title = soup.find('title')title = title.get_text().strip() if title else "Article"for selector in content_selectors:elements = soup.select(selector)if elements:content = ' '.join([elem.get_text().strip() for elem in elements])if len(content) > 100:breakif content and len(content.strip()) > 100:content = content.strip()# Limit content lengthif len(content) > max_length:content = content[:max_length] + "..."return {"title": title,"content": content,"success": True}except Exception as e:passreturn {"title": "Failed to extract","content": "Could not extract article content from this URL.","success": False}def extract_multiple_articles(self, urls, max_articles=3):"""Extract content from multiple URLs with rate limiting"""extracted_articles = []for i, url in enumerate(urls[:max_articles]):if i > 0:time.sleep(1) # Rate limitingarticle_data = self.extract_article_content(url)article_data['url'] = urlextracted_articles.append(article_data)return extracted_articlesdef should_extract_articles(self, question):"""Determine if we should extract article content based on the query"""# Skip article extraction for simple/quick queriesquick_query_indicators = ["quick", "fast", "summary", "brief", "short", "overview"]question_lower = question.lower()if any(indicator in question_lower for indicator in quick_query_indicators):return False# Extract articles for news and detailed information requestsdetailed_query_indicators = ["details", "full", "complete", "comprehensive", "in-depth","article", "report", "analysis", "explain"]if any(indicator in question_lower for indicator in detailed_query_indicators):return True# Default: extract articles for news queries, skip for othersreturn "news" in question_lowerdef __call__(self, question, files=None):context = ""if files:19 unmodified linesreturn self.clean_response(generated_text, input_text)elif self.needs_web_search(question):# Handle web search requestsif self.config.get("enable_web_search", True):try:search_results = self.perform_web_search(question)# If article extraction is enabled, try to synthesize the informationif (self.config.get("enable_article_extraction", True) and"Article Content:" in search_results andlen(search_results) > 1000): # Only synthesize if we have substantial contenttry:# Use LLM to synthesize the article contentsystem_prompt = get_system_prompt("web_search_with_content")prompt = f"Search Results with Article Content:\n{search_results}\n\nUser Question: {question}\n\nSynthesized Answer:"input_text = f"{system_prompt}\n{prompt}"result = self.llm(input_text,do_sample=True,temperature=0.7,max_new_tokens=512, # More tokens for synthesispad_token_id=self.llm.tokenizer.eos_token_id,eos_token_id=self.llm.tokenizer.eos_token_id,repetition_penalty=1.1)generated_text = result[0]["generated_text"]synthesized_answer = self.clean_response(generated_text, input_text)# Return both synthesized answer and full search resultsreturn f"**Synthesized Answer:**\n{synthesized_answer}\n\n{'='*80}\n\n**Full Search Results:**\n{search_results}"except Exception as e:# If synthesis fails, return raw search resultsreturn search_resultselse:# Return search results as-isreturn search_resultsexcept Exception as e:# Fallback to guidance if search failsreturn self.get_web_search_guidance(question)else:# Web search disabled, provide guidancereturn self.get_web_search_guidance(question)elif self.is_math_or_code(question):# Handle math/code questions
4 unmodified lines56784 unmodified linespdfplumber>=0.10.0python-docx>=0.8.11Pillow>=9.0.0requests>=2.28.04 unmodified lines567891011124 unmodified linespdfplumber>=0.10.0python-docx>=0.8.11Pillow>=9.0.0requests>=2.28.0ddgs>=9.4.0beautifulsoup4>=4.13.0newspaper3k>=0.2.8lxml[html_clean]>=6.0.0
.gitignore+4-1
config.py+11
evaluation.py+11-1
hf_agent.py+265-2
requirements.txt+5-1