Spaces:
Runtime error
Runtime error
Update app.py
Browse files6 unmodified lines78910111213178 unmodified lines192193194195196197100 unmodified lines2982993003013023033043056 unmodified lines3123133143153163173 unmodified lines32132232332432532632732832933033133255 unmodified lines388389390391392393394395396397398399400401402403404405406407408409410112 unmodified lines52352452552652752852953053153253353453566 unmodified lines6026036046056066076 unmodified linesimport torch.nn.functional as Fimport torch.optim as optimimport gradio as grfrom datetime import datetime # Added from app_combined.py# Removed: import kagglehub, pandas, tqdm178 unmodified linesdef perform_web_search(query):print(f"**Web Search Triggered for:** '{query}'")query_lower = query.lower()if "capital of singapore" in query_lower:100 unmodified linestext = re.sub(r"\s+([,.!?;:])", r"\1", text)text = text.strip()if not text or check_repetition(text):return "I couldn't generate a stable response. Please try a shorter or clearer prompt."return text6 unmodified lineslast_user_message, last_ai_response = history[-1][0], history[-1][1]file_context_text = ""file_match = re.search(r"\(Attached: (.*?)\)", last_user_message)if file_match:file_name = file_match.group(1)3 unmodified linesclean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()search_context_text = ""if "?" in clean_user_message or any(clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]):search_context_text = perform_web_search(clean_user_message)print(f"\n--- FEEDBACK RECEIVED ---")print(f"Rating: {rating}")print(f"User Prompt: '{last_user_message}'")55 unmodified linesconversation_context = ""# In the UI flow, the user message is already in history, so we use history[:-1] as context# If this function is called directly (e.g., from the API wrapper), history might not be updated yet.# We rely on the calling function (like `chat_submit_api` or the `then` block) to ensure history is ready.context_history = history[:-1] if not is_instruction else historyif context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):last_user, last_ai = context_history[-1][0], context_history[-1][1]conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"search_context_text = ""search_needed = bool(web_search_enabled) or "?" in clean_user_message or any(clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"])if search_needed:search_context_text = perform_web_search(clean_user_message)display_search_result = f"π **Search Result Used:** {search_context_text}" if search_context_text else "π **No Search Performed or Result Found.**"final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_promptreply = generate_response(112 unmodified linesclear.click(lambda: [], None, chat, queue=False)def feedback_good_wrapper(history_state):# NOTE: This wrapper in app.py seems to have been intended for a UI button# but the logic for online_update is now handled in process_feedback/feedback_good.# It's kept for completeness but the UI-based feedback is not fully defined here.return process_feedback(history_state, "Good Response")def feedback_bad_wrapper(history_state):# NOTE: Same as above.return process_feedback(history_state, "Bad Response")# --- Public API Endpoints (from app.py and app_combined.py) ---66 unmodified linesif __name__ == "__main__":# Using the demo.queue().launch() from app.pydemo.queue(api_open=True).launch(ssr_mode=False)# The server_name and server_port from app_combined.py's launch call are not needed# for the default Gradio launch, but the combined app will run on a similar port.6 unmodified lines78910111213178 unmodified lines192193194195196197198100 unmodified lines2993003013023033043053063073086 unmodified lines3153163173183193203213 unmodified lines32532632732832933033133233355 unmodified lines389390391392393394395396397398399400401402403404405406407408409410411412413112 unmodified lines52652752852953053153253353466 unmodified lines6016026036046 unmodified linesimport torch.nn.functional as Fimport torch.optim as optimimport gradio as grfrom datetime import datetime# Removed: import kagglehub, pandas, tqdm178 unmodified linesdef perform_web_search(query):"""MOCK WEB SEARCH: Only returns results for hard-coded queries."""print(f"**Web Search Triggered for:** '{query}'")query_lower = query.lower()if "capital of singapore" in query_lower:100 unmodified linestext = re.sub(r"\s+([,.!?;:])", r"\1", text)text = text.strip()# CRITICAL FIX 1: If the generation fails or is repetitive, return a default silly message# instead of the "I couldn't generate a stable response" placeholder.if not text or check_repetition(text):return "I got lost in the data tubes! Perhaps ask me something a little sillier? π€ͺ"return text6 unmodified lineslast_user_message, last_ai_response = history[-1][0], history[-1][1]file_context_text = ""# Note: The JS client injects file names using special markers, which are needed to determine context.file_match = re.search(r"\(Attached: (.*?)\)", last_user_message)if file_match:file_name = file_match.group(1)3 unmodified linesclean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()# We assume search_context_text is empty here because the API for feedback doesn't pass search_enabledsearch_context_text = ""print(f"\n--- FEEDBACK RECEIVED ---")print(f"Rating: {rating}")print(f"User Prompt: '{last_user_message}'")55 unmodified linesconversation_context = ""context_history = history[:-1] if not is_instruction else historyif context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):last_user, last_ai = context_history[-1][0], context_history[-1][1]conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"search_context_text = ""# CRITICAL FIX 2: Only check for search need IF the web search is explicitly enabled (from the checkbox).search_needed = bool(web_search_enabled) and ("?" in clean_user_message or any(clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]))if search_needed:search_context_text = perform_web_search(clean_user_message)display_search_result = f"π **Search Result Used:** {search_context_text}" if search_context_text else "π **No Search Performed or Result Found.**"# If search was NOT enabled, overwrite the message to be definitively "No Search Performed."if not web_search_enabled:display_search_result = "π **Web Search Disabled by Menu.**"final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_promptreply = generate_response(112 unmodified linesclear.click(lambda: [], None, chat, queue=False)def feedback_good_wrapper(history_state):return process_feedback(history_state, "Good Response")def feedback_bad_wrapper(history_state):return process_feedback(history_state, "Bad Response")# --- Public API Endpoints (from app.py and app_combined.py) ---66 unmodified linesif __name__ == "__main__":# Using the demo.queue().launch() from app.pydemo.queue(api_open=True).launch(ssr_mode=False)
app.py+16-19