te-assistant / app.py
MustafaHussein's picture
retrieved fixed app.py
ec94e83
Raw History Blame Contribute Delete
13.6 kB
"""Telecom Egypt Virtual Assistant: FastAPI backend + Gradio UI (Hugging Face ZeroGPU / local / on-prem).
python app.py -> UI at http://localhost:7860, REST API under /api, docs at /docs
"""
import core.gpu # noqa: F401 (must be imported before torch)
from core.gpu import gpu
import json
import os
import threading
import time
from typing import Literal, Optional
import gradio as gr
from fastapi import APIRouter, File, HTTPException, UploadFile
from fastapi.responses import FileResponse
from pydantic import BaseModel
import config
from core import asr, llm, pipeline, tts
from core.pipeline import Engine
from core.rag import TEIndex
# ZeroGPU refuses to start a Space unless at least one @spaces.GPU function is registered
# at import time. This tiny top-level function guarantees that (it is never called).
# On non-ZeroGPU hosts `gpu` is a no-op decorator, so it does nothing.
@gpu
def _zerogpu_registration() -> bool:
return True
# --------------------------------------------------------------------------------------
# Lazy engine (embedder + indexes)
# --------------------------------------------------------------------------------------
_engine: Optional[Engine] = None
_engine_lock = threading.Lock()
def get_engine() -> Engine:
global _engine
with _engine_lock:
if _engine is None:
_engine = Engine()
return _engine
_warmed = False
def warmup() -> None:
global _warmed
if _warmed:
return
_warmed = True
for name, fn in (("retrieval", get_engine), ("asr", asr.warmup), ("tts", tts.warmup)):
try:
t = time.time()
fn()
print(f"[warmup] {name} ready in {time.time() - t:.1f}s")
except Exception as e: # noqa: BLE001
print(f"[warmup] {name} skipped: {e}")
def health_md() -> str:
msgs = []
if not TEIndex.exists(config.INDEX_DIR):
msgs.append("⚠️ **te.eg index not found.** Run `scripts/scrape_te.py` then `scripts/build_index.py` "
"(only your uploaded documents can be searched until then).")
if not asr.available():
msgs.append(f"⚠️ **No sherpa-onnx model** in `{config.SHERPA_DIR}`: voice input is disabled.")
if config.OLLAMA_BASE_URL.startswith("https://ollama.com") and not config.OLLAMA_API_KEY:
msgs.append("⚠️ **OLLAMA_API_KEY is not set**: the LLM cannot answer yet.")
return "\n\n".join(msgs)
def _sid(req: Optional[gr.Request]) -> str:
return getattr(req, "session_hash", None) or "local"
# --------------------------------------------------------------------------------------
# One chat turn (shared by voice and text)
# --------------------------------------------------------------------------------------
def _turn(question: str, mode: str, history: list, req, pre: str = ""):
"""Generator yielding (history, audio_update, status_markdown)."""
sid = _sid(req)
past = list(history or [])
history = list(past)
history.append({"role": "user", "content": ("🎤 " if mode == "voice" else "") + question})
history.append({"role": "assistant", "content": "…"})
bits = [pre] if pre else []
yield history, gr.update(), " · ".join(bits + ["🔎 searching sources…"])
t0 = time.time()
try:
prep = pipeline.prepare(get_engine(), question, sid, past, mode)
except Exception as e: # noqa: BLE001
history[-1]["content"] = f"⚠️ Retrieval error: {e}"
yield history, gr.update(), " · ".join(bits)
return
bits.append(f"lang **{prep.lang}**{' (Egyptian)' if prep.egyptian else ''}")
bits.append(f"retrieval {time.time() - t0:.2f}s")
if prep.hits:
bits.append(f"confidence **{pipeline.confidence(prep.top_score)}** ({prep.top_score:.2f}, {len(prep.hits)} passages)")
if prep.messages is None: # nothing relevant: do not let the LLM guess
answer = llm.NO_ANSWER[prep.lang]
history[-1]["content"] = answer
bits.append("no relevant source")
else:
t1, last, acc = time.time(), 0.0, ""
try:
for piece in llm.stream_chat(prep.messages):
acc += piece
if time.time() - last > 0.08:
last = time.time()
history[-1]["content"] = llm.strip_think(acc) or "…"
yield history, gr.update(), " · ".join(bits + ["✍️ answering…"])
except llm.LLMError as e:
history[-1]["content"] = f"⚠️ {e}"
yield history, gr.update(), " · ".join(bits)
return
answer = llm.strip_think(acc).strip()
if not answer:
history[-1]["content"] = "⚠️ The model returned an empty answer. Please try again."
yield history, gr.update(), " · ".join(bits)
return
sources_md, _ = pipeline.format_sources(answer, prep.hits)
history[-1]["content"] = answer + sources_md
bits.append(f"LLM {time.time() - t1:.1f}s")
audio = gr.update()
if mode == "voice":
yield history, gr.update(), " · ".join(bits + ["🔊 generating speech…"])
t2 = time.time()
try:
path = tts.synthesize(answer)
except Exception as e: # noqa: BLE001
path = None
bits.append(f"TTS failed: {e}")
if path:
history.append({"role": "assistant", "content": {"path": path}}) # playable inside the chat history
audio = path # and autoplays below the chat
bits.append(f"TTS {time.time() - t2:.1f}s")
yield history, audio, " · ".join(bits)
def on_text(text, history, request: gr.Request):
text = (text or "").strip()
if not text:
yield history, gr.update(), gr.update(), gr.update(), ""
return
for h, a, s in _turn(text, "text", history, request):
yield h, "", None, a, s
def on_voice(audio_path, history, asr_lang, denoise, request: gr.Request):
if not audio_path:
yield history, gr.update(), gr.update(), gr.update(), ""
return
yield history, gr.update(), gr.update(), gr.update(), "🎙️ transcribing…"
try:
res = asr.transcribe(audio_path, asr_lang, denoise)
except Exception as e: # noqa: BLE001
yield history, "", None, gr.update(), f"⚠️ ASR error: {e}"
return
if not res["text"]:
yield history, "", None, gr.update(), "🔇 No speech detected. Please try again."
return
pre = f"ASR `{res['model']}` {res['seconds']}s for {res['audio_seconds']}s audio"
for h, a, s in _turn(res["text"], "voice", history, request, pre):
yield h, "", None, a, s
# ---- documents -------------------------------------------------------------------------
def _docs_md(sid: str) -> str:
files = get_engine().user_files(sid)
return ("**Indexed for this chat:** " + ", ".join(files)) if files else "_No documents uploaded yet._"
def on_upload(paths, request: gr.Request):
sid = _sid(request)
if not paths:
return _docs_md(sid)
names = [p if isinstance(p, str) else getattr(p, "name", str(p)) for p in paths]
return "\n\n".join(get_engine().add_documents(sid, names)) + "\n\n" + _docs_md(sid)
def on_clear_docs(request: gr.Request):
get_engine().clear_documents(_sid(request))
return _docs_md(_sid(request)), None
def on_like(evt: gr.LikeData):
try:
config.FEEDBACK_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(config.FEEDBACK_PATH, "a", encoding="utf-8") as f:
f.write(json.dumps({"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "liked": evt.liked,
"index": evt.index, "value": evt.value}, ensure_ascii=False, default=str) + "\n")
except Exception: # noqa: BLE001
pass
# --------------------------------------------------------------------------------------
# Gradio UI
# --------------------------------------------------------------------------------------
CSS = """
#chat p, #chat li, #chat span, #chat td { unicode-bidi: plaintext; }
.gradio-container { max-width: 1250px !important; }
"""
EXAMPLES = [
"ما هي باقات الإنترنت المنزلي المتاحة؟",
"How can I pay my landline bill online?",
"ازاي أعرف رصيد الإنترنت بتاعي؟",
"عايز أقدم على خط أرضي جديد، أعمل إيه؟",
]
FILE_TYPES = [".pdf", ".docx", ".txt", ".md", ".html", ".htm", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"]
with gr.Blocks(title="Telecom Egypt Assistant", theme=gr.themes.Soft(), css=CSS) as demo:
gr.Markdown("# 📞 Telecom Egypt Virtual Assistant\n**المساعد الذكي للمصرية للاتصالات** · "
"ask by voice or text, in Arabic, English or Egyptian dialect. Answers are grounded in te.eg "
"and your own documents, with sources.")
health = gr.Markdown(health_md())
with gr.Row():
with gr.Column(scale=3):
chat = gr.Chatbot(type="messages", height=520, elem_id="chat", show_copy_button=True,
label="Conversation / المحادثة",
placeholder="Ask about Telecom Egypt services · اسأل عن خدمات المصرية للاتصالات")
with gr.Row():
txt = gr.Textbox(placeholder="Type your question… / اكتب سؤالك…", show_label=False,
container=False, scale=6)
send = gr.Button("Send", variant="primary", scale=1)
mic = gr.Audio(sources=["microphone"], type="filepath", format="wav",
label="🎤 Speak: the answer will be spoken back / تحدث وسيتم الرد صوتياً")
speak = gr.Audio(label="🔊 Last spoken answer", autoplay=True, interactive=False, type="filepath")
gr.Examples(examples=[[e] for e in EXAMPLES], inputs=[txt], label="Try / جرّب")
with gr.Column(scale=1):
gr.Markdown("### Voice settings")
asr_lang = gr.Dropdown([("Auto-detect", "auto"), ("العربية", "ar"), ("English", "en")],
value="auto", label="Speech language (Whisper-type models)")
denoise = gr.Checkbox(value=True, label="Noise reduction (for noisy recordings)")
gr.Markdown("### Your documents")
files = gr.File(file_count="multiple", file_types=FILE_TYPES, type="filepath",
label="PDF · DOCX · TXT · HTML · images")
docs = gr.Markdown("_No documents uploaded yet._")
clear_docs = gr.Button("Clear my documents", size="sm")
gr.Markdown("### Last answer details")
status = gr.Markdown()
clear_chat = gr.Button("Clear chat", size="sm")
outs = [chat, txt, mic, speak, status]
txt.submit(on_text, [txt, chat], outs)
send.click(on_text, [txt, chat], outs)
mic.stop_recording(on_voice, [mic, chat, asr_lang, denoise], outs)
files.upload(on_upload, [files], [docs])
clear_docs.click(on_clear_docs, None, [docs, files])
clear_chat.click(lambda: ([], "", None, None, ""), None, outs)
chat.like(on_like, None, None)
demo.load(health_md, None, health)
demo.queue(default_concurrency_limit=8)
# --------------------------------------------------------------------------------------
# FastAPI: REST endpoints (integration, notebook, benchmarking) + the Gradio UI at "/"
# --------------------------------------------------------------------------------------
api = APIRouter()
class AskIn(BaseModel):
question: str
session_id: Optional[str] = None
mode: Literal["text", "voice"] = "text"
class TTSIn(BaseModel):
text: str
@api.get("/api/health")
def health_endpoint():
return {"te_index": TEIndex.exists(config.INDEX_DIR), "asr": asr.available(),
"asr_model": asr.model_type() if asr.available() else None,
"llm": {"base_url": config.OLLAMA_BASE_URL, "model": config.OLLAMA_MODEL,
"key_set": bool(config.OLLAMA_API_KEY)}}
@api.post("/api/ask")
def ask(body: AskIn):
try:
return pipeline.answer_once(get_engine(), body.question, body.session_id or "api", body.mode)
except llm.LLMError as e:
raise HTTPException(502, str(e))
@api.post("/api/transcribe")
def transcribe_endpoint(file: UploadFile = File(...), language: str = "auto", denoise: bool = True):
suffix = os.path.splitext(file.filename or "")[1] or ".wav"
tmp = config.TMP_DIR / f"upload_{int(time.time() * 1000)}{suffix}"
tmp.write_bytes(file.file.read())
try:
return asr.transcribe(str(tmp), language, denoise)
except asr.ASRError as e:
raise HTTPException(400, str(e))
finally:
tmp.unlink(missing_ok=True)
@api.post("/api/tts")
def tts_endpoint(body: TTSIn):
path = tts.synthesize(body.text)
if not path:
raise HTTPException(400, "Nothing to synthesize.")
return FileResponse(path, media_type="audio/wav")
if os.getenv("TE_WARMUP", "1") == "1":
warmup()
# Let Gradio start and own the server: on ZeroGPU the platform hooks Gradio's launch() to
# detect @spaces.GPU functions. ssr_mode=False avoids the Node.js SSR process on PORT 7861.
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", ssr_mode=False, prevent_thread_lock=True)
demo.app.include_router(api) # /api/ask, /api/transcribe, /api/tts, /api/health
demo.block_thread()