Spaces:
Sleeping
Sleeping
fix
Browse files11 unmodified lines1213141516171 unmodified line192021222324577 unmodified lines60260360460560660760860961061161261321 unmodified lines635636637638639640641223 unmodified lines86586686786886987087187287387487587687787887988088188288388488588688788888915 unmodified lines90590690790890991091111 unmodified linesfrom datetime import datetimeimport timeimport randomfrom content_analyzer.document_parser import DocumentProcessorfrom search_engine.indexer import RetrieverBuilder1 unmodified linefrom configuration import definitions, parameters# Example data for demoEXAMPLES = {"Generative AI and Jobs": {577 unmodified linessetInterval(tick, 500);'''with gr.Blocks(theme=gr.themes.Soft(), title="SmartDoc AI") as demo:gr.Markdown("### SmartDoc AI - Document Q&A", elem_classes="app-title")gr.Markdown("Upload your documents and ask questions. Answers will appear below, just like a chat.", elem_classes="app-description")gr.Markdown("---")# Examples dropdownexample_dropdown = gr.Dropdown(label="Quick Start - Choose an Example",choices=list(EXAMPLES.keys()),21 unmodified lines"session_start": datetime.now().strftime("%Y-%m-%d %H:%M")})def process_question(question_text, uploaded_files, chat_history):chat_history = chat_history or []yield (chat_history,223 unmodified linesreturn [], "", "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,15 unmodified linesserver_port = _find_open_port(configured_port)logger.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__":11 unmodified lines121314151617181 unmodified line20212223242526272829303132333435363738394041577 unmodified lines61962062162262362462562662762862963063163263363421 unmodified lines656657658659660661662663223 unmodified lines88788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893915 unmodified lines95595695795895996096111 unmodified linesfrom datetime import datetimeimport timeimport randomfrom collections import defaultdict, dequefrom content_analyzer.document_parser import DocumentProcessorfrom search_engine.indexer import RetrieverBuilder1 unmodified linefrom configuration import definitions, parameters# Rate limiting configuration - 3 requests per 60 seconds per IPWINDOW_S = 3600MAX_CALLS = 3_calls = defaultdict(deque) # ip -> timestampsdef rate_limit(request):ip = getattr(request.client, "host", "unknown")now = time.time()q = _calls[ip]while q and (now - q[0]) > WINDOW_S:q.popleft()if len(q) >= MAX_CALLS:raise gr.Error(f"Rate limit: {MAX_CALLS} requests per {WINDOW_S}s. Please wait.")q.append(now)# Example data for demoEXAMPLES = {"Generative AI and Jobs": {577 unmodified linessetInterval(tick, 500);'''# 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 Nonewith gr.Blocks(title="SmartDoc AI") as demo:gr.Markdown("### SmartDoc AI - Document Q&A", elem_classes="app-title")gr.Markdown("Upload your documents and ask questions. Answers will appear below, just like a chat.", elem_classes="app-description")gr.Markdown("---")# Examples dropdown - visible for both local and HF Spacesexample_dropdown = gr.Dropdown(label="Quick Start - Choose an Example",choices=list(EXAMPLES.keys()),21 unmodified lines"session_start": datetime.now().strftime("%Y-%m-%d %H:%M")})def process_question(question_text, uploaded_files, chat_history, request: gr.Request):rate_limit(request)chat_history = chat_history or []yield (chat_history,223 unmodified linesreturn [], "", "Select a valid example from the dropdown above"ex_data = EXAMPLES[example_key]question_text = ex_data["question"]file_names = ex_data["file_paths"]# Try to download from HF dataset if on Spacesif is_hf_space:try:from huggingface_hub import hf_hub_downloadcopied_files = []file_info_text = f"✅ Loaded: {example_key}\n\n"for file_path in file_names:filename = os.path.basename(file_path)try:local_path = hf_hub_download(repo_id="TilanTAB/smartdoc-samples",repo_type="dataset",filename=filename,)copied_files.append(local_path)file_size_mb = os.path.getsize(local_path) / (1024 * 1024)file_info_text += f"📄 {filename} ({file_size_mb:.2f} MB)\n"except Exception as e:logger.error(f"Failed to download {filename}: {e}")file_info_text += f"❌ {filename} - Download failed\n"if not copied_files:return [], "", "❌ Could not load example files from dataset"return copied_files, question_text, file_info_textexcept ImportError:return [], "", "❌ huggingface_hub not installed"else:# Local mode - use files from samples directoryimport tempfiletemp_dir = tempfile.mkdtemp()copied_files = []file_info_text = f"Loaded: {example_key}\n\n"for source_file_path in file_names: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,15 unmodified linesserver_port = _find_open_port(configured_port)logger.info(f"Launching Gradio on port {server_port}")logger.info(f"Access the app at: http://127.0.0.1:{server_port}")demo.launch(theme=gr.themes.Soft(), server_name="127.0.0.1", server_port=server_port, share=False, css=css, js=js)if __name__ == "__main__":
main.py+73-23