Spaces:
Sleeping
Sleeping
Download gradio_app.py from Catal/docSpaceSearch: direct link, hf CLI and curl.
- Browser
- Download file 3.52 kB
-
https://huggingface.co/spaces/Catal/docSpaceSearch/resolve/main/gradio_app.py
- Command line
-
hf download hf://spaces/Catal/docSpaceSearch/gradio_app.py
-
curl -L -o gradio_app.py https://huggingface.co/spaces/Catal/docSpaceSearch/resolve/main/gradio_app.py
3.52 kB
| """Entry point for a Hugging Face Space with the free Gradio SDK (the Docker SDK is paid). | |
| The Space runs `python gradio_app.py`. Gradio's own server (`launch()`) serves: | |
| * the service's API — /health, /search, /index, /refresh (see app/main.py), registered first; | |
| * a small page at / to check the index and try a search. | |
| Launching through Gradio matters on ZeroGPU hardware: the runtime only reports a healthy start-up | |
| from `launch()`. Nothing uses the GPU — embeddings run on CPU. | |
| """ | |
| from __future__ import annotations | |
| # On ZeroGPU hardware the `spaces` package must be imported before anything touches torch, and the | |
| # runtime refuses to start without at least one @spaces.GPU function. This one is never called. | |
| try: | |
| import spaces | |
| def _zero_gpu_placeholder() -> bool: | |
| return True | |
| except ImportError: # CPU Basic, Docker or local runs | |
| pass | |
| import hmac | |
| import os | |
| import gradio as gr | |
| from app.main import create_app | |
| api = create_app(sync_on_start=False) # Gradio runs the server: the sync is started below | |
| index = api.state.index | |
| sync = api.state.sync | |
| API_PATHS = {"/health", "/search", "/index", "/refresh"} | |
| # The API's routes go first in Gradio's app, ahead of Gradio's own. | |
| API_ROUTES = [route for route in api.routes if getattr(route, "path", None) in API_PATHS] | |
| def status() -> str: | |
| stats = index.stats | |
| state = "gata" if sync.ready or stats["documents"] else "se încarcă" | |
| lines = [ | |
| f"**Stare:** {state} · **documente:** {stats['documents']} · **fragmente:** {stats['chunks']}", | |
| f"**Ultima sincronizare:** {sync.last_sync or '—'}", | |
| ] | |
| if not (sync.app_url and sync.secret): | |
| lines.append("**Configurare:** lipsesc `APP_URL` sau `RAG_SECRET` (Settings → Variables and secrets).") | |
| if sync.last_error: | |
| lines.append(f"**Ultima eroare:** `{sync.last_error}`") | |
| return "\n\n".join(lines) | |
| def try_search(query: str, secret: str) -> str: | |
| expected = os.environ.get("RAG_SECRET", "") | |
| if not expected or not hmac.compare_digest(secret.encode(), expected.encode()): | |
| return "Secret greșit (RAG_SECRET)." | |
| if not query.strip(): | |
| return "Scrieți o întrebare." | |
| results = index.search(query, 6) | |
| if not results: | |
| return "Niciun rezultat." | |
| return "\n\n".join( | |
| f"**{i + 1}. [{r['title']}{', ' + r['cite'] if r['cite'] else ''}]({os.environ.get('APP_URL', '')}{r['url']})**" | |
| f" · scor {r['score']}\n\n{r['text'][:400]}" | |
| for i, r in enumerate(results) | |
| ) | |
| with gr.Blocks(title="Căutare documente") as ui: | |
| gr.Markdown("## Serviciul de căutare al asistentului\nIndexul se reconstruiește din exportul aplicației.") | |
| state = gr.Markdown() | |
| gr.Button("Reîmprospătează starea").click(status, outputs=state) | |
| with gr.Row(): | |
| query = gr.Textbox(label="Întrebare de test", scale=3) | |
| secret = gr.Textbox(label="RAG_SECRET", type="password", scale=1) | |
| output = gr.Markdown() | |
| gr.Button("Caută", variant="primary").click(try_search, inputs=[query, secret], outputs=output) | |
| ui.load(status, outputs=state) # current state on every page load, not the one at start-up | |
| APP_KWARGS = {"routes": API_ROUTES} | |
| if __name__ == "__main__": | |
| sync.start() | |
| ui.launch( | |
| server_name="0.0.0.0", | |
| server_port=int(os.environ.get("PORT", "7860")), | |
| # No server-side rendering: it would start a separate Node server on port 7860. | |
| ssr_mode=False, | |
| app_kwargs=APP_KWARGS, | |
| ) |