MohitGupta41 commited on
Commit
91cac95
·
1 Parent(s): f113950

Initial Commit

Browse files
.env ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Directories (already created in Dockerfile)
2
+ INDEX_DIR=/workspace/data/index
3
+ CACHE_DIR=/workspace/cache
4
+
5
+ # Face identification thresholds
6
+ THRESHOLD=0.50
7
+ MARGIN=0.05
8
+ TOPK_DB=20
9
+ TOPK_SHOW=3
10
+
11
+ # InsightFace providers (comma separated). Default in run.sh is CPU-only.
12
+ # For GPU container: CUDAExecutionProvider,CPUExecutionProvider
13
+ PROVIDERS=["CPUExecutionProvider"]
14
+
15
+ # Demo SQL path (sqlite); ":memory:" is also fine
16
+ SQLITE_PATH=/workspace/data/demo.db
Dockerfile ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"]
Dockerfile copy ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------
2
+ # Hugging Face Space (Docker)
3
+ # CPU-friendly default base
4
+ # --------------------------
5
+ FROM python:3.12-slim
6
+
7
+ # System deps (add build-essential + common runtime libs for OpenCV/ONNX)
8
+ RUN apt-get update && apt-get install -y --no-install-recommends \
9
+ build-essential gcc g++ make cmake pkg-config \
10
+ libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 libgomp1 git curl && \
11
+ rm -rf /var/lib/apt/lists/*
12
+
13
+ # Workspace & writable directories
14
+ ENV APP_HOME=/workspace
15
+ RUN mkdir -p $APP_HOME/app $APP_HOME/data $APP_HOME/cache && chmod -R 777 $APP_HOME
16
+ WORKDIR $APP_HOME
17
+
18
+ # (Optional but helps some builds)
19
+ ENV CC=gcc CXX=g++
20
+ ENV INSIGHTFACE_HOME=/workspace/cache/insightface
21
+ ENV MPLCONFIGDIR=/workspace/cache/matplotlib
22
+
23
+ # Python deps
24
+ COPY requirements.txt ./requirements.txt
25
+
26
+ # Pre-install numpy so headers are ready during builds
27
+ RUN pip install --no-cache-dir --upgrade pip && \
28
+ pip install --no-cache-dir "numpy<2.0; python_version<'3.12'" "numpy>=2.0; python_version>='3.12'" && \
29
+ pip install --no-cache-dir -r requirements.txt
30
+
31
+ # App
32
+ COPY app ./app
33
+ COPY run.sh ./run.sh
34
+ RUN chmod +x ./run.sh
35
+
36
+ ENV PORT=7860
37
+ CMD ["./run.sh"]
app/__init__.py ADDED
File without changes
app/deps.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/deps.py
2
+ from typing import Optional
3
+ from fastapi import Header
4
+
5
+ from app.settings import settings
6
+ from app.services.index_store import LocalIndex
7
+ from app.services.face_service import FaceService
8
+
9
+ # --- SQL agent pieces ---
10
+ from app.tools.sql_tool import SQLTool
11
+ from app.tools.llm_sqlgen import SQLGenTool
12
+ from app.tools.llm_answer import AnswerLLM
13
+ from app.services.agent_sql import SQLAgent
14
+
15
+ # ---------------- Vector index / Face ----------------
16
+ index = LocalIndex(settings.INDEX_DIR)
17
+
18
+ providers = settings.PROVIDERS
19
+ if isinstance(providers, str):
20
+ providers = [p.strip() for p in providers.split(",") if p.strip()]
21
+ face = FaceService(providers=providers)
22
+
23
+ # ---------------- SQL + Agents (singletons) ----------------
24
+ sql = SQLTool(db_path=settings.SQLITE_PATH)
25
+ sql.setup_demo_enterprise(start="2025-08-10", end="2025-09-10", seed=123)
26
+
27
+ _sqlgen = SQLGenTool(model_id=settings.LLM_MODEL_ID, token=settings.HF_TOKEN, timeout=settings.TIMEOUT)
28
+ _ansllm = AnswerLLM(model_id=settings.LLM_MODEL_ID, token=settings.HF_TOKEN, timeout=settings.TIMEOUT)
29
+ _sql_agent = SQLAgent(sql=sql, sqlgen=_sqlgen, answer_llm=_ansllm)
30
+
31
+
32
+ def get_hf_token(
33
+ authorization: Optional[str] = Header(None),
34
+ x_hf_token: Optional[str] = Header(None, convert_underscores=False),
35
+ ) -> Optional[str]:
36
+ if x_hf_token:
37
+ return x_hf_token.strip()
38
+ if authorization and authorization.lower().startswith("bearer "):
39
+ return authorization.split(" ", 1)[1].strip()
40
+ return None
41
+
42
+ def build_agent_with_token(hf_token: Optional[str]) -> SQLAgent:
43
+ """
44
+ Returns the shared SQLAgent but (temporarily) sets the token when present.
45
+ Avoids re-instantiating clients for every request.
46
+ """
47
+ if hf_token:
48
+ _sqlgen.set_token(hf_token)
49
+ _ansllm.set_token(hf_token)
50
+ else:
51
+ _sqlgen.set_token(settings.HF_TOKEN)
52
+ _ansllm.set_token(settings.HF_TOKEN)
53
+ return _sql_agent
app/main copy.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Query, Depends
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
+
14
+ app = FastAPI(title="Realtime BI Assistant")
15
+
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"], allow_credentials=True,
19
+ allow_methods=["*"], allow_headers=["*"],
20
+ )
21
+
22
+ @app.get("/")
23
+ def root():
24
+ return {"ok": True, "msg": "Backend alive"}
25
+
26
+ def _decide_identity(agg, threshold: float, margin: float):
27
+ if not agg:
28
+ return "Unknown", 0.0, 0.0
29
+ best_user, best_score = agg[0]
30
+ second = agg[1][1] if len(agg) > 1 else -1.0
31
+ margin_val = best_score - second
32
+ if best_score >= threshold and margin_val >= margin and best_user != "Unknown":
33
+ return best_user, best_score, margin_val
34
+ return "Unknown", best_score, margin_val
35
+
36
+ def _safe_extract(zf: zipfile.ZipFile, dest: str):
37
+ os.makedirs(dest, exist_ok=True)
38
+ for member in zf.infolist():
39
+ p = os.path.realpath(os.path.join(dest, member.filename))
40
+ if not p.startswith(os.path.realpath(dest) + os.sep):
41
+ continue
42
+ if member.is_dir():
43
+ os.makedirs(p, exist_ok=True)
44
+ else:
45
+ os.makedirs(os.path.dirname(p), exist_ok=True)
46
+ with zf.open(member) as src, open(p, "wb") as out:
47
+ out.write(src.read())
48
+
49
+ def _guess_images_root(tmpdir: str) -> str | None:
50
+ pref = os.path.join(tmpdir, "Images")
51
+ if os.path.isdir(pref):
52
+ return pref
53
+ for root, dirs, files in os.walk(tmpdir):
54
+ subdirs = [os.path.join(root, d) for d in dirs]
55
+ if subdirs and any(
56
+ any(fn.lower().endswith((".jpg",".jpeg",".png")) for fn in os.listdir(sd))
57
+ for sd in subdirs
58
+ ):
59
+ return root
60
+ return None
61
+
62
+ @app.post("/enroll_zip", response_model=EnrollResp)
63
+ async def enroll_zip(zipfile_upload: UploadFile = File(...)):
64
+ """
65
+ Accepts a ZIP with structure: Images/<UserName>/*.jpg|png
66
+ Upserts all faces into the local FAISS index under user metadata.
67
+ """
68
+ if not zipfile_upload.filename.lower().endswith(".zip"):
69
+ raise HTTPException(400, "Please upload a .zip")
70
+
71
+ raw = await zipfile_upload.read()
72
+ tmpdir = os.path.join("/workspace", "upload", uuid.uuid4().hex[:8])
73
+ os.makedirs(tmpdir, exist_ok=True)
74
+ try:
75
+ with zipfile.ZipFile(io.BytesIO(raw), "r") as zf:
76
+ _safe_extract(zf, tmpdir)
77
+
78
+ root = _guess_images_root(tmpdir)
79
+ if not root:
80
+ raise HTTPException(400, "Couldn't find 'Images/<UserName>/*' structure in ZIP")
81
+
82
+ user_dirs = sorted([p for p in glob.glob(os.path.join(root, "*")) if os.path.isdir(p)])
83
+ if not user_dirs:
84
+ raise HTTPException(400, "No user folders found under Images/")
85
+
86
+ total = 0
87
+ enrolled_users = []
88
+ for udir in user_dirs:
89
+ user = os.path.basename(udir)
90
+ paths = sorted([p for p in glob.glob(os.path.join(udir, "*")) if p.lower().endswith((".jpg",".jpeg",".png"))])
91
+ if not paths:
92
+ continue
93
+ count_user = 0
94
+ for p in paths:
95
+ img = cv2.imdecode(np.fromfile(p, dtype=np.uint8), cv2.IMREAD_COLOR)
96
+ if img is None: continue
97
+ bbox, emb, det_score = face.embed_best(img)
98
+ if emb is None: continue
99
+ vec = emb.astype(np.float32)
100
+ vec = vec / (np.linalg.norm(vec) + 1e-9)
101
+ vid = f"{user}::{uuid.uuid4().hex[:8]}"
102
+ index.add_vectors(vecs=np.array([vec]),
103
+ metas=[{"user":user,"det_score":float(det_score), "source":"enroll_zip"}],
104
+ ids=[vid])
105
+ count_user += 1
106
+ total += 1
107
+ if count_user > 0:
108
+ enrolled_users.append(user)
109
+
110
+ return EnrollResp(users=enrolled_users, total_vectors=total)
111
+ finally:
112
+ try:
113
+ shutil.rmtree(tmpdir, ignore_errors=True)
114
+ except Exception:
115
+ pass
116
+
117
+ # ---------- endpoints ----------
118
+ @app.post("/index/upsert_image")
119
+ async def upsert_image(user: str = Query(..., description="User label"),
120
+ image: UploadFile = File(...)):
121
+ raw = await image.read()
122
+ img = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
123
+ if img is None:
124
+ raise HTTPException(400, "Invalid image file")
125
+ bbox, emb, det_score = face.embed_best(img)
126
+ if emb is None:
127
+ return {"ok": False, "msg": "no face detected"}
128
+ vec = emb.astype(np.float32)
129
+ vec = vec / (np.linalg.norm(vec) + 1e-9)
130
+ vid = f"{user}::{uuid.uuid4().hex[:8]}"
131
+ index.add_vectors(vecs=np.array([vec]),
132
+ metas=[{"user":user,"det_score":float(det_score)}],
133
+ ids=[vid])
134
+ return {"ok": True, "id": vid, "user": user, "det_score": float(det_score)}
135
+
136
+ @app.post("/identify", response_model=IdentifyResp)
137
+ async def identify(req: IdentifyReq):
138
+ try:
139
+ img = imdecode(req.image_b64)
140
+ except Exception:
141
+ raise HTTPException(status_code=400, detail="Bad image_b64")
142
+ bbox, emb, det_score = face.embed_best(img)
143
+ if emb is None:
144
+ return IdentifyResp(decision="NoFace", best_score=0.0, margin=0.0, topk=[], bbox=None)
145
+
146
+ matches = index.query(emb, top_k=settings.TOPK_DB)
147
+ agg = aggregate_by_user(matches)
148
+
149
+ user, best, margin_val = _decide_identity(agg, settings.THRESHOLD, settings.MARGIN)
150
+ topk = [IdentifyHit(user=u, score=s) for u, s in agg[:req.top_k]]
151
+ return IdentifyResp(decision=user, best_score=best, margin=margin_val, topk=topk, bbox=bbox)
152
+
153
+ # ---------- NEW: multi-face endpoint ----------
154
+ @app.post("/identify_many", response_model=IdentifyManyResp)
155
+ async def identify_many(req: IdentifyManyReq):
156
+ try:
157
+ img = imdecode(req.image_b64)
158
+ except Exception:
159
+ raise HTTPException(status_code=400, detail="Bad image_b64")
160
+
161
+ faces = face.embed_all(img)
162
+ if not faces:
163
+ return IdentifyManyResp(detections=[])
164
+
165
+ detections: list[FaceDet] = []
166
+ top_k_db = req.top_k_db or settings.TOPK_DB
167
+
168
+ for bbox, emb, det_score in faces:
169
+ matches = index.query(emb, top_k=top_k_db)
170
+ agg = aggregate_by_user(matches)
171
+ user, best, margin_val = _decide_identity(agg, settings.THRESHOLD, settings.MARGIN)
172
+ topk = [IdentifyHit(user=u, score=s) for u, s in agg[:req.top_k]]
173
+ detections.append(FaceDet(
174
+ bbox=bbox,
175
+ decision=user,
176
+ best_score=best,
177
+ margin=margin_val,
178
+ topk=topk
179
+ ))
180
+
181
+ return IdentifyManyResp(detections=detections)
182
+
183
+ @app.post("/query", response_model=QueryResp)
184
+ async def query(req: QueryReq, hf_token: str | None = Depends(get_hf_token)):
185
+ text = (req.text or "").strip()
186
+ if not text:
187
+ raise HTTPException(400, "Empty question")
188
+
189
+ sql_agent = build_agent_with_token(hf_token)
190
+
191
+ try:
192
+ answer_text, meta = sql_agent.ask(req.user_id, text)
193
+ citations = [f"sql:{meta['sql']}"]
194
+ return QueryResp(
195
+ answer_text=answer_text,
196
+ citations=citations,
197
+ metrics={},
198
+ chart_refs=[],
199
+ # uncertainty=0.15
200
+ )
201
+ except Exception as e:
202
+ raise HTTPException(status_code=400, detail=f"Query failed: {e}")
app/main.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")
app/models/face.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # models/face.py
2
+ from pydantic import BaseModel, Field
3
+ from typing import List, Optional
4
+
5
+ class EnrollResp(BaseModel):
6
+ users: List[str] = Field(default_factory=list)
7
+ total_vectors: int
8
+
9
+ class IdentifyReq(BaseModel):
10
+ image_b64: str
11
+ top_k: int = 3
12
+
13
+ class IdentifyHit(BaseModel):
14
+ user: str
15
+ score: float
16
+
17
+ class IdentifyResp(BaseModel):
18
+ decision: str
19
+ best_score: float
20
+ margin: float
21
+ topk: List[IdentifyHit]
22
+ bbox: Optional[List[int]] = None
23
+
24
+ class FaceDet(BaseModel):
25
+ bbox: List[int]
26
+ decision: str
27
+ best_score: float
28
+ margin: float
29
+ topk: List[IdentifyHit] = Field(default_factory=list)
30
+
31
+ class IdentifyManyReq(BaseModel):
32
+ image_b64: str
33
+ top_k: int = 3
34
+ top_k_db: Optional[int] = None
35
+
36
+ class IdentifyManyResp(BaseModel):
37
+ detections: List[FaceDet] = Field(default_factory=list)
app/models/query.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ class QueryReq(BaseModel):
5
+ user_id: Optional[str] = None
6
+ text: str
7
+ visual_ctx: Optional[Dict[str, Any]] = Field(
8
+ default=None,
9
+ json_schema_extra={"example": {}},
10
+ )
11
+
12
+ class QueryResp(BaseModel):
13
+ answer_text: str
14
+ citations: List[str] = Field(default_factory=list)
15
+ metrics: Dict[str, Any] = Field(default_factory=dict)
16
+ chart_refs: List[str] = Field(default_factory=list)
17
+ # uncertainty: float = 0.0
app/services/agent_sql.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/services/agent_sql.py
2
+ from typing import Dict, Any, Tuple
3
+ from app.tools.sql_tool import SQLTool
4
+ from app.tools.llm_sqlgen import SQLGenTool
5
+ from app.tools.llm_answer import AnswerLLM
6
+
7
+ class SQLAgent:
8
+ def __init__(self, sql: SQLTool, sqlgen: SQLGenTool, answer_llm: AnswerLLM):
9
+ self.sql = sql
10
+ self.sqlgen = sqlgen
11
+ self.answer_llm = answer_llm
12
+
13
+ def ask(self, user_id: str | None, question: str) -> Tuple[str, Dict[str, Any]]:
14
+ sql = self.sqlgen.generate_sql(question)
15
+ result = self.sql.execute_sql_readonly(sql)
16
+ answer = self.answer_llm.generate(question, sql, result["columns"], result["rows"])
17
+ meta = {
18
+ "sql": sql,
19
+ "rowcount": result["rowcount"],
20
+ "columns": result["columns"],
21
+ }
22
+ return answer, meta
app/services/aggregator.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ import numpy as np
3
+
4
+ def aggregate_by_user(matches):
5
+ per_user = defaultdict(list)
6
+ for m in matches:
7
+ u = (m.get("metadata") or {}).get("user", "Unknown")
8
+ per_user[u].append(m["score"])
9
+ agg = [(u, float(np.max(v))) for u, v in per_user.items()]
10
+ agg.sort(key=lambda x: x[1], reverse=True)
11
+ return agg
app/services/face_service.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services/face_service.py
2
+ import os, base64, cv2, numpy as np
3
+
4
+ os.environ.setdefault("HOME", "/workspace")
5
+ os.environ.setdefault("INSIGHTFACE_HOME", "/workspace/cache/insightface")
6
+ os.environ.setdefault("MPLCONFIGDIR", "/workspace/cache/matplotlib")
7
+ os.makedirs(os.environ["INSIGHTFACE_HOME"], exist_ok=True)
8
+ os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)
9
+
10
+ from insightface.app import FaceAnalysis
11
+
12
+ def imdecode(b64: str):
13
+ raw = base64.b64decode(b64)
14
+ arr = np.frombuffer(raw, np.uint8)
15
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
16
+ if img is None:
17
+ raise ValueError("Bad image_b64")
18
+ return img
19
+
20
+ class FaceService:
21
+ def __init__(self, providers):
22
+ cache_root = os.environ["INSIGHTFACE_HOME"]
23
+ self.app = FaceAnalysis(
24
+ name="buffalo_l",
25
+ providers=providers,
26
+ root=cache_root,
27
+ )
28
+ self.app.prepare(ctx_id=0, det_size=(640, 640))
29
+
30
+ def embed_best(self, img_bgr):
31
+ faces = self.app.get(img_bgr)
32
+ if not faces:
33
+ return None, None, None
34
+ best = max(faces, key=lambda f: (f.bbox[2]-f.bbox[0])*(f.bbox[3]-f.bbox[1]))
35
+ bbox = best.bbox.astype(int).tolist()
36
+ emb = best.normed_embedding
37
+ score = float(getattr(best, 'det_score', 1.0))
38
+ return bbox, emb, score
39
+
40
+ def embed_all(self, img_bgr):
41
+ faces = self.app.get(img_bgr)
42
+ out = []
43
+ for f in faces:
44
+ bbox = f.bbox.astype(int).tolist()
45
+ emb = f.normed_embedding
46
+ score = float(getattr(f, 'det_score', 1.0))
47
+ out.append((bbox, emb, score))
48
+ return out
app/services/index_store.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json
2
+ import numpy as np
3
+ import faiss
4
+
5
+ class LocalIndex:
6
+ def __init__(self, index_dir: str):
7
+ self.index_dir = index_dir
8
+ self.index_path = os.path.join(index_dir, "faiss.index")
9
+ self.ids_path = os.path.join(index_dir, "ids.npy")
10
+ self.meta_path = os.path.join(index_dir, "meta.json")
11
+
12
+ if os.path.exists(self.index_path) and os.path.exists(self.ids_path) and os.path.exists(self.meta_path):
13
+ self.index = faiss.read_index(self.index_path)
14
+ self.local_ids = list(np.load(self.ids_path, allow_pickle=True))
15
+ with open(self.meta_path, "r") as f:
16
+ self.local_meta = json.load(f)
17
+ else:
18
+ self.index = faiss.IndexFlatIP(512)
19
+ self.local_ids = []
20
+ self.local_meta = {}
21
+ self._persist()
22
+
23
+ def _persist(self):
24
+ faiss.write_index(self.index, self.index_path)
25
+ np.save(self.ids_path, np.array(self.local_ids, dtype=object), allow_pickle=True)
26
+ with open(self.meta_path, "w") as f:
27
+ json.dump(self.local_meta, f)
28
+
29
+ def add_vectors(self, vecs: np.ndarray, metas: list, ids: list):
30
+ vecs = vecs.astype(np.float32)
31
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True) + 1e-9
32
+ vecs = vecs / norms
33
+ self.index.add(vecs)
34
+ for vid, meta in zip(ids, metas):
35
+ self.local_ids.append(vid)
36
+ self.local_meta[vid] = meta
37
+ self._persist()
38
+
39
+ def query(self, emb: np.ndarray, top_k: int):
40
+ q = emb.astype(np.float32)
41
+ q = q / (np.linalg.norm(q) + 1e-9)
42
+ D, I = self.index.search(q.reshape(1, -1), top_k)
43
+ out = []
44
+ for score, idx in zip(D[0], I[0]):
45
+ if idx == -1:
46
+ continue
47
+ vid = self.local_ids[idx]
48
+ out.append({"id": vid, "score": float(score), "metadata": dict(self.local_meta.get(vid, {}))})
49
+ return out
app/settings.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from pydantic_settings import BaseSettings, SettingsConfigDict
3
+ from pydantic import Field, AliasChoices, computed_field
4
+ import json, os
5
+
6
+ # ensure sane defaults for caches
7
+ os.environ.setdefault("HOME", "/workspace")
8
+ os.environ.setdefault("INSIGHTFACE_HOME", "/workspace/cache/insightface")
9
+ os.environ.setdefault("MPLCONFIGDIR", "/workspace/cache/matplotlib")
10
+
11
+ class Settings(BaseSettings):
12
+ model_config = SettingsConfigDict(env_file=".env", extra="ignore")
13
+ INDEX_DIR: str = "/workspace/data/index"
14
+ CACHE_DIR: str = "/workspace/cache"
15
+ THRESHOLD: float = 0.50
16
+ MARGIN: float = 0.05
17
+ TIMEOUT: int = 180
18
+ TOPK_DB: int = 20
19
+ TOPK_SHOW: int = 3
20
+ SQLITE_PATH: str = "/workspace/data/demo.db"
21
+
22
+ LLM_MODEL_ID: str = "google/gemma-3-27b-it"
23
+ HF_TOKEN: Optional[str] = None
24
+ LLM_MAX_NEW_TOKENS: int = 200
25
+ LLM_TEMPERATURE: float = 0.2
26
+
27
+ PROVIDERS_RAW: Optional[str] = Field(default=None, validation_alias=AliasChoices("PROVIDERS"))
28
+
29
+ @computed_field(return_type=List[str])
30
+ @property
31
+ def PROVIDERS(self) -> List[str]:
32
+ s = (self.PROVIDERS_RAW or "").strip()
33
+ if not s:
34
+ return ["CPUExecutionProvider"]
35
+ if s.startswith("["):
36
+ return json.loads(s)
37
+ return [p.strip() for p in s.split(",") if p.strip()]
38
+
39
+ settings = Settings()
40
+ os.makedirs(settings.INDEX_DIR, exist_ok=True)
41
+ os.makedirs(settings.CACHE_DIR, exist_ok=True)
app/tools/llm_answer.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/tools/llm_answer.py
2
+ from __future__ import annotations
3
+ from typing import Optional, Dict, Any, List
4
+ import requests, json
5
+
6
+ HF_CHAT_URL = "https://router.huggingface.co/featherless-ai/v1/chat/completions"
7
+
8
+ SYSTEM_PROMPT = """You are a BI copilot.
9
+ - NEVER invent numbers; only summarize from provided table rows.
10
+ - Use 3-letter region codes (NCR, BLR, MUM, HYD, CHN, PUN).
11
+ - Write one concise paragraph and up to 2 brief bullets with clear takeaways.
12
+ - If you donot get any response then just say that donot invent anything new.
13
+ """
14
+
15
+ class AnswerLLM:
16
+ def __init__(self, model_id: str, token: Optional[str], temperature: float = 0.2, max_tokens: int = 300, timeout: int = 60):
17
+ self.model_id = model_id
18
+ self.token = token
19
+ self.temperature = temperature
20
+ self.max_tokens = max_tokens
21
+ self.timeout = timeout
22
+ self.enabled = bool(token and model_id)
23
+
24
+ def set_token(self, token: Optional[str]) -> None:
25
+ self.token = token
26
+ self.enabled = bool(token and self.model_id)
27
+
28
+ def generate(self, question: str, sql: str, columns: List[str], rows: List[list]) -> str:
29
+ if not self.enabled:
30
+ # deterministic fallback
31
+ return f"Rows: {len(rows)} | Columns: {columns[:4]}..."
32
+ # keep rows small in prompt; if big, sample top-N
33
+ preview = rows if len(rows) <= 50 else rows[:50]
34
+ table_json = json.dumps({"columns": columns, "rows": preview}, ensure_ascii=False)
35
+ payload = {
36
+ "model": self.model_id,
37
+ "stream": False,
38
+ "messages": [
39
+ {"role":"system", "content":[{"type":"text","text":SYSTEM_PROMPT}]},
40
+ {"role":"user", "content":[
41
+ {"type":"text","text": f"Question: {question}\nSQL used:\n{sql}\n\nHere are the rows (JSON):\n{table_json}\n\nAnswer:"}
42
+ ]},
43
+ ],
44
+ "temperature": self.temperature,
45
+ "max_tokens": self.max_tokens,
46
+ }
47
+ headers = {"Authorization": f"Bearer {self.token}"}
48
+ r = requests.post(HF_CHAT_URL, headers=headers, json=payload, timeout=self.timeout)
49
+ r.raise_for_status()
50
+ return r.json()["choices"][0]["message"]["content"]
app/tools/llm_sqlgen.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/tools/llm_sqlgen.py
2
+ from __future__ import annotations
3
+ from typing import Optional, Dict, Any
4
+ import requests, json
5
+
6
+ HF_CHAT_URL = "https://router.huggingface.co/featherless-ai/v1/chat/completions"
7
+
8
+ SCHEMA_SPEC = """
9
+ Tables and columns (SQLite):
10
+
11
+ dim_region(code, name)
12
+ dim_product(sku, category, name, price)
13
+ dim_employee(emp_id, name, region_code, role, hire_date)
14
+
15
+ fact_sales(day, region_code, sku, channel, units, revenue)
16
+ fact_sales_detail(day, region_code, sku, channel, employee_id, units, revenue)
17
+
18
+ inv_stock(day, region_code, sku, on_hand_qty)
19
+
20
+ Rules:
21
+ - Use only SELECT. Never modify data.
22
+ - Prefer ISO date literals 'YYYY-MM-DD'.
23
+ - Region codes are 3 letters: NCR, BLR, MUM, HYD, CHN, PUN.
24
+ - For monthly rollups use strftime('%Y-%m', day).
25
+ - Join to dim_product when you need category/name/price.
26
+ - For per-employee metrics use fact_sales_detail (employee_id may be NULL for Online).
27
+ """
28
+
29
+ FEW_SHOTS = [
30
+ {
31
+ "q": "What is monthly revenue for Electronics in BLR for 2025-09?",
32
+ "sql": """SELECT strftime('%Y-%m', fs.day) AS month, SUM(fs.revenue) AS revenue
33
+ FROM fact_sales fs
34
+ JOIN dim_product p ON p.sku = fs.sku
35
+ WHERE fs.region_code='BLR' AND p.category='Electronics' AND fs.day BETWEEN '2025-09-01' AND '2025-09-30'
36
+ GROUP BY month
37
+ ORDER BY month"""
38
+ },
39
+ {
40
+ "q": "Show Ramesh's sales (units and revenue) in NCR on 2025-09-06",
41
+ "sql": """SELECT e.name, d.units, d.revenue
42
+ FROM fact_sales_detail d
43
+ JOIN dim_employee e ON e.emp_id = d.employee_id
44
+ WHERE e.name LIKE 'Ramesh %' AND d.region_code='NCR' AND d.day='2025-09-06'"""
45
+ },
46
+ {
47
+ "q": "What's the on-hand stock for sku ELEC-002 in MUM on 2025-09-05?",
48
+ "sql": """SELECT on_hand_qty
49
+ FROM inv_stock
50
+ WHERE region_code='MUM' AND sku='ELEC-002' AND day='2025-09-05'"""
51
+ },
52
+ {
53
+ "q": "Top 5 SKUs by revenue in HYD on 2025-09-06 (include category)",
54
+ "sql": """SELECT fs.sku, p.category, SUM(fs.revenue) AS rev
55
+ FROM fact_sales fs
56
+ JOIN dim_product p ON p.sku=fs.sku
57
+ WHERE fs.region_code='HYD' AND fs.day='2025-09-06'
58
+ GROUP BY fs.sku, p.category
59
+ ORDER BY rev DESC
60
+ LIMIT 5"""
61
+ }
62
+ ]
63
+
64
+ class SQLGenTool:
65
+ def __init__(self, model_id: str, token: Optional[str], temperature: float = 0.0, max_tokens: int = 400, timeout: int = 60):
66
+ self.model_id = model_id
67
+ self.token = token
68
+ self.temperature = temperature
69
+ self.max_tokens = max_tokens
70
+ self.timeout = timeout
71
+ self.enabled = bool(token and model_id)
72
+
73
+ def set_token(self, token: Optional[str]) -> None:
74
+ self.token = token
75
+ self.enabled = bool(token and self.model_id)
76
+
77
+ def generate_sql(self, question: str) -> str:
78
+ if not self.enabled:
79
+ raise RuntimeError("SQLGenTool disabled: missing HF token or model_id.")
80
+ fewshot_txt = "\n".join([f"Q: {ex['q']}\nSQL:\n{ex['sql']}\n" for ex in FEW_SHOTS])
81
+ sys = (
82
+ "You are a SQL generator. Output only a single JSON object: {\"sql\": \"...\"}.\n"
83
+ "No prose. No explanations. Use the provided schema only.\n" + SCHEMA_SPEC
84
+ )
85
+ user = f"Question:\n{question}\n\nReturn JSON with a single key 'sql'."
86
+ payload = {
87
+ "model": self.model_id,
88
+ "stream": False,
89
+ "messages": [
90
+ {"role":"system","content":[{"type":"text","text":sys}]},
91
+ {"role":"user","content":[{"type":"text","text":fewshot_txt + "\n\n" + user}]},
92
+ ],
93
+ "temperature": self.temperature,
94
+ "max_tokens": self.max_tokens,
95
+ }
96
+ headers = {"Authorization": f"Bearer {self.token}"}
97
+ r = requests.post(HF_CHAT_URL, headers=headers, json=payload, timeout=self.timeout)
98
+ r.raise_for_status()
99
+ content = r.json()["choices"][0]["message"]["content"].strip()
100
+ s, e = content.find("{"), content.rfind("}")
101
+ obj = json.loads(content[s:e+1])
102
+ sql = obj.get("sql","").strip()
103
+ return sql
app/tools/powerbi_tool.py ADDED
File without changes
app/tools/sql_tool.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/tools/sql_tool.py
2
+ import os, sqlite3, random, math, string
3
+ from datetime import date, timedelta
4
+ from typing import Optional, Dict, Any, List, Tuple
5
+
6
+ REGIONS: List[Tuple[str, str]] = [
7
+ ("NCR", "Delhi NCR"),
8
+ ("BLR", "Bengaluru"),
9
+ ("MUM", "Mumbai"),
10
+ ("HYD", "Hyderabad"),
11
+ ("CHN", "Chennai"),
12
+ ("PUN", "Pune"),
13
+ ]
14
+
15
+ PRODUCTS: List[Tuple[str, str, str, float]] = [
16
+ ("ELEC-001", "Electronics", "Smartphone Alpha", 29999.0),
17
+ ("ELEC-002", "Electronics", "Smartphone Pro", 49999.0),
18
+ ("ELEC-003", "Electronics", "Laptop 14\"", 65999.0),
19
+ ("ELEC-004", "Electronics", "Earbuds", 3999.0),
20
+ ("APP-001", "Apparel", "Athleisure Tee", 999.0),
21
+ ("APP-002", "Apparel", "Formal Shirt", 1599.0),
22
+ ("APP-003", "Apparel", "Denim Jeans", 2499.0),
23
+ ("GROC-001", "Grocery", "Olive Oil 1L", 799.0),
24
+ ("GROC-002", "Grocery", "Basmati 5kg", 899.0),
25
+ ("GROC-003", "Grocery", "Almonds 1kg", 1199.0),
26
+ ("HOME-001", "Home", "Mixer Grinder", 3499.0),
27
+ ("HOME-002", "Home", "Air Fryer", 6999.0),
28
+ ]
29
+
30
+ def _rand_name(rnd: random.Random):
31
+ first = ["Ramesh","Suresh","Mahesh","Amit","Priya","Anita","Kiran","Sunil","Neha","Pooja","Ravi","Vijay","Anil","Meera","Tarun"]
32
+ last = ["Kumar","Sharma","Patel","Verma","Reddy","Iyer","Das","Ghosh","Yadav","Gupta","Singh","Menon"]
33
+ return f"{rnd.choice(first)} {rnd.choice(last)}"
34
+
35
+ class SQLTool:
36
+ """
37
+ Enterprise-ish SQLite schema with dims/facts and safe read-only SQL execution.
38
+
39
+ dim_region(code, name)
40
+ dim_product(sku, category, name, price)
41
+ dim_employee(emp_id, name, region_code, role, hire_date)
42
+
43
+ fact_sales(day, region_code, sku, channel, units, revenue) -- daily aggregates
44
+ fact_sales_detail(day, region_code, sku, channel, employee_id, units, revenue) -- retail split by employee
45
+
46
+ inv_stock(day, region_code, sku, on_hand_qty)
47
+ """
48
+
49
+ def __init__(self, db_path: Optional[str] = None):
50
+ path = db_path or os.getenv("SQLITE_PATH", ":memory:")
51
+ self.path = path
52
+ self.conn = sqlite3.connect(path, check_same_thread=False)
53
+ self.conn.execute("PRAGMA journal_mode=WAL;")
54
+ self.conn.execute("PRAGMA synchronous=NORMAL;")
55
+
56
+ # ---------------------- schema & seed ----------------------
57
+ def setup_demo_enterprise(self, start: str = "2025-08-10", end: str = "2025-09-10", seed: int = 42):
58
+ cur = self.conn.cursor()
59
+ cur.executescript(
60
+ """
61
+ CREATE TABLE IF NOT EXISTS dim_region (
62
+ code TEXT PRIMARY KEY,
63
+ name TEXT NOT NULL
64
+ );
65
+ CREATE TABLE IF NOT EXISTS dim_product (
66
+ sku TEXT PRIMARY KEY,
67
+ category TEXT NOT NULL,
68
+ name TEXT NOT NULL,
69
+ price REAL NOT NULL
70
+ );
71
+ CREATE TABLE IF NOT EXISTS dim_employee (
72
+ emp_id TEXT PRIMARY KEY,
73
+ name TEXT NOT NULL,
74
+ region_code TEXT NOT NULL REFERENCES dim_region(code),
75
+ role TEXT NOT NULL,
76
+ hire_date TEXT NOT NULL
77
+ );
78
+ CREATE TABLE IF NOT EXISTS fact_sales (
79
+ day TEXT NOT NULL,
80
+ region_code TEXT NOT NULL REFERENCES dim_region(code),
81
+ sku TEXT NOT NULL REFERENCES dim_product(sku),
82
+ channel TEXT NOT NULL,
83
+ units INTEGER NOT NULL,
84
+ revenue REAL NOT NULL,
85
+ PRIMARY KEY (day, region_code, sku, channel)
86
+ );
87
+ CREATE TABLE IF NOT EXISTS fact_sales_detail (
88
+ day TEXT NOT NULL,
89
+ region_code TEXT NOT NULL REFERENCES dim_region(code),
90
+ sku TEXT NOT NULL REFERENCES dim_product(sku),
91
+ channel TEXT NOT NULL,
92
+ employee_id TEXT NULL REFERENCES dim_employee(emp_id),
93
+ units INTEGER NOT NULL,
94
+ revenue REAL NOT NULL
95
+ );
96
+ CREATE TABLE IF NOT EXISTS inv_stock (
97
+ day TEXT NOT NULL,
98
+ region_code TEXT NOT NULL REFERENCES dim_region(code),
99
+ sku TEXT NOT NULL REFERENCES dim_product(sku),
100
+ on_hand_qty INTEGER NOT NULL,
101
+ PRIMARY KEY (day, region_code, sku)
102
+ );
103
+
104
+ CREATE INDEX IF NOT EXISTS idx_sales_day ON fact_sales(day);
105
+ CREATE INDEX IF NOT EXISTS idx_sales_region ON fact_sales(region_code);
106
+ CREATE INDEX IF NOT EXISTS idx_sales_sku ON fact_sales(sku);
107
+ CREATE INDEX IF NOT EXISTS idx_sales_day_region ON fact_sales(day, region_code);
108
+
109
+ CREATE INDEX IF NOT EXISTS idx_detail_day_region ON fact_sales_detail(day, region_code);
110
+ CREATE INDEX IF NOT EXISTS idx_detail_emp ON fact_sales_detail(employee_id);
111
+
112
+ CREATE INDEX IF NOT EXISTS idx_stock_day_region ON inv_stock(day, region_code);
113
+ """
114
+ )
115
+
116
+ existing = set(r[0] for r in cur.execute("SELECT code FROM dim_region"))
117
+ to_ins = [(c, n) for c, n in REGIONS if c not in existing]
118
+ if to_ins:
119
+ cur.executemany("INSERT INTO dim_region(code, name) VALUES (?,?)", to_ins)
120
+
121
+ existing_sku = set(r[0] for r in cur.execute("SELECT sku FROM dim_product"))
122
+ to_ins_p = [p for p in PRODUCTS if p[0] not in existing_sku]
123
+ if to_ins_p:
124
+ cur.executemany("INSERT INTO dim_product(sku, category, name, price) VALUES (?,?,?,?)", to_ins_p)
125
+
126
+ emp_count = cur.execute("SELECT COUNT(*) FROM dim_employee").fetchone()[0]
127
+ rnd = random.Random(seed)
128
+ if emp_count == 0:
129
+ rows = []
130
+ for code, _ in REGIONS:
131
+ n = 8
132
+ for _ in range(n):
133
+ emp_id = f"E{code}{rnd.randint(1000,9999)}"
134
+ rows.append((emp_id, _rand_name(rnd), code, rnd.choice(["AE","SE","AM"]), "2023-01-01"))
135
+ cur.executemany("INSERT INTO dim_employee(emp_id,name,region_code,role,hire_date) VALUES (?,?,?,?,?)", rows)
136
+
137
+ n_sales = cur.execute("SELECT COUNT(*) FROM fact_sales").fetchone()[0]
138
+ if n_sales == 0:
139
+ self._seed_fact_sales(cur, start, end, seed)
140
+
141
+ n_detail = cur.execute("SELECT COUNT(*) FROM fact_sales_detail").fetchone()[0]
142
+ if n_detail == 0:
143
+ self._seed_sales_detail(cur, seed)
144
+
145
+ n_stock = cur.execute("SELECT COUNT(*) FROM inv_stock").fetchone()[0]
146
+ if n_stock == 0:
147
+ self._seed_stock(cur, start, end, seed)
148
+
149
+ self.conn.commit()
150
+
151
+ def _seed_fact_sales(self, cur: sqlite3.Cursor, start: str, end: str, seed: int):
152
+ rnd = random.Random(seed)
153
+ start_d = date.fromisoformat(start)
154
+ end_d = date.fromisoformat(end)
155
+ days = (end_d - start_d).days + 1
156
+ region_factor = {"NCR":1.25,"MUM":1.15,"BLR":1.10,"HYD":0.95,"CHN":0.90,"PUN":0.85}
157
+ channels = ["Online","Retail"]
158
+
159
+ batch = []
160
+ for i in range(days):
161
+ d = (start_d + timedelta(days=i)).isoformat()
162
+ wknd = (start_d + timedelta(days=i)).weekday() >= 5
163
+ wknd_boost = 1.10 if wknd else 1.0
164
+ for code, _name in REGIONS:
165
+ rfac = region_factor[code]
166
+ for sku, category, _nm, price in PRODUCTS:
167
+ for ch in channels:
168
+ base = {"Electronics":12,"Apparel":25,"Grocery":40,"Home":9}[category]
169
+ ch_mult = 1.15 if ch == "Online" else 0.95
170
+ mu = base * rfac * wknd_boost * ch_mult
171
+ sigma = max(1.0, mu * 0.25)
172
+ units = max(0, int(rnd.gauss(mu, sigma)))
173
+ season = 1.0 + 0.08 * math.sin(i / 3.5)
174
+ revenue = round(units * price * season, 2)
175
+ batch.append((d, code, sku, ch, units, revenue))
176
+ cur.executemany(
177
+ "INSERT INTO fact_sales(day, region_code, sku, channel, units, revenue) VALUES (?,?,?,?,?,?)",
178
+ batch
179
+ )
180
+
181
+ def _seed_sales_detail(self, cur: sqlite3.Cursor, seed: int):
182
+ rnd = random.Random(seed+7)
183
+ rows = cur.execute(
184
+ "SELECT day, region_code, sku, units, revenue FROM fact_sales WHERE channel='Retail'"
185
+ ).fetchall()
186
+
187
+ for d, region, sku, units, revenue in rows:
188
+ if units == 0:
189
+ continue
190
+ emp_ids = [r[0] for r in cur.execute("SELECT emp_id FROM dim_employee WHERE region_code=?", (region,))]
191
+ parts = rnd.randint(1, min(4, max(1, units)))
192
+ cuts = sorted(rnd.sample(range(1, units), parts-1)) if units > parts else []
193
+ splits = [b-a for a,b in zip([0]+cuts, cuts+[units])]
194
+ total_units = float(sum(splits))
195
+ rev_splits = [round(revenue * (u/total_units), 2) for u in splits]
196
+ if rev_splits:
197
+ drift = round(revenue - sum(rev_splits), 2)
198
+ rev_splits[0] += drift
199
+ for u, r in zip(splits, rev_splits):
200
+ emp = rnd.choice(emp_ids) if emp_ids else None
201
+ cur.execute(
202
+ "INSERT INTO fact_sales_detail(day, region_code, sku, channel, employee_id, units, revenue) "
203
+ "VALUES (?,?,?,?,?,?,?)",
204
+ (d, region, sku, "Retail", emp, u, r)
205
+ )
206
+
207
+ def _seed_stock(self, cur: sqlite3.Cursor, start: str, end: str, seed: int):
208
+ rnd = random.Random(seed+13)
209
+ start_d = date.fromisoformat(start)
210
+ end_d = date.fromisoformat(end)
211
+ days = (end_d - start_d).days + 1
212
+
213
+ for i in range(days):
214
+ d = (start_d + timedelta(days=i)).isoformat()
215
+ for code, _ in REGIONS:
216
+ for sku, category, _nm, _price in PRODUCTS:
217
+ base = {"Electronics":400,"Apparel":800,"Grocery":600,"Home":300}[category]
218
+ noise = rnd.randint(-30, 30)
219
+ on_hand = max(0, base + noise - i*2)
220
+ cur.execute(
221
+ "INSERT INTO inv_stock(day, region_code, sku, on_hand_qty) VALUES (?,?,?,?)",
222
+ (d, code, sku, on_hand)
223
+ )
224
+
225
+ # ---------------------- helpers + read-only executor ----------------------
226
+ def region_codes(self) -> List[str]:
227
+ rows = self.conn.execute("SELECT code FROM dim_region").fetchall()
228
+ return [r[0] for r in rows]
229
+
230
+ def execute_sql_readonly(self, sql: str) -> Dict[str, Any]:
231
+ """Hard safety: allow only a single SELECT statement; no comments/CTEs with semicolons."""
232
+ s = sql.strip()
233
+ bad = (";", "--", "/*", "*/")
234
+ if not s.lower().startswith("select"):
235
+ raise ValueError("Only SELECT statements are allowed.")
236
+ if any(tok in s for tok in bad):
237
+ raise ValueError("Disallowed token in SQL.")
238
+ cur = self.conn.cursor()
239
+ cur.execute(s)
240
+ cols = [d[0] for d in cur.description] if cur.description else []
241
+ rows = cur.fetchall()
242
+ return {"columns": cols, "rows": rows, "rowcount": len(rows)}
243
+
244
+ if __name__ == "__main__":
245
+ import argparse
246
+ import os
247
+ import sys
248
+ from pathlib import Path
249
+
250
+ parser = argparse.ArgumentParser(
251
+ description="Create and persist the demo enterprise SQLite database."
252
+ )
253
+ parser.add_argument(
254
+ "--db",
255
+ default=os.getenv("SQLITE_PATH", "./demo_enterprise.sqlite"),
256
+ help="Path to the SQLite DB file to create (defaults to ./demo_enterprise.sqlite or $SQLITE_PATH).",
257
+ )
258
+ parser.add_argument(
259
+ "--start",
260
+ default="2025-08-10",
261
+ help="Start date (YYYY-MM-DD) for seeding data.",
262
+ )
263
+ parser.add_argument(
264
+ "--end",
265
+ default="2025-09-10",
266
+ help="End date (YYYY-MM-DD) for seeding data.",
267
+ )
268
+ parser.add_argument(
269
+ "--seed",
270
+ type=int,
271
+ default=42,
272
+ help="Random seed used for deterministic seeding.",
273
+ )
274
+ args = parser.parse_args()
275
+
276
+ # Ensure we persist to disk (avoid in-memory DB).
277
+ db_path = args.db
278
+ if db_path == ":memory:":
279
+ print("':memory:' was requested; switching to ./demo_enterprise.sqlite so the DB is saved to disk.")
280
+ db_path = "./demo_enterprise.db"
281
+
282
+ # Make sure the parent directory exists
283
+ parent = Path(db_path).expanduser().resolve().parent
284
+ parent.mkdir(parents=True, exist_ok=True)
285
+
286
+ tool = SQLTool(db_path=str(Path(db_path).expanduser()))
287
+ tool.setup_demo_enterprise(start=args.start, end=args.end, seed=args.seed)
288
+
289
+ # Flush and close
290
+ tool.conn.commit()
291
+ tool.conn.close()
292
+
293
+ print(f"✅ Database created at: {Path(db_path).expanduser().resolve()}")
294
+ print(f" Seed window: {args.start} → {args.end} | seed={args.seed}")
295
+
296
+ # # Default location ./demo_enterprise.sqlite
297
+ # python app/tools/sql_tool.py
298
+
299
+ # # Custom location and date range
300
+ # python BI_Assistant_Backend/app/tools/sql_tool.py --db ./data/retail_demo.sqlite --start 2025-08-01 --end 2025-09-10 --seed 123
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ pydantic
4
+ 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
12
+ requests
13
+ Pillow
14
+ huggingface_hub
run.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONUNBUFFERED=1
4
+
5
+ # If user sets PROVIDERS env, use it; else default to CPU provider
6
+ export PROVIDERS="${PROVIDERS:-CPUExecutionProvider}"
7
+ export INSIGHTFACE_HOME=/workspace/cache/insightface
8
+ export MPLCONFIGDIR=/workspace/cache/matplotlib
9
+
10
+ mkdir -p "$INSIGHTFACE_HOME" "$MPLCONFIGDIR"
11
+
12
+ # Start FastAPI
13
+ uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}