Spaces:
Sleeping
Sleeping
Update app.py
Browse files290 unmodified lines291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880290 unmodified linesreturn list(set(key_phrases)) # Return unique phrasesdef general_reasoning_qa(self, state):question = state["question"]question_lower = question.lower()try:search_results = wikipedia.search(question, results=3)if not search_results:state["response"] = "Sorry, I couldn't find relevant information on Wikipedia."return statecontext = self.get_relevant_context(question, search_results)# Store the context in an instance variable so other methods can access itself.current_context = contextif not context:state["response"] = "Sorry, I couldn't find detailed relevant information."return statecontext = self.preprocess_context(context)tables = self.extract_tables_from_wikipedia(context)# Try to extract a specific answer firstanswer = self.extract_answer(question, context, tables)if answer and self.validate_answer(question, answer):state["response"] = answerreturn state# If no specific answer or validation failed, try to get the most relevant sentenceif not answer:question_keywords = self.extract_key_phrases(question)if question_keywords:sentences = re.split(r'(?<=[.!?])\s+', context) # Split more carefully to keep punctuation with sentencescored_sentences = []for sentence in sentences:sentence = sentence.strip()if not sentence:continue# Score based on keyword density and presence of question wordsscore = 0sentence_lower = sentence.lower()for keyword in question_keywords:if keyword.lower() in sentence_lower:score += 1# Boost if it contains an answer-like entity (number, date, named entity)if any(char.isdigit() for char in sentence): # Contains numbersscore += 0.5if any(ent.label_ in ["PERSON", "ORG", "GPE", "DATE"] for ent in nlp(sentence).ents):score += 0.7if score > 0:scored_sentences.append((score, sentence))if scored_sentences:scored_sentences.sort(key=lambda x: (-x[0], -len(x[1])))best_sentence = scored_sentences[0][1]# Fallback to the best sentence, ensuring it ends properlyif best_sentence.endswith('.') or best_sentence.endswith('!') or best_sentence.endswith('?'):state["response"] = best_sentenceelse:state["response"] = best_sentence + "."return state# If all else fails, provide a summarytry:first_page = self.wiki_wiki.page(search_results[0])if first_page.exists():summary = first_page.summary[:700] + "..." # Slightly larger summarystate["response"] = f"I couldn't find a specific answer, but here's some relevant information: {summary}"else:state["response"] = "No relevant information found."except Exception as e:state["response"] = f"I couldn't find a specific answer in the available information."except Exception as e:state["response"] = f"An error occurred while searching for information: {str(e)}"return statedef validate_answer(self, question, answer):"""Validate if the extracted answer seems plausible for the question type."""question_lower = question.lower()# Check for numeric answers for "how many/much" questionsif "how many" in question_lower or "how much" in question_lower:if not re.search(r'\d+', answer):# If question asks for a number but answer has no number, it's likely wrongreturn False# Check for year/date answers for "when" questionsif "when" in question_lower or "year" in question_lower:if not re.search(r'\b\d{4}\b', answer) and not re.search(r'\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b', answer):return False# Simple check: avoid answers that are just prepositions or very shortif len(answer.split()) < 3 and not re.search(r'\d+', answer): # Allow short numeric answersreturn Falsereturn Truedef extract_tables_from_wikipedia(self, content):"""Extract tables from Wikipedia content (wiki markup and basic HTML).Improved parsing for cells and handling multiple tables."""tables = []# Regex for wiki markup tables# Improved: Capture table contents, then parse row by rowwiki_table_pattern = r'\{\|\s*(?:class="[^"]*")?.*?\|\}(?=\n|\Z)'for table_match in re.finditer(wiki_table_pattern, content, re.DOTALL):table_content = table_match.group(0)rows = re.findall(r'\|\-(.*?)(?=\|\-|\{\||\Z)', table_content, re.DOTALL) # Split by |-clean_rows = []if not rows and '|+' in table_content: # Handle tables with only a captioncontinue# First row might be headers (starting with !) or data (|)# Try to find header row explicitly if presentheader_match = re.search(r'\|\n(?:!\s*[^|!]+\s*(?:\|\|)?)+\n', table_content)if header_match:header_line = header_match.group(0).strip()headers = re.findall(r'!\s*([^|!]+?)\s*(?:\|\||(?=\n))', header_line)clean_headers = [self._clean_cell_content(h) for h in headers]if clean_headers:clean_rows.append(clean_headers)# Remove header line from subsequent parsingtable_content = table_content.replace(header_line, '', 1)rows = re.findall(r'\|\-(.*?)(?=\|\-|\{\||\Z)', table_content, re.DOTALL)for row in rows:# Cells can start with | or ||cells = re.findall(r'(?:\||\!)\s*([^|!]+?)(?:\|\||(?=\n)|(?=\Z))', row, re.DOTALL)clean_cells = [self._clean_cell_content(cell) for cell in cells]if clean_cells:clean_rows.append(clean_cells)if clean_rows:tables.append(clean_rows)# Basic HTML table extraction (often less structured in Wikipedia text than wiki markup)html_table_pattern = r'<table.*?</table>'for html_table_match in re.finditer(html_table_pattern, content, re.DOTALL | re.IGNORECASE):table_content = html_table_match.group(0)rows = re.findall(r'<tr.*?</tr>', table_content, re.DOTALL | re.IGNORECASE)clean_rows = []for row in rows:cells = re.findall(r'<t[dh].*?</t[dh]>', row, re.DOTALL | re.IGNORECASE)clean_cells = []for cell in cells:cell_text = self._clean_cell_content(cell)clean_cells.append(cell_text)if clean_cells:clean_rows.append(clean_cells)if clean_rows:tables.append(clean_rows)return tablesdef _clean_cell_content(self, cell):"""Helper to clean individual table cell content."""cell = re.sub(r'\[\[(?:[^|\]]+\|)?([^\]]+)\]\]', r'\1', cell) # Remove wiki links, keep textcell = re.sub(r'<[^>]+>', '', cell) # Remove HTML tagscell = re.sub(r'\{\{.*?\}\}', '', cell) # Remove templates within cellscell = re.sub(r'\s+', ' ', cell).strip()return celldef extract_answer(self, question, context, tables=None):"""Enhanced general purpose answer extraction from text context using spaCy."""if tables is None:tables = []question_lower = question.lower()doc_context = nlp(context)# First, check tables for a direct answertable_answer = self.find_answer_in_tables(question, tables)if table_answer:return table_answerquestion_type = self.detect_question_type(question_lower)# Extract named entities and their labelsentities = [(ent.text, ent.label_, ent.start_char, ent.end_char) for ent in doc_context.ents]# Extract all numbers and datesnumbers_dates = []for match in re.finditer(r'(\d[\d,]*\d*|\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*\s+\d{1,2}(?:st|nd|rd|th)?(?:,\s+\d{4})?|\b\d{1,2}/\d{1,2}/\d{2,4}\b|\b\d{4}\b)', context, re.IGNORECASE):numbers_dates.append((match.group(1).replace(',', ''), match.start(), match.end()))# Prioritize answers based on question type and entity recognitionif question_type in ["count", "how many"]:# Look for numbers with relevant contextbest_number_match = self.find_best_number_match_spacy(question_lower, numbers_dates, context)if best_number_match:return f"{best_number_match[0]}"elif question_type == "person":relevant_person = self.find_relevant_person_spacy(question_lower, entities)if relevant_person:return f"{relevant_person}"elif question_type == "date":relevant_date = self.find_relevant_date_spacy(question_lower, numbers_dates, entities)if relevant_date:return f"{relevant_date}"elif question_type == "location":relevant_location = self.find_relevant_location_spacy(question_lower, entities)if relevant_location:return f"{relevant_location}"# Fallback to general sentence scoring if specific extraction failskey_phrases = self.extract_key_phrases(question)sentences = re.split(r'(?<=[.!?])\s+', context)scored_sentences = []for sentence in sentences:sentence = sentence.strip()if not sentence:continuescore = 0sentence_lower = sentence.lower()for keyword in key_phrases:if keyword.lower() in sentence_lower:score += 1# Boost score if sentence contains relevant entity typesdoc_sentence = nlp(sentence)for ent in doc_sentence.ents:if (question_type == "person" and ent.label_ == "PERSON") or \(question_type == "date" and ent.label_ == "DATE") or \(question_type == "location" and ent.label_ in ["GPE", "LOC", "ORG"]) or \(question_type == "count" and ent.label_ == "CARDINAL"):score += 2 # Higher boost for direct entity type matchif score > 0:scored_sentences.append((score, sentence))if scored_sentences:scored_sentences.sort(key=lambda x: (-x[0], -len(x[1])))best_sentence = scored_sentences[0][1]if best_sentence.endswith('.') or best_sentence.endswith('!') or best_sentence.endswith('?'):return best_sentencereturn best_sentence + "."return Nonedef detect_question_type(self, question):"""Classify the type of question using spaCy token analysis."""doc = nlp(question)# Check for "wh-" words and common patternsif "how many" in question or "how much" in question or "total" in question or "number of" in question:return "count"if "who" in question or "which person" in question or "which player" in question:return "person"if "when" in question or "what year" in question or "what date" in question:return "date"if "where" in question or "what location" in question or "in what city" in question:return "location"if "what is" in question or "what was" in question or "define" in question:return "definition"if "list of" in question or "list the" in question or "enumerate" in question:return "list"# Analyze dependency parse for more complex typesfor token in doc:if token.dep_ == "nsubj" and token.head.lemma_ in ["be", "do"]: # What is X, Who is Yif token.ent_type_ == "PERSON": return "person"if token.ent_type_ in ["GPE", "LOC"]: return "location"if token.text.lower() in ["number", "amount", "total"]: return "count"return "general" # Default to generaldef find_best_number_match_spacy(self, question, numbers_dates, context):"""Find the number from context that best matches the question using spaCy."""if not numbers_dates:return Nonequestion_keywords = self.extract_key_phrases(question)doc_context = nlp(context)scored_numbers = []for number, start_char, end_char in numbers_dates:score = 0# Get surrounding text (sentence)span = doc_context.char_span(start_char, end_char)if span and span.sent:sentence = span.sent.textsentence_lower = sentence.lower()# Score based on question keyword presence in the sentencefor keyword in question_keywords:if keyword.lower() in sentence_lower:score += 1# Check if it's a cardinal entityfor ent in nlp(sentence).ents:if ent.text == number and ent.label_ == "CARDINAL":score += 2 # Boost for being a recognized cardinal number# Proximity to keywords (more advanced with spaCy)for keyword_doc in nlp(question):if not keyword_doc.is_stop and not keyword_doc.is_punct:# Find occurrences of keyword lemma in sentencefor token in nlp(sentence):if token.lemma_ == keyword_doc.lemma_:distance = abs(token.i - span.start)score += max(0, 1.0 - (distance / 20.0)) # Closer is betterscored_numbers.append((score, number, sentence))if not scored_numbers:return Nonescored_numbers.sort(reverse=True, key=lambda x: x[0])return (scored_numbers[0][1], scored_numbers[0][2])def extract_named_entities(self, text):"""Extract named entities (PERSON, ORG, GPE, LOC) from text using spaCy."""doc = nlp(text)entities = []for ent in doc.ents:if ent.label_ in ["PERSON", "ORG", "GPE", "LOC"]:entities.append((ent.text, ent.label_, ent.start_char, ent.end_char))return entitiesdef find_relevant_person_spacy(self, question, entities):"""Find the most relevant person entity based on question context using spaCy."""person_entities = [ent for ent in entities if ent[1] == "PERSON"]if not person_entities:return Nonequestion_doc = nlp(question)question_keywords = [token.lemma_ for token in question_doc if not token.is_stop and not token.is_punct]best_score = -1best_person = Nonefor person_text, _, start_char, end_char in person_entities:score = 0# Get sentence where person appearsspan = nlp(self.current_context).char_span(start_char, end_char) # Need current_contextif span and span.sent:sentence = span.sent.textsentence_doc = nlp(sentence)# Check for keyword overlap (lemma-based)for q_lemma in question_keywords:for s_token in sentence_doc:if s_token.lemma_ == q_lemma:score += 1# Boost if the person is the subject of a relevant verbfor token in sentence_doc:if token.text == person_text and token.dep_ == "nsubj":if token.head.lemma_ in ["be", "do", "play", "win", "create", "discover", "lead"]:score += 2 # Strong boostif score > best_score:best_score = scorebest_person = person_textreturn best_persondef find_best_number_match_spacy(self, question, numbers_dates, context):if not numbers_dates:return Nonequestion_keywords = self.extract_key_phrases(question)doc_context = nlp(context)scored_numbers = []# Identify specific metrics from the question# Example: "at bats", "walks"specific_metrics = []if "at bats" in question.lower():specific_metrics.append("at bats")specific_metrics.append("ab") # Common abbreviationif "walks" in question.lower():specific_metrics.append("walks")specific_metrics.append("bb") # Common abbreviation# Add more as neededfor number, start_char, end_char in numbers_dates:score = 0span = doc_context.char_span(start_char, end_char)if span and span.sent:sentence = span.sent.textsentence_lower = sentence.lower()# Very high boost if specific metric keywords are near the numberfor metric in specific_metrics:if metric in sentence_lower and re.search(r'\b' + re.escape(number) + r'\b.*\b' + re.escape(metric) + r'\b|\b' + re.escape(metric) + r'\b.*\b' + re.escape(number) + r'\b', sentence_lower, re.IGNORECASE):score += 100 # Huge boost if the specific metric is explicitly linked# Existing keyword matchingfor keyword in question_keywords:if keyword.lower() in sentence_lower:score += 1# Check if it's a cardinal entityfor ent in nlp(sentence).ents:if ent.text == number and ent.label_ == "CARDINAL":score += 2# Proximity to keywords (more advanced with spaCy)for keyword_doc in nlp(question):if not keyword_doc.is_stop and not keyword_doc.is_punct:for token in nlp(sentence):if token.lemma_ == keyword_doc.lemma_:distance = abs(token.i - span.start_token.i) # Using token index for distancescore += max(0, 1.0 - (distance / 20.0))scored_numbers.append((score, number, sentence))if not scored_numbers:return None# Sort and returnscored_numbers.sort(reverse=True, key=lambda x: x[0])return (scored_numbers[0][1], scored_numbers[0][2])def find_relevant_location_spacy(self, question, entities):"""Find the most relevant location entity based on question context using spaCy."""location_entities = [ent for ent in entities if ent[1] in ["GPE", "LOC"]]if not location_entities:return Nonequestion_doc = nlp(question)question_keywords = [token.lemma_ for token in question_doc if not token.is_stop and not token.is_punct]best_score = -1best_location = Nonefor loc_text, _, start_char, end_char in location_entities:score = 0span = nlp(self.current_context).char_span(start_char, end_char) # Need current_contextif span and span.sent:sentence = span.sent.textsentence_doc = nlp(sentence)for q_lemma in question_keywords:for s_token in sentence_doc:if s_token.lemma_ == q_lemma:score += 1# Boost if it's a recognized GPE (geo-political entity)for ent in sentence_doc.ents:if ent.text == loc_text and ent.label_ in ["GPE", "LOC"]:score += 2if score > best_score:best_score = scorebest_location = loc_textreturn best_locationdef find_answer_in_tables(self, question, tables):"""Search through extracted tables to find an answer to the question.Improved with better column type detection and keyword matching."""if not tables:return Nonequestion_keywords = self.extract_key_phrases(question)question_lower = question.lower()for table in tables:if not table:continue# Assuming the first row is headers if presentheaders = [self._clean_cell_content(cell).lower() for cell in table[0]] if table else []data_rows = table[1:] if len(table) > 1 else []# Determine column types (placeholder for now, needs implementation)column_types = self.detect_column_types(table)# ... (Rest of your table search logic would go here)# For now, just return a dummy answer if a table is found to avoid the error.# You'll need to implement the actual table search and answer extraction logic.# Example:if "president" in question_lower and "usa" in question_lower and headers and "name" in headers:name_col_idx = headers.index("name")# More complex logic needed to find relevant rowreturn "Placeholder: Found answer in table for president question."# Simple keyword match within table cells as a basic examplefor row_idx, row in enumerate(table):for cell_idx, cell_content in enumerate(row):cell_lower = cell_content.lower()if any(keyword in cell_lower for keyword in question_keywords):# This is very basic, a proper implementation would consider column headers# and question type to return a specific cell or a combination.if headers and cell_idx < len(headers):return f"Found '{cell_content}' under '{headers[cell_idx]}' in a table."else:return f"Found '{cell_content}' in a table."return Nonedef detect_column_types(self, table):"""Detects the type of data in each column (e.g., 'number', 'text', 'date').This is a placeholder and would need a robust implementation."""if not table or not table[0]:return []num_cols = len(table[0])column_types = ["text"] * num_cols # Default to text# Example: rudimentary detection for the first few rowsfor col_idx in range(num_cols):num_count = 0date_count = 0for row_idx in range(1, min(len(table), 5)): # Check first 5 data rowsif col_idx < len(table[row_idx]):cell_content = self._clean_cell_content(table[row_idx][col_idx])if re.match(r'^\d+(\.\d+)?$', cell_content):num_count += 1if re.match(r'\b\d{4}\b', cell_content) or re.match(r'\b(Jan|Feb|Mar)\w*\s+\d{1,2}(?:st|nd|rd|th)?(?:,\s+\d{4})?\b', cell_content, re.IGNORECASE):date_count += 1if num_count > 2: # Heuristic: if more than 2 numberscolumn_types[col_idx] = "number"elif date_count > 1: # Heuristic: if more than 1 datecolumn_types[col_idx] = "date"return column_types# --- Gradio Interface (as provided, assuming it will call agent correctly) ---# Define the Gradio interface if needed for testing outside the main app.# If this is part of a larger application, this might be handled differently.if __name__ == '__main__':agent = SuperSmartAgent() # Instantiate the agentdef chat_interface(question):response = agent(question) # The __call__ method handles the graph invocationreturn responseif os.getenv("RUN_GRADIO_APP", "false").lower() == "true":demo = gr.Interface(fn=chat_interface,inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),outputs="text",title="Super Smart Agent",description="An agent capable of answering questions, solving riddles, and generating Python code.")demo.launch()# Example usage for testing without Gradio:print("Testing SuperSmartAgent without Gradio:")my_agent = SuperSmartAgent()test_questions = ["What is the opposite of the word 'cold'?","How many planets are in our solar system?","Sort the list [5, 2, 8, 1]","What is the capital of France?","When was Albert Einstein born?","If I have 3 apples and you take 1, how many do I have?", # Riddle"What is the population of Tokyo?","What is the sum of 10 and 20?","gnitset a si sihT", # Reversed question"Who invented the telephone?"]for q in test_questions:print(f"\nQuestion: {q}")answer = my_agent(q)print(f"Answer: {answer}")290 unmodified lines291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366290 unmodified linesreturn list(set(key_phrases)) # Return unique phrasesdef general_reasoning_qa(self, state):question = state["question"]question_lower = question.lower()try:search_results = wikipedia.search(question, results=3)if not search_results:state["response"] = "Sorry, I couldn't find relevant information on Wikipedia."return statecontext = self.get_relevant_context(question, search_results)self.current_context = contextif not context:state["response"] = "Sorry, I couldn't find detailed relevant information."return statecontext = self.preprocess_context(context)tables = self.extract_tables_from_wikipedia(context)answer = self.extract_answer(question, context, tables)if answer and self.validate_answer(question, answer):state["response"] = answerreturn stateif not answer:question_keywords = self.extract_key_phrases(question)if question_keywords:sentences = re.split(r'(?<=[.!?])\s+', context) # Split more carefully to keep punctuation with sentencescored_sentences = []for sentence in sentences:sentence = sentence.strip()if not sentence:continuescore = 0sentence_lower = sentence.lower()for keyword in question_keywords:if keyword.lower() in sentence_lower:score += 1if score > 0:scored_sentences.append((score, sentence))if scored_sentences:scored_sentences.sort(key=lambda x: (-x[0], -len(x[1])))best_sentence = scored_sentences[0][1]if best_sentence.endswith('.') or best_sentence.endswith('!') or best_sentence.endswith('?'):state["response"] = best_sentenceelse:state["response"] = best_sentence + "."return statetry:first_page = self.wiki_wiki.page(search_results[0])if first_page.exists():summary = first_page.summary[:700] + "..." # Slightly larger summarystate["response"] = f"I couldn't find a specific answer, but here's some relevant information: {summary}"else:state["response"] = "No relevant information found."except Exception as e:state["response"] = f"I couldn't find a specific answer in the available information."except Exception as e:state["response"] = f"An error occurred while searching for information: {str(e)}"return state
app.py+60-574