from __future__ import annotations import os # Avoid the Node.js SSR proxy in hosted environments where it can terminate unexpectedly. os.environ["GRADIO_SSR_MODE"] = "false" import gradio as gr from document_orchestrator import orchestrate_all_active_tenants from google_sheets_service import GoogleSheetsConfigError, append_row_to_google_sheet try: import spaces # type: ignore[import-not-found] except ImportError: spaces = None custom_css = """ .cell-menu, .cell-menu-button { display: none !important; } """ def gpu_decorator(fn): if spaces is None: return fn return spaces.GPU(fn) @gpu_decorator def run_orchestrator_endpoint(api_key: str) -> dict: """Multi-tenant orchestration endpoint - processes all active tenants and their rules.""" expected_api_key = str(os.getenv("ORCHESTRATOR_API_KEY") or "").strip() provided_api_key = str(api_key or "").strip() if provided_api_key != expected_api_key: return { "ok": False, "error": "Unauthorized: invalid API key.", } model_name = os.getenv("OPENAI_MODEL", "gpt-4o") try: # Load all active tenants from Firebase return orchestrate_all_active_tenants( model=model_name, include_subfolders=True, send_to_sheet=True, ) except Exception as exc: return { "ok": False, "error": str(exc), } def build_app() -> gr.Blocks: with gr.Blocks(title="Procesador de Documentos") as demo: gr.Markdown("# Procesador de Comprobantes de Compra\nRevisa documentos Parsed/Modified y envia los seleccionados.") with gr.Accordion("Orquestador API - Multi Tenant", open=False): gr.Markdown("Endpoint publico para ejecutar escaneo + parseo + persistencia del orquestador en modo multi-tenant (carga todos los tenants activos de Firebase).") mt_orchestrator_api_key = gr.Textbox( label="API Key", type="password", value="", ) mt_orchestrator_button = gr.Button("Ejecutar orquestador (Multi Tenant)", variant="primary") mt_orchestrator_output = gr.JSON(label="Resultado orquestacion") mt_orchestrator_button.click( run_orchestrator_endpoint, inputs=[mt_orchestrator_api_key], outputs=[mt_orchestrator_output], api_name="orchestrate_all_tenants", ) return demo demo = build_app() if __name__ == "__main__": launch_kwargs = {"theme": gr.themes.Soft(), "show_error": True} # Spaces manages networking itself; local runs keep explicit host/port. if os.getenv("SPACE_ID"): try: demo.launch(css=custom_css, ssr_mode=False, **launch_kwargs) except TypeError: # Backward-compatible fallback if this Gradio build does not accept ssr_mode. demo.launch(css=custom_css, **launch_kwargs) else: try: demo.launch(css=custom_css, server_name="0.0.0.0", server_port=7860, ssr_mode=False, **launch_kwargs) except TypeError: demo.launch(css=custom_css, server_name="0.0.0.0", server_port=7860, **launch_kwargs)