Spaces:
Sleeping
Sleeping
|
Download README.md from Alopmel/bookSearchLLM: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/Alopmel/bookSearchLLM/resolve/main/README.md
- Command line
-
hf download hf://spaces/Alopmel/bookSearchLLM/README.md
-
curl -L -o README.md https://huggingface.co/spaces/Alopmel/bookSearchLLM/resolve/main/README.md
11.6 kB
| title: BookSearchLLM | |
| emoji: 📚 | |
| colorFrom: purple | |
| colorTo: blue | |
| sdk: docker | |
| pinned: false | |
| short\_description: "Buscador inteligente" | |
| # 📖 Book Search LLM | |
| Búsqueda híbrida (literal + semántica) sobre **18 libros** con **FastAPI**, **Qdrant** y **Sentence-Transformers**. Frontend en **HTML/CSS/JS**. El Space de Hugging Face utiliza **Docker** (no necesitas Docker local). | |
| --- | |
| ## 🧠 ¿Qué hace el proyecto? | |
| * **Búsqueda híbrida** | |
| * **Semántica**: embeddings con `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` (384 dims, distancia **cosine**) almacenados en **Qdrant** (vector `dense`). | |
| * **Literal fuzzy**: normalización (sin tildes), variaciones útiles para sánscrito y similitud `difflib`. | |
| * **Estrategias**: `smart | keyword | semantic | balanced`. | |
| * **Contexto por párrafos**: ventana antes/después del párrafo seleccionado, respetando el orden de capítulos (`chapter_path`). | |
| * **Traducción EN/IT→ES con M2M100** (`facebook/m2m100_418M`) + `langdetect`. El resultado se guarda en `translate_text` dentro de Qdrant. | |
| * **Frontend** con filtros (score, tipo de match, autor/libro), paginación, historial y exportación. | |
| --- | |
| ## 🗂️ Estructura del repo | |
| ``` | |
| app/ | |
| main.py # FastAPI + endpoints | |
| qdrant_backend.py # búsquedas (Qdrant) + traducción + contexto | |
| static/ | |
| app.js # UI/UX | |
| app.css | |
| templates/ | |
| index.html # frontend | |
| requirements.txt # dependencias | |
| README.md | |
| ``` | |
| --- | |
| ## ✅ Requisitos | |
| * **Python 3.10** (para desarrollo local) | |
| * Cuenta en **Hugging Face** (Space con SDK `docker`) | |
| * Instancia de **Qdrant** accesible por URL y API Key | |
| * **git** y **git-lfs** | |
| > El Space usa Docker según el `Dockerfile` incluido; no hace falta Docker local. | |
| --- | |
| ## 📦 Dependencias (requirements.txt) | |
| ``` | |
| # --- Web/API --- | |
| fastapi>=0.110,<1.0 | |
| uvicorn[standard]>=0.27 | |
| jinja2>=3.1 | |
| aiofiles>=23.2 | |
| python-dotenv>=1.0 | |
| pydantic>=2,<3 | |
| # --- Vector / búsqueda --- | |
| qdrant-client==1.9.0 | |
| fastembed==0.5.1 | |
| onnxruntime>=1.17 # backend para fastembed en CPU | |
| # --- LLM/Traducción M2M100 --- | |
| transformers>=4.42,<4.47 | |
| torch>=2.2,<2.6 | |
| sentencepiece==0.1.99 | |
| safetensors>=0.4.3 | |
| # --- Utilidades proyecto --- | |
| python-Levenshtein>=0.21 | |
| langdetect==1.0.9 | |
| huggingface_hub[hf_xet]>=0.24 | |
| ``` | |
| --- | |
| ## 🧪 Puesta en marcha local (VS Code, Windows/Linux/macOS) | |
| ### 1) Clonar el repo | |
| ```bash | |
| git clone https://github.com/ALOPMEL/bookSearchLLM.git | |
| cd bookSearchLLM | |
| ``` | |
| ### 2) Crear y activar **entorno virtual (Python 3.10)** | |
| **PowerShell/VS Code terminal:** | |
| ```powershell | |
| py -3.10 -m venv .venv | |
| .venv\Scripts\activate | |
| ``` | |
| **Bash (Linux/macOS/WSL):** | |
| ```bash | |
| python3 -m venv .venv | |
| source .venv/bin/activate | |
| ``` | |
| **Git Bash (Windows):** | |
| ```bash | |
| source .venv/Scripts/activate | |
| ``` | |
| En VS Code: `Ctrl+Shift+P → Python: Select Interpreter → .venv`. | |
| ### 3) Instalar dependencias | |
| ```bash | |
| python -m pip install --upgrade pip | |
| pip install -r requirements.txt | |
| ``` | |
| ### 4) Variables de entorno | |
| Crea **.env** en la raíz: | |
| ``` | |
| QDRANT_URL=https://TU-QDRANT:6333 | |
| QDRANT_API_KEY=xxxxxxxxxxxxxxxx | |
| QDRANT_COLLECTION=bookSearchLLM | |
| EMBED_MODEL=sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 | |
| M2M_MODEL=facebook/m2m100_418M | |
| M2M_MAX_SRC_TOKENS=900 | |
| M2M_MAX_NEW_TOKENS=512 | |
| WARMUP=1 | |
| DEBUG=0 | |
| ``` | |
| ### 5) Ejecutar la API en local | |
| ```bash | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 | |
| # Abre http://127.0.0.1:7860 | |
| ``` | |
| --- | |
| ## 🗄️ Qdrant (colección) | |
| * **Nombre**: `bookSearchLLM` (ajústalo en `.env`) | |
| * **Vector** `dense`: **384** dimensiones, **cosine** | |
| * **Puntos**: \~16k (variable) | |
| * Payload mínimo por punto: `text`, `book`, `page`, `paragraph_index`, `author`; opcional `chapter_path`, `translate_text`. | |
| --- | |
| ## ☁️ Conectar y desplegar en Hugging Face (Space Docker) | |
| ### 1) Login en HF | |
| ```bash | |
| pip install huggingface_hub git-lfs | |
| huggingface-cli login # pega tu Access Token | |
| ``` | |
| ### 2) Añadir remoto del Space y publicar | |
| ```bash | |
| git remote add hf https://huggingface.co/spaces/Alopmel/bookSearchLLM | |
| git add -A && git commit -m "feat: actualización app y backend" | |
| git push hf main | |
| ``` | |
| > El Space reconstruye el **Docker** automáticamente con el `Dockerfile`. | |
| ### 3) Si el repo principal está en GitHub | |
| ```bash | |
| git remote -v # origin → GitHub, hf → HuggingFace | |
| ``` | |
| --- | |
| ## 🐳 Dockerfile (referencia) | |
| ```dockerfile | |
| FROM python:3.11-slim | |
| ENV PIP_NO_CACHE_DIR=1 \ | |
| HF_HOME=/app/.cache/huggingface \ | |
| HUGGINGFACE_HUB_CACHE=/app/.cache/huggingface \ | |
| UVICORN_WORKERS=1 \ | |
| OMP_NUM_THREADS=1 | |
| WORKDIR /app | |
| COPY requirements.txt ./ | |
| RUN pip install --no-cache-dir -r requirements.txt | |
| RUN python - <<'PY' | |
| from fastembed import TextEmbedding | |
| TextEmbedding("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2") | |
| from sentence_transformers import SentenceTransformer | |
| SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2") | |
| print("Modelos precargados ✅") | |
| PY | |
| COPY . . | |
| EXPOSE 7860 | |
| CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"] | |
| ``` | |
| --- | |
| ## 📥 Ejemplos de uso de la API (curl) | |
| **Buscar (híbrido):** | |
| ```bash | |
| curl -X POST "http://127.0.0.1:7860/api/search" \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "text": "¿Qué es el spanda?", | |
| "strategy": "smart", | |
| "max_results": 50 | |
| }' | |
| ``` | |
| **Contexto por párrafo:** | |
| ```bash | |
| curl -X POST "http://127.0.0.1:7860/api/context" \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "libro": "Tantraloka", | |
| "author": "Abhinavagupta", | |
| "page": 120, | |
| "paragraph_index": 3, | |
| "before": 2, | |
| "after": 2 | |
| }' | |
| ``` | |
| **Traducción EN/IT → ES (M2M100) + guardado en Qdrant:** | |
| ```bash | |
| curl -X POST "http://127.0.0.1:7860/api/translate" \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "libro": "Tantraloka", | |
| "page": 120, | |
| "paragraph_index": 3, | |
| "author": "Abhinavagupta", | |
| "text": "Consciousness is the ground of reality.", | |
| "src_lang": "en" | |
| }' | |
| ``` | |
| --- | |
| ## 🔌 Endpoints | |
| * `POST /api/search` → búsqueda | |
| * `POST /api/search/advanced` → filtros | |
| * `POST /api/context` → contexto por párrafo | |
| * `POST /api/translate` → traducción (EN/IT→ES con M2M100) y guardado en Qdrant | |
| * `GET /health` → estado + stats | |
| --- | |
| ## 🧩 Detalles clave de implementación | |
| * **Embeddings** con **fastembed** | |
| * **Fuzzy**: variaciones + similitud difusa | |
| * **Estrategia `smart`**: preguntas largas → semántica; tokens cortos → balanced/keyword | |
| * **Traducción**: troceo + batch con **M2M100**; persistencia en Qdrant | |
| --- | |
| ## 🆘 Troubleshooting | |
| ### Problemas comunes | |
| * `huggingface-cli: command not found` → `pip install huggingface_hub` | |
| * `sentencepiece` faltante → revisa `requirements.txt` | |
| * `Could not import module "main"` → ejecuta desde raíz: `uvicorn app.main:app --reload` | |
| ### Entornos virtuales | |
| **Crear / activar / desactivar** | |
| ```powershell | |
| py -3.10 -m venv .venv | |
| .venv\Scripts\activate | |
| deactivate | |
| ``` | |
| ```bash | |
| python3 -m venv .venv | |
| source .venv/bin/activate | |
| deactivate | |
| ``` | |
| **Listar entornos virtuales** | |
| ```powershell | |
| Get-ChildItem -Recurse -Directory -Force | Where-Object { $_.Name -in @('venv','.venv') } | |
| ``` | |
| ```bash | |
| find . -type d \( -name "venv" -o -name ".venv" \) | |
| ``` | |
| **Ver versión de Python** | |
| ```powershell | |
| $py = ".venv\\Scripts\\python.exe"; & $py -V | |
| ``` | |
| ```bash | |
| source .venv/bin/activate && python -V | |
| ``` | |
| **Borrar entornos bloqueados (Windows)** | |
| ```powershell | |
| Get-Process python,pythonw,uvicorn,pip -ErrorAction SilentlyContinue | Stop-Process -Force | |
| Remove-Item -Recurse -Force .venv | |
| ``` | |
| ### Logs del servidor | |
| ```bash | |
| uvicorn app.main:app --reload --log-level debug | |
| ``` | |
| ```powershell | |
| uvicorn app.main:app --reload --port 7860 | Tee-Object -FilePath .\server.log | |
| ``` | |
| --- | |
| ## 📘 Guía de Comandos (PowerShell & Bash) | |
| Este apartado está listo para **copiar y pegar**. | |
| ### 🐍 Entornos virtuales | |
| **Crear** | |
| ```powershell | |
| # PowerShell | |
| py -3.10 -m venv .venv | |
| ``` | |
| ```bash | |
| # Bash / WSL / macOS | |
| python3 -m venv .venv | |
| ``` | |
| **Activar** | |
| ```powershell | |
| # PowerShell | |
| .venv\Scripts\activate | |
| ``` | |
| ```bash | |
| # Bash / WSL / macOS | |
| source .venv/bin/activate | |
| # Git Bash en Windows (alternativa) | |
| source .venv/Scripts/activate | |
| ``` | |
| **Desactivar** | |
| ```bash | |
| deactivate | |
| ``` | |
| **Eliminar (Windows bloqueado por procesos)** | |
| ```powershell | |
| Get-Process python,pythonw,uvicorn,pip -ErrorAction SilentlyContinue | Stop-Process -Force | |
| Remove-Item -Recurse -Force .venv | |
| ``` | |
| ```bash | |
| rm -rf .venv | |
| ``` | |
| **Listar entornos dentro del proyecto** | |
| ```powershell | |
| Get-ChildItem -Recurse -Directory -Force | Where-Object { $_.Name -in @('venv','.venv') } | |
| ``` | |
| ```bash | |
| find . -type d \( -name "venv" -o -name ".venv" \) | |
| ``` | |
| **Comprobar versión de Python del venv** | |
| ```powershell | |
| $py = ".venv\Scripts\python.exe"; & $py -V | |
| ``` | |
| ```bash | |
| source .venv/bin/activate && python -V | |
| ``` | |
| ### 📦 Dependencias | |
| ```bash | |
| pip install --upgrade pip | |
| pip install -r requirements.txt | |
| ``` | |
| ### 🚀 Servidor FastAPI (Uvicorn) | |
| **Windows (PowerShell)** | |
| (Opcional) Para evitar errores de codificación con emojis/acentos: | |
| ```powershell | |
| chcp 65001 | Out-Null | |
| [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new() | |
| $OutputEncoding = [System.Text.UTF8Encoding]::new() | |
| $env:PYTHONIOENCODING = "utf-8" | |
| ``` | |
| 1. Solo consola (el propio proyecto ya guarda en logs/app.log) | |
| ```powershell | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug | |
| ``` | |
| 2. Consola y guardar copia adicional (evita duplicados usando otro archivo) | |
| ```powershell | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug ` | |
| | Tee-Object -FilePath .\logs\uvicorn.log -Append | |
| ``` | |
| 3. Solo archivo, sin mostrar nada en consola | |
| Opción A (recomendada): silenciar la consola y dejar que tu logger escriba en logs/app.log | |
| ```powershell | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug *> $null | |
| ``` | |
| Opción B: redirigir toda la salida de Uvicorn a otro archivo | |
| ```powershell | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug *> .\logs\uvicorn.log | |
| ``` | |
| **Linux / macOS (Bash)** | |
| 1. Solo consola (el propio proyecto ya guarda en logs/app.log) | |
| ```bash | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug | |
| ``` | |
| 2. Consola y guardar copia adicional | |
| ```bash | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug 2>&1 | tee -a logs/uvicorn.log | |
| ``` | |
| 3. Solo archivo, sin mostrar nada en consola | |
| Opción A (recomendada): silenciar la consola y dejar que tu logger escriba en logs/app.log | |
| ```bash | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug >/dev/null 2>&1 | |
| ``` | |
| Opción B: redirigir toda la salida de Uvicorn a otro archivo | |
| ```bash | |
| uvicorn app.main:app --reload --host 0.0.0.0 --port 7860 --log-level debug > logs/uvicorn.log 2>&1 | |
| ``` | |
| --- | |
| ## 🐙 Git (opcional) | |
| ```bash | |
| git init | |
| git add . | |
| git commit -m "Primer commit" | |
| git remote add origin https://github.com/usuario/repositorio.git | |
| git branch -M main | |
| git push -u origin main | |
| ``` | |
| --- | |
| ## 🧹 Tips | |
| ```bash | |
| # Ver dependencias | |
| pip list | |
| # Congelar dependencias | |
| pip freeze > requirements.txt | |
| # Probar salud | |
| curl http://127.0.0.1:7860/health | |
| ``` | |
| --- | |
| ## 👤 Para el programador del cliente | |
| 1. Clona el repo, crea `.env` con Qdrant y selecciona Python 3.10 en VS Code. | |
| 2. `pip install -r requirements.txt` y arranca con `uvicorn app.main:app --reload`. | |
| 3. Haz login en HF (`huggingface-cli login`) y añade el remoto `hf`. | |
| 4. `git push hf main` para reconstruir el Space (Docker). | |
| --- | |
| ## 📝 Licencia | |
| MIT (ajústala si el cliente necesita otra). | |