Spaces:
Running on Zero

te-assistant / README.md
MustafaHussein's picture
Notebook, README, threshold and confidence fixes
e164e80
|
Raw History Blame Contribute Delete
8.13 kB
---
title: Telecom Egypt Virtual Assistant
emoji: πŸ“ž
colorFrom: red
colorTo: purple
sdk: gradio
sdk_version: 5.29.0
python_version: "3.10"
app_file: app.py
pinned: false
---
# Telecom Egypt Virtual Assistant (POC)
**Live demo:** https://huggingface.co/spaces/MustafaHussein/te-assistant
Voice + text assistant that answers customer questions in **Arabic, English and Egyptian dialect**, grounded in
**te.eg** and in documents the user uploads, with **source citations**. Voice in β†’ ASR β†’ RAG β†’ LLM β†’ TTS β†’ spoken
answer *and* text. Text in β†’ text answer.
```
mic ──► sherpa-onnx ASR ─┐
β”œβ”€β–Ί language/dialect detect ─► multilingual-e5 ─► FAISS (te.eg) ┐
text β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ session index ─┴─► top passages
uploads (PDF/DOCX/TXT/HTML/image) ─► parse / EasyOCR ─► chunk ─► e5 ─► session index β”‚
β–Ό
chat (text + citations) ◄── Ollama LLM API (answer only from passages, cite [n])
spoken reply (MMS-TTS) ◄── only when the question came by voice
```
| Layer | Choice |
|---|---|
| UI + API | Gradio mounted on FastAPI (`/` UI, `/api/*` REST, `/docs` OpenAPI) |
| ASR | sherpa-onnx (CPU), your local weights, + high-pass filter, optional noise reduction, silence trim |
| Embeddings | `intfloat/multilingual-e5-small` (Arabic ↔ English cross-lingual retrieval) |
| Vector store | FAISS (te.eg, prebuilt) + in-memory numpy index per chat session (uploads) |
| LLM | Ollama API: Ollama Cloud now, your own Ollama server on-prem (env vars only) |
| TTS | `facebook/mms-tts-ara` / `mms-tts-eng` (ZeroGPU when available, CPU fallback) |
| OCR | EasyOCR `ar`+`en` |
## 1. Prepare the knowledge base (run on your machine)
```bash
pip install -r requirements.txt
python scripts/scrape_te.py --max-pages 40 # trial run; open data/te_corpus.jsonl and check it
python scripts/scrape_te.py --max-pages 600 # real crawl (add --render if pages come back empty)
python scripts/build_index.py # -> data/index/te.faiss + te_meta.json
```
Commit `data/te_corpus.jsonl` and `data/index/` so the Space needs no scraping at runtime.
## 2. Add the ASR weights
Copy your sherpa-onnx model files into `models/sherpa/`: `tokens.txt` plus either
`*encoder*.onnx` + `*decoder*.onnx` (+ `*joiner*.onnx` for a transducer) or a single `model.onnx`.
The family is auto-detected; force it with `SHERPA_MODEL_TYPE=whisper|transducer|nemo_ctc|paraformer`
(set `SHERPA_STREAMING=1` only for a streaming transducer). `int8` files are preferred when present.
## 3. Run locally
```bash
export OLLAMA_API_KEY=... # Ollama Cloud key
export OLLAMA_MODEL=gpt-oss:120b # any model your account serves; pick one that handles Arabic well
python app.py # http://localhost:7860 (API docs: /docs)
```
Needs `ffmpeg` and `libsndfile` on the system (see `packages.txt`).
## 4. Deploy on Hugging Face (ZeroGPU)
1. Create a **Gradio** Space with **ZeroGPU** hardware and push this folder (`.onnx` weights go through LFS/Xet).
2. Settings β†’ **Secrets**: `OLLAMA_API_KEY`. **Variables**: `OLLAMA_MODEL` (optionally `MIN_SCORE`, `SHERPA_MODEL_TYPE`).
3. In `requirements.txt` keep `torch` on a version ZeroGPU supports (check the HF ZeroGPU docs).
ZeroGPU is used for TTS; ASR (sherpa), embeddings and OCR run on CPU, which is enough at this model size.
## 5. On-prem deployment
Nothing in the code is cloud-specific. To run fully on-prem:
- `ollama serve` on an internal GPU server, `ollama pull <model>`, then `OLLAMA_BASE_URL=http://<server>:11434` (no key).
- Sherpa weights, e5, MMS-TTS and EasyOCR models are downloaded once and then cached on disk; pre-download them
and set `HF_HUB_OFFLINE=1` for an air-gapped host.
- Run `python app.py` behind a reverse proxy, or in a container; the index is plain files.
## REST API
```bash
curl -X POST localhost:7860/api/ask -H 'content-type: application/json' \
-d '{"question": "Ω…Ψ§ Ω‡ΩŠ Ψ¨Ψ§Ω‚Ψ§Ψͺ Ψ§Ω„Ψ₯Ω†ΨͺΨ±Ω†Ψͺ Ψ§Ω„Ω…Ω†Ψ²Ω„ΩŠΨŸ"}'
curl -X POST localhost:7860/api/transcribe -F file=@sample.wav -F language=ar
curl -X POST localhost:7860/api/tts -H 'content-type: application/json' -d '{"text": "Ω…Ψ±Ψ­Ψ¨Ψ§"}' -o out.wav
```
## Configuration (env vars)
See `config.py` and `.env.example`. The important ones: `OLLAMA_BASE_URL`, `OLLAMA_API_KEY`, `OLLAMA_MODEL`,
`SHERPA_DIR`, `MIN_SCORE` (relevance cut-off, calibrate on your own questions), `EMBED_MODEL`.
## Evaluation (notebook: `notebooks/te_asr_rag.ipynb`)
All numbers come from running the notebook; rerun it to reproduce them.
**Speech (Whisper-small int8 via sherpa-onnx, CPU).** Three clean Egyptian-Arabic questions spoken by the author, with
verified transcripts: mean **CER about 15%, WER about 56%** (Arabic-normalised). Errors are concentrated in the first
short question word (for example Ψ§ΩŠΩ‡) and one rare word; the content words are mostly right. This is a very small sample
(3 clips, 1 speaker) and should be read as a smoke test, not a benchmark. Decoding ran slower than real time on a laptop CPU
(about 1.4x the clip length after warm-up), so a GPU or a smaller model is the first latency fix. The noise sweep
(white and pink noise at 20, 10, 5 and 0 dB, denoise on and off) showed no clear benefit from denoising on this sample,
so denoising stays a user-controlled option.
**Retrieval (248 chunks, 81 pages, 26 hand-labelled questions in Arabic, English and dialect).**
recall@1 81%, recall@3 92%, recall@10 92%, MRR 0.865. Two questions are missed entirely (wording mismatch such as
"Ψ£Ω†Ω‚Ω„ Ψ±Ω‚Ω…ΩŠ" versus "Ω†Ω‚Ω„ Ψ§Ω„Ψ£Ψ±Ω‚Ψ§Ω…", and a product-list question); a reranker cannot recover those because it only reorders
the top results, so **hybrid keyword + dense search** is the first retrieval upgrade, not a reranker.
**Relevance cut-off.** In-scope questions scored 0.821 or higher at top-1; off-topic English questions about 0.77 and some
off-topic Arabic questions up to 0.83, so no single threshold separates them perfectly. `MIN_SCORE` defaults to 0.80
(keeps all in-scope questions, blocks the English off-topic ones); the grounded prompt is the second guard.
## Design decisions
- **16 kHz mono audio:** the ASR model is trained on 16 kHz log-Mel features, 8 kHz of bandwidth carries speech, and one
fixed rate keeps browser, upload and TTS audio consistent (MMS-TTS also outputs 16 kHz).
- **Exact FAISS index (`IndexFlatIP`)**: a few hundred chunks, so approximate indexes add error without any speed gain.
- **No reranker / BM25 yet:** deliberate; the notebook's recall and MRR show where they would and would not help.
- **No answer without evidence:** if nothing passes the cut-off the app returns a fixed not-found reply and does not call the LLM.
- **Branch questions:** the model is told never to claim a nearest branch; it points to the te.eg branch finder or 111.
## Known limitations
- Egyptian-dialect ASR quality depends on the sherpa model you ship; the notebook benchmarks it on clean and noisy audio.
- Whisper decodes long audio in 28 s windows without overlap; a word at a boundary can be lost (voice questions are short).
- MMS Arabic TTS speaks Modern Standard Arabic without diacritics, not Egyptian dialect.
- The knowledge base depends on what the crawler could fetch: branch locations and the latest price lists need a rendered
crawl (`--render`) and may be missing; the assistant says so instead of guessing.
- The evaluation sets are small (3 audio clips, 26 questions); they catch regressions but do not support precise accuracy claims.
- Scanned-PDF OCR is capped (`MAX_OCR_PAGES`) to protect the free Space; PDF text extraction can reorder Arabic in some files.
- Uploaded documents live in memory for the chat session only; they are not persisted.
- The cloud LLM is an external API; for data that must not leave the company, use the on-prem Ollama option above.