Spaces:
Sleeping
Sleeping
fix
Browse files515 unmodified lines51651751851952052152212 unmodified lines53553653753853954054127 unmodified lines5695705715725735745755765775786 unmodified lines58558658758858959059159259359448 unmodified lines6436446456466476486494 unmodified lines65465565665765865966021 unmodified lines6826836846856866876886 unmodified lines6956966976986997007017027037047057067077083 unmodified lines7127137147157167177187 unmodified lines7267277287297307317327337347355 unmodified lines7417427437447457467477487497507517527537547557567577587597607617627636 unmodified lines770771772773774775776515 unmodified linesborder: 2px solid #d1d5db !important;margin-bottom: 16px !important;}"""with gr.Blocks(theme=gr.themes.Soft(), title="SmartDoc AI", css=css) as demo:12 unmodified linesfiles = gr.Files(label="Upload your files", file_types=definitions.ALLOWED_TYPES)question = gr.Textbox(label="Ask a question", lines=2, placeholder="Type your question here...")chat = gr.Chatbot(label="Answers", elem_id="chat-history", type="messages")submit_btn = gr.Button("Get Answer", variant="primary")processing_message = gr.HTML("", elem_id="processing-message", visible=False)doc_context_display = gr.Markdown("*Submit a question to see which document sections were referenced*", elem_classes="doc-context", visible=False)27 unmodified lines)try:if not question_text.strip():chat_history.extend([{"role": "user", "content": question_text},{"role": "assistant", "content": "Please enter a question."}])yield (chat_history,gr.update(visible=False),6 unmodified lines)returnif not uploaded_files:chat_history.extend([{"role": "user", "content": question_text},{"role": "assistant", "content": "Please upload at least one document."}])yield (chat_history,gr.update(visible=False),48 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style=\"background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);\">\n <span id=\"processing-msg\"></span>\n <span id=\"processing-timer\" style=\"opacity:0.8; margin-left:8px;\"></span>\n</div>''', visible=True))# After all chunks, show 100%yield (4 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style=\"background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);">\n <span id=\"processing-msg\"></span>\n <span id=\"processing-timer\" style=\"opacity:0.8; margin-left:8px;\"></span>\n</div>''', visible=True))# Stage 3: Building Retrieveryield (21 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style=\"background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);\">\n <span id=\"processing-msg\"></span>\n <span id=\"processing-timer\" style=\"opacity:0.8; margin-left:8px;\"></span>\n</div>''', visible=True))result = orchestrator.run_workflow(question=question_text, retriever=retriever)answer = result["draft_answer"]6 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style=\"background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);\">\n <span id=\"processing-msg\"></span>\n <span id=\"processing-timer\" style=\"opacity:0.8; margin-left:8px;\"></span>\n</div>''', visible=True))verification = result.get("verification_report", "No verification details available.")logger.info(f"Verification (internal):\n{verification}")chat_history.extend([{"role": "user", "content": question_text},{"role": "assistant", "content": f"**Answer:**\n{answer}"}])session_state.value["last_documents"] = retriever.invoke(question_text)yield (chat_history,3 unmodified linesgr.update(interactive=True),gr.update(interactive=True),gr.update(interactive=True),gr.update(value='''<div style=\"background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);">\n <span id="processing-msg"></span>\n <span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span>\n</div>''', visible=True))yield (chat_history,7 unmodified lines)except Exception as e:logger.error(f"Processing error: {e}", exc_info=True)chat_history.extend([{"role": "user", "content": question_text},{"role": "assistant", "content": f"Error: {str(e)}"}])yield (chat_history,gr.update(visible=False),5 unmodified linesgr.update(value="", visible=False))def refresh_context(chat_history):docs = session_state.value.get("last_documents", [])last_question = ""for msg in reversed(chat_history or []):if msg.get("role") == "user":last_question = msg.get("content", "")breakreturn format_document_context(docs, last_question)refresh_context_btn.click(fn=refresh_context,inputs=[chat],outputs=[doc_context_display])# Launch server - Compatible with both local and Hugging Face Spaces# HF Spaces sets SPACE_ID environment variableis_hf_space = os.environ.get("SPACE_ID") is not Nonedemo.queue()if is_hf_space:# Hugging Face Spaces configuration6 unmodified lineslogger.info(f"Launching Gradio on port {server_port}")logger.info(f"Access the app at: http://127.0.0.1:{server_port}")demo.launch(server_name="127.0.0.1", server_port=server_port, share=False)if __name__ == "__main__":main()515 unmodified lines51651751851952052152212 unmodified lines53553653753853954054127 unmodified lines5695705715725735745755766 unmodified lines58358458558658758858959048 unmodified lines6396406416426436446456466476484 unmodified lines65365465565665765865966066166221 unmodified lines6846856866876886896906916926936 unmodified lines7007017027037047057067077087097107117127137147153 unmodified lines7197207217227237247257267277287 unmodified lines7367377387397407417427435 unmodified lines7497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108116 unmodified lines818819820821822823824515 unmodified linesborder: 2px solid #d1d5db !important;margin-bottom: 16px !important;}"""with gr.Blocks(theme=gr.themes.Soft(), title="SmartDoc AI", css=css) as demo:12 unmodified linesfiles = gr.Files(label="Upload your files", file_types=definitions.ALLOWED_TYPES)question = gr.Textbox(label="Ask a question", lines=2, placeholder="Type your question here...")chat = gr.Chatbot(label="Answers", elem_id="chat-history")submit_btn = gr.Button("Get Answer", variant="primary")processing_message = gr.HTML("", elem_id="processing-message", visible=False)doc_context_display = gr.Markdown("*Submit a question to see which document sections were referenced*", elem_classes="doc-context", visible=False)27 unmodified lines)try:if not question_text.strip():chat_history.append({"role": "user", "content": question_text})chat_history.append({"role": "assistant", "content": "Please enter a question."})yield (chat_history,gr.update(visible=False),6 unmodified lines)returnif not uploaded_files:chat_history.append({"role": "user", "content": question_text})chat_history.append({"role": "assistant", "content": "Please upload at least one document."})yield (chat_history,gr.update(visible=False),48 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style="background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);"><span id="processing-msg"></span><span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span></div>''', visible=True))# After all chunks, show 100%yield (4 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style="background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);"><span id="processing-msg"></span><span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span></div>''', visible=True))# Stage 3: Building Retrieveryield (21 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style="background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);"><span id="processing-msg"></span><span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span></div>''', visible=True))result = orchestrator.run_workflow(question=question_text, retriever=retriever)answer = result["draft_answer"]6 unmodified linesgr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False),gr.update(value='''<div style="background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);"><span id="processing-msg"></span><span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span></div>''', visible=True))verification = result.get("verification_report", "No verification details available.")logger.info(f"Verification (internal):\n{verification}")# Do not display verification to user, only use internallychat_history.append({"role": "user", "content": question_text})chat_history.append({"role": "assistant", "content": f"**Answer:**\n{answer}"})session_state.value["last_documents"] = retriever.invoke(question_text)yield (chat_history,3 unmodified linesgr.update(interactive=True),gr.update(interactive=True),gr.update(interactive=True),gr.update(value='''<div style="background:#fff; border-radius:8px; padding:18px 24px; margin-top:32px; color:#1e293b; font-size:1.2em; font-weight:600; box-shadow:0 2px 8px rgba(0,0,0,0.04);"><span id="processing-msg"></span><span id="processing-timer" style="opacity:0.8; margin-left:8px;"></span></div>''', visible=True))yield (chat_history,7 unmodified lines)except Exception as e:logger.error(f"Processing error: {e}", exc_info=True)chat_history.append({"role": "user", "content": question_text})chat_history.append({"role": "assistant", "content": f"Error: {str(e)}"})yield (chat_history,gr.update(visible=False),5 unmodified linesgr.update(value="", visible=False))submit_btn.click(fn=process_question,inputs=[question, files, chat],outputs=[chat, doc_context_display, refresh_context_btn, submit_btn, question, files, example_dropdown, processing_message],queue=True,show_progress=True)def refresh_context():docs = session_state.value.get("last_documents", [])last_question = ""for msg in reversed(chat.value or []):if msg["role"] == "user":last_question = msg["content"]breakreturn format_document_context(docs, last_question)refresh_context_btn.click(fn=refresh_context,inputs=[],outputs=[doc_context_display])def load_example(example_key):if not example_key or example_key not in EXAMPLES:return [], "", "Select a valid example from the dropdown above"ex_data = EXAMPLES[example_key]question_text = ex_data["question"]file_paths = ex_data["file_paths"]import tempfiletemp_dir = tempfile.mkdtemp()copied_files = []file_info_text = f"Loaded: {example_key}\n\n"for source_file_path in file_paths:abs_source = os.path.abspath(source_file_path)if os.path.exists(abs_source):filename = os.path.basename(abs_source)temp_file_path = os.path.join(temp_dir, filename)shutil.copy2(abs_source, temp_file_path)copied_files.append(temp_file_path)file_size_mb = os.path.getsize(temp_file_path) / (1024 * 1024)file_info_text += f"{filename} ({file_size_mb:.2f} MB)\n"else:file_info_text += f"{source_file_path} not found\n"if not copied_files:return [], "", "Could not load example files"return copied_files, question_text, file_info_textexample_dropdown.change(fn=load_example,inputs=[example_dropdown],outputs=[files, question, loaded_file_info])# Launch server - Compatible with both local and Hugging Face Spaces# HF Spaces sets SPACE_ID environment variableis_hf_space = os.environ.get("SPACE_ID") is not Nonedemo.queue()if is_hf_space:# Hugging Face Spaces configuration6 unmodified lineslogger.info(f"Launching Gradio on port {server_port}")logger.info(f"Access the app at: http://127.0.0.1:{server_port}")demo.launch(server_name="127.0.0.1", server_port=server_port, share=False)if __name__ == "__main__":main()
main.py+77-29