MohitGupta41 commited on
Commit ·
91b6d82
1
Parent(s): 8148bd1
Initial Commit
Browse files- Dockerfile_e +0 -77
- app/main_e.py +0 -414
- requirements.txt +0 -1
Dockerfile_e
DELETED
|
@@ -1,77 +0,0 @@
|
|
| 1 |
-
# --------------------------
|
| 2 |
-
# Hugging Face Space (Docker) - Backend (CPU)
|
| 3 |
-
# --------------------------
|
| 4 |
-
FROM python:3.12-slim
|
| 5 |
-
|
| 6 |
-
# =============== System deps ===============
|
| 7 |
-
# - build-essential et al. for any wheels that need compile
|
| 8 |
-
# - ffmpeg for audio resample
|
| 9 |
-
# - libsndfile1 for python-soundfile
|
| 10 |
-
# - OpenCV runtime libs already included below
|
| 11 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
-
build-essential gcc g++ make cmake pkg-config \
|
| 13 |
-
libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 libgomp1 \
|
| 14 |
-
libsndfile1 ffmpeg git curl ca-certificates \
|
| 15 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 16 |
-
|
| 17 |
-
# =============== Workspace ===============
|
| 18 |
-
ENV APP_HOME=/workspace
|
| 19 |
-
RUN mkdir -p $APP_HOME/app $APP_HOME/data $APP_HOME/cache && chmod -R 777 $APP_HOME
|
| 20 |
-
WORKDIR $APP_HOME
|
| 21 |
-
|
| 22 |
-
# Optional caches for various libs
|
| 23 |
-
ENV CC=gcc CXX=g++
|
| 24 |
-
ENV INSIGHTFACE_HOME=/workspace/cache/insightface
|
| 25 |
-
ENV MPLCONFIGDIR=/workspace/cache/matplotlib
|
| 26 |
-
|
| 27 |
-
# =============== Python deps ===============
|
| 28 |
-
COPY requirements.txt ./requirements.txt
|
| 29 |
-
|
| 30 |
-
# Pre-install numpy variant compatible with py3.12, then the rest
|
| 31 |
-
RUN python -m pip install --no-cache-dir --upgrade pip && \
|
| 32 |
-
pip install --no-cache-dir "numpy<2.0; python_version<'3.12'" "numpy>=2.0; python_version>='3.12'" && \
|
| 33 |
-
pip install --no-cache-dir -r requirements.txt
|
| 34 |
-
|
| 35 |
-
# Add audio utils used by /stt and /tts (already referenced in code you’ll add)
|
| 36 |
-
RUN pip install --no-cache-dir soundfile faster-whisper==1.0.0
|
| 37 |
-
|
| 38 |
-
# =============== Piper (offline TTS) ===============
|
| 39 |
-
# Download a small/medium English voice (change to hi-IN or en-IN if you prefer)
|
| 40 |
-
# Piper releases: https://github.com/rhasspy/piper/releases
|
| 41 |
-
RUN curl -L -o /usr/local/bin/piper \
|
| 42 |
-
https://github.com/rhasspy/piper/releases/download/v1.2.0/piper_linux_x86_64 && \
|
| 43 |
-
chmod +x /usr/local/bin/piper
|
| 44 |
-
|
| 45 |
-
# Voice (~50–80MB each). Swap to another voice if you need Indian English/Hindi.
|
| 46 |
-
# See https://github.com/rhasspy/piper#voices for alternatives.
|
| 47 |
-
RUN mkdir -p /models/piper/en_US && \
|
| 48 |
-
curl -L -o /models/piper/en_US/libri_tts_en_US-medium.onnx \
|
| 49 |
-
https://github.com/rhasspy/piper/releases/download/v1.2.0/libri_tts_en_US-medium.onnx
|
| 50 |
-
|
| 51 |
-
# =============== faster-whisper model (offline STT) ===============
|
| 52 |
-
# Pre-download the "small" model (~460 MB) so no runtime fetch is needed.
|
| 53 |
-
RUN mkdir -p /models/faster-whisper
|
| 54 |
-
RUN python - <<'PY'
|
| 55 |
-
from faster_whisper import WhisperModel
|
| 56 |
-
WhisperModel("small", download_root="/models/faster-whisper")
|
| 57 |
-
print("Downloaded faster-whisper 'small' to /models/faster-whisper")
|
| 58 |
-
PY
|
| 59 |
-
|
| 60 |
-
# =============== App ===============
|
| 61 |
-
COPY app ./app
|
| 62 |
-
COPY run.sh ./run.sh
|
| 63 |
-
RUN chmod +x ./run.sh
|
| 64 |
-
|
| 65 |
-
# =============== Runtime ENV ===============
|
| 66 |
-
# Voice/STT providers default to OFFLINE so Space does not need internet
|
| 67 |
-
ENV STT_PROVIDER=offline \
|
| 68 |
-
TTS_PROVIDER=offline \
|
| 69 |
-
FW_MODEL_DIR=/models/faster-whisper \
|
| 70 |
-
FW_MODEL_SIZE=small \
|
| 71 |
-
PIPER_BIN=/usr/local/bin/piper \
|
| 72 |
-
PIPER_VOICE=/models/piper/en_US/libri_tts_en_US-medium.onnx \
|
| 73 |
-
PIPER_SAMPLE_RATE=22050 \
|
| 74 |
-
PORT=7860
|
| 75 |
-
|
| 76 |
-
# Keep your existing port/cmd
|
| 77 |
-
CMD ["./run.sh"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/main_e.py
DELETED
|
@@ -1,414 +0,0 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException, Query, Depends, Body
|
| 2 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from .settings import settings
|
| 4 |
-
from .deps import index, face, get_hf_token, build_agent_with_token
|
| 5 |
-
from .models.face import (
|
| 6 |
-
EnrollResp, IdentifyReq, IdentifyResp, IdentifyHit,
|
| 7 |
-
IdentifyManyReq, IdentifyManyResp, FaceDet,
|
| 8 |
-
)
|
| 9 |
-
from .models.query import QueryReq, QueryResp
|
| 10 |
-
from .services.aggregator import aggregate_by_user
|
| 11 |
-
from .services.face_service import imdecode
|
| 12 |
-
import numpy as np, uuid, cv2, os, io, zipfile, glob, shutil
|
| 13 |
-
import base64, tempfile, subprocess, json
|
| 14 |
-
from typing import Optional, Tuple
|
| 15 |
-
from fastapi.responses import Response, StreamingResponse
|
| 16 |
-
from pydantic import BaseModel
|
| 17 |
-
import soundfile as sf
|
| 18 |
-
import numpy as np
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
|
| 21 |
-
app = FastAPI(title="Realtime BI Assistant")
|
| 22 |
-
|
| 23 |
-
app.add_middleware(
|
| 24 |
-
CORSMiddleware,
|
| 25 |
-
allow_origins=["*"], allow_credentials=True,
|
| 26 |
-
allow_methods=["*"], allow_headers=["*"],
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
@app.get("/")
|
| 30 |
-
def root():
|
| 31 |
-
return {"ok": True, "msg": "Backend alive"}
|
| 32 |
-
|
| 33 |
-
# ---------- Voice config ----------
|
| 34 |
-
STT_PROVIDER = os.getenv("STT_PROVIDER", "offline") # "offline" | "hf"
|
| 35 |
-
TTS_PROVIDER = os.getenv("TTS_PROVIDER", "offline") # "offline" | "hf"
|
| 36 |
-
|
| 37 |
-
# Faster-Whisper (offline STT)
|
| 38 |
-
FW_MODEL_DIR = os.getenv("FW_MODEL_DIR", "/models/faster-whisper")
|
| 39 |
-
FW_MODEL_SIZE = os.getenv("FW_MODEL_SIZE", "small") # tiny|base|small|medium|large-v3 etc.
|
| 40 |
-
|
| 41 |
-
# Piper (offline TTS)
|
| 42 |
-
PIPER_BIN = os.getenv("PIPER_BIN", "/usr/local/bin/piper")
|
| 43 |
-
PIPER_VOICE = os.getenv("PIPER_VOICE", "/models/piper/en_US/libri_tts_en_US-medium.onnx") # change to your voice
|
| 44 |
-
PIPER_SAMPLE_RATE = int(os.getenv("PIPER_SAMPLE_RATE", "22050"))
|
| 45 |
-
|
| 46 |
-
# Hugging Face (online STT/TTS)
|
| 47 |
-
HF_STT_MODEL = os.getenv("HF_STT_MODEL", "openai/whisper-small") # any STT model with audio-to-text
|
| 48 |
-
HF_TTS_MODEL = os.getenv("HF_TTS_MODEL", "espnet/kan-bayashi_ljspeech_vits") # any TTS wav output model
|
| 49 |
-
|
| 50 |
-
def _ensure_wav_16k_mono(in_bytes: bytes, in_mime: str = "audio/wav") -> Tuple[np.ndarray, int]:
|
| 51 |
-
"""
|
| 52 |
-
Convert arbitrary audio to mono 16k PCM via ffmpeg, return (float32 PCM, sr=16000).
|
| 53 |
-
"""
|
| 54 |
-
# Write temp input
|
| 55 |
-
with tempfile.NamedTemporaryFile(suffix=".input", delete=False) as f_in:
|
| 56 |
-
f_in.write(in_bytes)
|
| 57 |
-
in_path = f_in.name
|
| 58 |
-
out_path = in_path + ".wav"
|
| 59 |
-
|
| 60 |
-
# ffmpeg -y -i in -ac 1 -ar 16000 -f wav out
|
| 61 |
-
cmd = [
|
| 62 |
-
"ffmpeg", "-y", "-i", in_path,
|
| 63 |
-
"-ac", "1", "-ar", "16000",
|
| 64 |
-
"-f", "wav", out_path
|
| 65 |
-
]
|
| 66 |
-
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 67 |
-
|
| 68 |
-
# Load wav
|
| 69 |
-
data, sr = sf.read(out_path, dtype="float32", always_2d=False)
|
| 70 |
-
if sr != 16000:
|
| 71 |
-
raise RuntimeError("ffmpeg resample failed")
|
| 72 |
-
try:
|
| 73 |
-
os.remove(in_path)
|
| 74 |
-
# keep out_path for debug if needed
|
| 75 |
-
except Exception:
|
| 76 |
-
pass
|
| 77 |
-
return data.astype(np.float32), 16000
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def _bytes_to_wav_stream(pcm: np.ndarray, sr: int = 22050) -> bytes:
|
| 81 |
-
"""Encode float32 PCM to WAV bytes."""
|
| 82 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f_out:
|
| 83 |
-
sf.write(f_out.name, pcm, sr, subtype="PCM_16")
|
| 84 |
-
with open(f_out.name, "rb") as fr:
|
| 85 |
-
wav_bytes = fr.read()
|
| 86 |
-
try:
|
| 87 |
-
os.remove(f_out.name)
|
| 88 |
-
except Exception:
|
| 89 |
-
pass
|
| 90 |
-
return wav_bytes
|
| 91 |
-
|
| 92 |
-
# ---------- STT ----------
|
| 93 |
-
_fw_model = None
|
| 94 |
-
|
| 95 |
-
def _stt_offline(audio_bytes: bytes, mime: str, hf_token: Optional[str]) -> str:
|
| 96 |
-
global _fw_model
|
| 97 |
-
try:
|
| 98 |
-
from faster_whisper import WhisperModel
|
| 99 |
-
except Exception as e:
|
| 100 |
-
raise HTTPException(500, f"faster-whisper not installed: {e}")
|
| 101 |
-
|
| 102 |
-
if _fw_model is None:
|
| 103 |
-
_fw_model = WhisperModel(FW_MODEL_SIZE, device="cpu", compute_type="int8", download_root=FW_MODEL_DIR)
|
| 104 |
-
|
| 105 |
-
pcm, _ = _ensure_wav_16k_mono(audio_bytes, mime)
|
| 106 |
-
# faster-whisper expects path or np array; we’ll pass array
|
| 107 |
-
segments, info = _fw_model.transcribe(pcm, language=None, beam_size=1, vad_filter=True)
|
| 108 |
-
text = " ".join([seg.text.strip() for seg in segments]).strip()
|
| 109 |
-
return text or ""
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def _stt_hf(audio_bytes: bytes, mime: str, hf_token: Optional[str]) -> str:
|
| 113 |
-
if not hf_token:
|
| 114 |
-
raise HTTPException(400, "HF token required for STT via Hugging Face")
|
| 115 |
-
url = f"https://api-inference.huggingface.co/models/{HF_STT_MODEL}"
|
| 116 |
-
headers = {"Authorization": f"Bearer {hf_token}"}
|
| 117 |
-
# HF accepts raw audio bytes
|
| 118 |
-
import requests as _rq
|
| 119 |
-
r = _rq.post(url, headers=headers, data=audio_bytes, timeout=120)
|
| 120 |
-
if not r.ok:
|
| 121 |
-
raise HTTPException(502, f"HF STT failed: {r.status_code} {r.text[:200]}")
|
| 122 |
-
try:
|
| 123 |
-
out = r.json()
|
| 124 |
-
# common outputs: {"text": "..."} or [{"text": "..."}]
|
| 125 |
-
if isinstance(out, dict) and "text" in out:
|
| 126 |
-
return out["text"]
|
| 127 |
-
if isinstance(out, list) and out and isinstance(out[0], dict) and "text" in out[0]:
|
| 128 |
-
return out[0]["text"]
|
| 129 |
-
# some models return {"generated_text": "..."}
|
| 130 |
-
if isinstance(out, dict) and "generated_text" in out:
|
| 131 |
-
return out["generated_text"]
|
| 132 |
-
return ""
|
| 133 |
-
except Exception:
|
| 134 |
-
return ""
|
| 135 |
-
|
| 136 |
-
# ---------- TTS ----------
|
| 137 |
-
def _tts_offline_piper(text: str, voice_path: str) -> bytes:
|
| 138 |
-
"""
|
| 139 |
-
Call Piper CLI to synthesize WAV.
|
| 140 |
-
"""
|
| 141 |
-
if not os.path.isfile(voice_path):
|
| 142 |
-
raise HTTPException(500, f"Piper voice not found at {voice_path}")
|
| 143 |
-
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f_txt:
|
| 144 |
-
f_txt.write(text.encode("utf-8"))
|
| 145 |
-
in_txt = f_txt.name
|
| 146 |
-
out_wav = in_txt + ".wav"
|
| 147 |
-
|
| 148 |
-
cmd = [PIPER_BIN, "--model", voice_path, "--output_file", out_wav, "--speaker", "0"]
|
| 149 |
-
with open(in_txt, "rb") as fin:
|
| 150 |
-
subprocess.run(cmd, stdin=fin, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 151 |
-
|
| 152 |
-
with open(out_wav, "rb") as fr:
|
| 153 |
-
audio = fr.read()
|
| 154 |
-
try:
|
| 155 |
-
os.remove(in_txt)
|
| 156 |
-
os.remove(out_wav)
|
| 157 |
-
except Exception:
|
| 158 |
-
pass
|
| 159 |
-
return audio
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
def _tts_hf(text: str, hf_token: Optional[str]) -> bytes:
|
| 163 |
-
if not hf_token:
|
| 164 |
-
raise HTTPException(400, "HF token required for TTS via Hugging Face")
|
| 165 |
-
url = f"https://api-inference.huggingface.co/models/{HF_TTS_MODEL}"
|
| 166 |
-
headers = {"Authorization": f"Bearer {hf_token}", "Accept": "audio/wav", "Content-Type": "application/json"}
|
| 167 |
-
import requests as _rq
|
| 168 |
-
r = _rq.post(url, headers=headers, json={"inputs": text}, timeout=120)
|
| 169 |
-
if not r.ok:
|
| 170 |
-
# Some HF TTS return JSON with b64; try to parse
|
| 171 |
-
try:
|
| 172 |
-
js = r.json()
|
| 173 |
-
b64 = js.get("audio", None)
|
| 174 |
-
if b64:
|
| 175 |
-
return base64.b64decode(b64)
|
| 176 |
-
except Exception:
|
| 177 |
-
pass
|
| 178 |
-
raise HTTPException(502, f"HF TTS failed: {r.status_code} {r.text[:200]}")
|
| 179 |
-
return r.content
|
| 180 |
-
|
| 181 |
-
# ---------- Schemas ----------
|
| 182 |
-
class TTSReq(BaseModel):
|
| 183 |
-
text: str
|
| 184 |
-
voice: Optional[str] = "en-IN"
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
# ---------- /stt ----------
|
| 188 |
-
@app.post("/stt")
|
| 189 |
-
async def stt(audio: UploadFile = File(...), hf_token: Optional[str] = Depends(get_hf_token)):
|
| 190 |
-
in_bytes = await audio.read()
|
| 191 |
-
mime = audio.content_type or "audio/wav"
|
| 192 |
-
|
| 193 |
-
if STT_PROVIDER == "offline":
|
| 194 |
-
text = _stt_offline(in_bytes, mime, hf_token)
|
| 195 |
-
elif STT_PROVIDER == "hf":
|
| 196 |
-
text = _stt_hf(in_bytes, mime, hf_token)
|
| 197 |
-
else:
|
| 198 |
-
raise HTTPException(400, f"Unknown STT_PROVIDER: {STT_PROVIDER}")
|
| 199 |
-
|
| 200 |
-
return {"text": text}
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
# # ---------- /tts ----------
|
| 204 |
-
# @app.post("/tts")
|
| 205 |
-
# async def tts(req: TTSReq, hf_token: Optional[str] = Depends(get_hf_token)):
|
| 206 |
-
# text = (req.text or "").strip()
|
| 207 |
-
# if not text:
|
| 208 |
-
# raise HTTPException(400, "Empty text")
|
| 209 |
-
|
| 210 |
-
# if TTS_PROVIDER == "offline":
|
| 211 |
-
# # You can map req.voice -> multiple piper voices if you have them
|
| 212 |
-
# audio_bytes = _tts_offline_piper(text, PIPER_VOICE)
|
| 213 |
-
# elif TTS_PROVIDER == "hf":
|
| 214 |
-
# audio_bytes = _tts_hf(text, hf_token)
|
| 215 |
-
# else:
|
| 216 |
-
# raise HTTPException(400, f"Unknown TTS_PROVIDER: {TTS_PROVIDER}")
|
| 217 |
-
|
| 218 |
-
# return Response(content=audio_bytes, media_type="audio/wav")
|
| 219 |
-
VOICE_MAP = {
|
| 220 |
-
"en-IN": "/models/piper/en_IN/xyz.onnx",
|
| 221 |
-
"en-US": "/models/piper/en_US/libri_tts_en_US-medium.onnx",
|
| 222 |
-
}
|
| 223 |
-
|
| 224 |
-
@app.post("/tts")
|
| 225 |
-
async def tts(req: TTSReq, hf_token: Optional[str] = Depends(get_hf_token)):
|
| 226 |
-
text = (req.text or "").strip()
|
| 227 |
-
if not text:
|
| 228 |
-
raise HTTPException(400, "Empty text")
|
| 229 |
-
if TTS_PROVIDER == "offline":
|
| 230 |
-
voice_path = VOICE_MAP.get(req.voice, PIPER_VOICE)
|
| 231 |
-
audio_bytes = _tts_offline_piper(text, voice_path)
|
| 232 |
-
elif TTS_PROVIDER == "hf":
|
| 233 |
-
audio_bytes = _tts_hf(text, hf_token)
|
| 234 |
-
else:
|
| 235 |
-
raise HTTPException(400, f"Unknown TTS_PROVIDER: {TTS_PROVIDER}")
|
| 236 |
-
return Response(content=audio_bytes, media_type="audio/wav")
|
| 237 |
-
|
| 238 |
-
def _decide_identity(agg, threshold: float, margin: float):
|
| 239 |
-
if not agg:
|
| 240 |
-
return "Unknown", 0.0, 0.0
|
| 241 |
-
best_user, best_score = agg[0]
|
| 242 |
-
second = agg[1][1] if len(agg) > 1 else -1.0
|
| 243 |
-
margin_val = best_score - second
|
| 244 |
-
if best_score >= threshold and margin_val >= margin and best_user != "Unknown":
|
| 245 |
-
return best_user, best_score, margin_val
|
| 246 |
-
return "Unknown", best_score, margin_val
|
| 247 |
-
|
| 248 |
-
def _safe_extract(zf: zipfile.ZipFile, dest: str):
|
| 249 |
-
os.makedirs(dest, exist_ok=True)
|
| 250 |
-
for member in zf.infolist():
|
| 251 |
-
p = os.path.realpath(os.path.join(dest, member.filename))
|
| 252 |
-
if not p.startswith(os.path.realpath(dest) + os.sep):
|
| 253 |
-
continue
|
| 254 |
-
if member.is_dir():
|
| 255 |
-
os.makedirs(p, exist_ok=True)
|
| 256 |
-
else:
|
| 257 |
-
os.makedirs(os.path.dirname(p), exist_ok=True)
|
| 258 |
-
with zf.open(member) as src, open(p, "wb") as out:
|
| 259 |
-
out.write(src.read())
|
| 260 |
-
|
| 261 |
-
def _guess_images_root(tmpdir: str) -> str | None:
|
| 262 |
-
pref = os.path.join(tmpdir, "Images")
|
| 263 |
-
if os.path.isdir(pref):
|
| 264 |
-
return pref
|
| 265 |
-
for root, dirs, files in os.walk(tmpdir):
|
| 266 |
-
subdirs = [os.path.join(root, d) for d in dirs]
|
| 267 |
-
if subdirs and any(
|
| 268 |
-
any(fn.lower().endswith((".jpg",".jpeg",".png")) for fn in os.listdir(sd))
|
| 269 |
-
for sd in subdirs
|
| 270 |
-
):
|
| 271 |
-
return root
|
| 272 |
-
return None
|
| 273 |
-
|
| 274 |
-
@app.post("/enroll_zip", response_model=EnrollResp)
|
| 275 |
-
async def enroll_zip(zipfile_upload: UploadFile = File(...)):
|
| 276 |
-
"""
|
| 277 |
-
Accepts a ZIP with structure: Images/<UserName>/*.jpg|png
|
| 278 |
-
Upserts all faces into the local FAISS index under user metadata.
|
| 279 |
-
"""
|
| 280 |
-
if not zipfile_upload.filename.lower().endswith(".zip"):
|
| 281 |
-
raise HTTPException(400, "Please upload a .zip")
|
| 282 |
-
|
| 283 |
-
raw = await zipfile_upload.read()
|
| 284 |
-
tmpdir = os.path.join("/workspace", "upload", uuid.uuid4().hex[:8])
|
| 285 |
-
os.makedirs(tmpdir, exist_ok=True)
|
| 286 |
-
try:
|
| 287 |
-
with zipfile.ZipFile(io.BytesIO(raw), "r") as zf:
|
| 288 |
-
_safe_extract(zf, tmpdir)
|
| 289 |
-
|
| 290 |
-
root = _guess_images_root(tmpdir)
|
| 291 |
-
if not root:
|
| 292 |
-
raise HTTPException(400, "Couldn't find 'Images/<UserName>/*' structure in ZIP")
|
| 293 |
-
|
| 294 |
-
user_dirs = sorted([p for p in glob.glob(os.path.join(root, "*")) if os.path.isdir(p)])
|
| 295 |
-
if not user_dirs:
|
| 296 |
-
raise HTTPException(400, "No user folders found under Images/")
|
| 297 |
-
|
| 298 |
-
total = 0
|
| 299 |
-
enrolled_users = []
|
| 300 |
-
for udir in user_dirs:
|
| 301 |
-
user = os.path.basename(udir)
|
| 302 |
-
paths = sorted([p for p in glob.glob(os.path.join(udir, "*")) if p.lower().endswith((".jpg",".jpeg",".png"))])
|
| 303 |
-
if not paths:
|
| 304 |
-
continue
|
| 305 |
-
count_user = 0
|
| 306 |
-
for p in paths:
|
| 307 |
-
img = cv2.imdecode(np.fromfile(p, dtype=np.uint8), cv2.IMREAD_COLOR)
|
| 308 |
-
if img is None: continue
|
| 309 |
-
bbox, emb, det_score = face.embed_best(img)
|
| 310 |
-
if emb is None: continue
|
| 311 |
-
vec = emb.astype(np.float32)
|
| 312 |
-
vec = vec / (np.linalg.norm(vec) + 1e-9)
|
| 313 |
-
vid = f"{user}::{uuid.uuid4().hex[:8]}"
|
| 314 |
-
index.add_vectors(vecs=np.array([vec]),
|
| 315 |
-
metas=[{"user":user,"det_score":float(det_score), "source":"enroll_zip"}],
|
| 316 |
-
ids=[vid])
|
| 317 |
-
count_user += 1
|
| 318 |
-
total += 1
|
| 319 |
-
if count_user > 0:
|
| 320 |
-
enrolled_users.append(user)
|
| 321 |
-
|
| 322 |
-
return EnrollResp(users=enrolled_users, total_vectors=total)
|
| 323 |
-
finally:
|
| 324 |
-
try:
|
| 325 |
-
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 326 |
-
except Exception:
|
| 327 |
-
pass
|
| 328 |
-
|
| 329 |
-
# ---------- endpoints ----------
|
| 330 |
-
@app.post("/index/upsert_image")
|
| 331 |
-
async def upsert_image(user: str = Query(..., description="User label"),
|
| 332 |
-
image: UploadFile = File(...)):
|
| 333 |
-
raw = await image.read()
|
| 334 |
-
img = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
|
| 335 |
-
if img is None:
|
| 336 |
-
raise HTTPException(400, "Invalid image file")
|
| 337 |
-
bbox, emb, det_score = face.embed_best(img)
|
| 338 |
-
if emb is None:
|
| 339 |
-
return {"ok": False, "msg": "no face detected"}
|
| 340 |
-
vec = emb.astype(np.float32)
|
| 341 |
-
vec = vec / (np.linalg.norm(vec) + 1e-9)
|
| 342 |
-
vid = f"{user}::{uuid.uuid4().hex[:8]}"
|
| 343 |
-
index.add_vectors(vecs=np.array([vec]),
|
| 344 |
-
metas=[{"user":user,"det_score":float(det_score)}],
|
| 345 |
-
ids=[vid])
|
| 346 |
-
return {"ok": True, "id": vid, "user": user, "det_score": float(det_score)}
|
| 347 |
-
|
| 348 |
-
@app.post("/identify", response_model=IdentifyResp)
|
| 349 |
-
async def identify(req: IdentifyReq):
|
| 350 |
-
try:
|
| 351 |
-
img = imdecode(req.image_b64)
|
| 352 |
-
except Exception:
|
| 353 |
-
raise HTTPException(status_code=400, detail="Bad image_b64")
|
| 354 |
-
bbox, emb, det_score = face.embed_best(img)
|
| 355 |
-
if emb is None:
|
| 356 |
-
return IdentifyResp(decision="NoFace", best_score=0.0, margin=0.0, topk=[], bbox=None)
|
| 357 |
-
|
| 358 |
-
matches = index.query(emb, top_k=settings.TOPK_DB)
|
| 359 |
-
agg = aggregate_by_user(matches)
|
| 360 |
-
|
| 361 |
-
user, best, margin_val = _decide_identity(agg, settings.THRESHOLD, settings.MARGIN)
|
| 362 |
-
topk = [IdentifyHit(user=u, score=s) for u, s in agg[:req.top_k]]
|
| 363 |
-
return IdentifyResp(decision=user, best_score=best, margin=margin_val, topk=topk, bbox=bbox)
|
| 364 |
-
|
| 365 |
-
# ---------- NEW: multi-face endpoint ----------
|
| 366 |
-
@app.post("/identify_many", response_model=IdentifyManyResp)
|
| 367 |
-
async def identify_many(req: IdentifyManyReq):
|
| 368 |
-
try:
|
| 369 |
-
img = imdecode(req.image_b64)
|
| 370 |
-
except Exception:
|
| 371 |
-
raise HTTPException(status_code=400, detail="Bad image_b64")
|
| 372 |
-
|
| 373 |
-
faces = face.embed_all(img)
|
| 374 |
-
if not faces:
|
| 375 |
-
return IdentifyManyResp(detections=[])
|
| 376 |
-
|
| 377 |
-
detections: list[FaceDet] = []
|
| 378 |
-
top_k_db = req.top_k_db or settings.TOPK_DB
|
| 379 |
-
|
| 380 |
-
for bbox, emb, det_score in faces:
|
| 381 |
-
matches = index.query(emb, top_k=top_k_db)
|
| 382 |
-
agg = aggregate_by_user(matches)
|
| 383 |
-
user, best, margin_val = _decide_identity(agg, settings.THRESHOLD, settings.MARGIN)
|
| 384 |
-
topk = [IdentifyHit(user=u, score=s) for u, s in agg[:req.top_k]]
|
| 385 |
-
detections.append(FaceDet(
|
| 386 |
-
bbox=bbox,
|
| 387 |
-
decision=user,
|
| 388 |
-
best_score=best,
|
| 389 |
-
margin=margin_val,
|
| 390 |
-
topk=topk
|
| 391 |
-
))
|
| 392 |
-
|
| 393 |
-
return IdentifyManyResp(detections=detections)
|
| 394 |
-
|
| 395 |
-
@app.post("/query", response_model=QueryResp)
|
| 396 |
-
async def query(req: QueryReq, hf_token: str | None = Depends(get_hf_token)):
|
| 397 |
-
text = (req.text or "").strip()
|
| 398 |
-
if not text:
|
| 399 |
-
raise HTTPException(400, "Empty question")
|
| 400 |
-
|
| 401 |
-
sql_agent = build_agent_with_token(hf_token)
|
| 402 |
-
|
| 403 |
-
try:
|
| 404 |
-
answer_text, meta = sql_agent.ask(req.user_id, text)
|
| 405 |
-
citations = [f"sql:{meta['sql']}"]
|
| 406 |
-
return QueryResp(
|
| 407 |
-
answer_text=answer_text,
|
| 408 |
-
citations=citations,
|
| 409 |
-
metrics={},
|
| 410 |
-
chart_refs=[],
|
| 411 |
-
# uncertainty=0.15
|
| 412 |
-
)
|
| 413 |
-
except Exception as e:
|
| 414 |
-
raise HTTPException(status_code=400, detail=f"Query failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -5,7 +5,6 @@ pydantic-settings
|
|
| 5 |
numpy==1.26.4
|
| 6 |
faiss-cpu
|
| 7 |
insightface==0.7.3
|
| 8 |
-
# onnxruntime
|
| 9 |
onnxruntime==1.17.3
|
| 10 |
opencv-python==4.10.0.84
|
| 11 |
python-multipart
|
|
|
|
| 5 |
numpy==1.26.4
|
| 6 |
faiss-cpu
|
| 7 |
insightface==0.7.3
|
|
|
|
| 8 |
onnxruntime==1.17.3
|
| 9 |
opencv-python==4.10.0.84
|
| 10 |
python-multipart
|