File size: 11,488 Bytes
dc9113f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935dae1
 
 
 
 
 
 
 
 
 
 
 
 
dc9113f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import os
import re
import time
from typing import List, Optional

import faiss
import numpy as np
import pandas as pd
import requests
from datasets import load_dataset
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer

MODEL_NAME = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-chat-v3-0324")
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "").strip()

KNOWLEDGE_URL = os.getenv(
    "KNOWLEDGE_URL",
    "https://huggingface.co/datasets/sharshar1/arabic-hr-rag-dataset/resolve/main/knowledge_chunks.jsonl",
)
FAQ_URL = os.getenv(
    "FAQ_URL",
    "https://huggingface.co/datasets/sharshar1/arabic-hr-rag-dataset/resolve/main/faq_pairs.jsonl",
)

app = FastAPI(title="HR Genie RAG API", version="1.0.0")


class ChatRequest(BaseModel):
    message: str = Field(..., min_length=1, max_length=2000)
    session_id: Optional[str] = None
    user_id: Optional[int] = None


class SourceItem(BaseModel):
    title: str
    source_file: str
    score: float


class ChatResponse(BaseModel):
    answer: str
    mode: str
    sources: List[SourceItem]
    latency_ms: int


search_df: Optional[pd.DataFrame] = None
embedding_model: Optional[SentenceTransformer] = None
faiss_index = None
bm25 = None


def normalize_ar(text: str) -> str:
    text = str(text)
    text = re.sub(r"[\u064B-\u0652\u0670\u0640]", "", text)
    text = re.sub(r"[أإآٱ]", "ا", text)
    text = text.replace("ى", "ي").replace("ة", "ه")
    text = re.sub(r"\s+", " ", text).strip()
    return text


def simple_ar_tokenize(text: str) -> List[str]:
    text = normalize_ar(text)
    text = re.sub(r"[^\w\s]", " ", text)
    return text.split()


def detect_response_style(query: str) -> str:
    text = str(query).strip()
    arabic_chars = len(re.findall(r"[\u0600-\u06FF]", text))
    latin_chars = len(re.findall(r"[A-Za-z]", text))

    if latin_chars > arabic_chars and latin_chars > 0:
        return "english"

    if arabic_chars > 0:
        egyptian_markers = ["ازاي", "عاوز", "عايز", "ليه", "عامل", "ازيك", "دلوقتي", "ممكن"]
        lowered = text.lower()
        if any(marker in lowered for marker in egyptian_markers):
            return "egyptian_ar"
        return "fusha_ar"

    return "english"


def style_instruction(style: str) -> str:
    if style == "english":
        return "Answer in clear natural English."
    if style == "egyptian_ar":
        return "أجب باللهجة المصرية بشكل طبيعي وواضح، وبأسلوب شات بوت ودود."
    return "أجب بالعربية الفصحى بشكل واضح ومهذب."


def source_label_for_style(style: str) -> str:
    return "Source" if style == "english" else "المصدر"


def sanitize_model_output(text: str) -> str:
    text = str(text or "")
    text = re.sub(r"[\u4e00-\u9fff]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return re.sub(r"[ \t]{2,}", " ", text).strip()


def openrouter_chat(messages: List[dict], temperature: float = 0.2, max_tokens: int = 300) -> str:
    if not OPENROUTER_API_KEY:
        raise RuntimeError("OPENROUTER_API_KEY is missing.")

    url = "https://openrouter.ai/api/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
    }

    payload = {
        "model": MODEL_NAME,
        "messages": messages,
        "temperature": temperature,
        "max_tokens": max_tokens,
    }

    response = requests.post(url, headers=headers, json=payload, timeout=60)
    response.raise_for_status()
    data = response.json()
    return sanitize_model_output(data["choices"][0]["message"]["content"])


def load_data() -> pd.DataFrame:
    knowledge_ds = load_dataset("json", data_files=KNOWLEDGE_URL)["train"]
    faq_ds = load_dataset("json", data_files=FAQ_URL)["train"]

    knowledge_df = pd.DataFrame(knowledge_ds)
    faq_df = pd.DataFrame(faq_ds)

    knowledge_search = knowledge_df.copy()
    knowledge_search["search_text"] = (
        "الفئة: "
        + knowledge_search["category_ar"].fillna("")
        + "\nالعنوان: "
        + knowledge_search["topic"].fillna("")
        + "\nالمحتوى: "
        + knowledge_search["content"].fillna("")
    )
    knowledge_search["answer_text"] = knowledge_search["content"]
    knowledge_search["display_title"] = knowledge_search["topic"]
    knowledge_search["record_type"] = "knowledge"

    faq_search = faq_df.copy()
    faq_search["search_text"] = (
        "الفئة: "
        + faq_search["category_ar"].fillna("")
        + "\nالسؤال: "
        + faq_search["question"].fillna("")
        + "\nالإجابة: "
        + faq_search["answer"].fillna("")
    )
    faq_search["answer_text"] = faq_search["answer"]
    faq_search["display_title"] = faq_search["question"]
    faq_search["record_type"] = "faq"

    common_cols = [
        "category_ar",
        "source_file",
        "record_type",
        "display_title",
        "answer_text",
        "search_text",
    ]

    return pd.concat([knowledge_search[common_cols], faq_search[common_cols]], ignore_index=True)


def build_indexes() -> None:
    global search_df, embedding_model, faiss_index, bm25

    search_df = load_data()

    embedding_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")

    search_texts = search_df["search_text"].apply(normalize_ar).tolist()
    vectors = embedding_model.encode(
        search_texts,
        batch_size=32,
        convert_to_numpy=True,
        normalize_embeddings=True,
    ).astype("float32")

    faiss_index = faiss.IndexFlatIP(vectors.shape[1])
    faiss_index.add(vectors)

    bm25_corpus = [simple_ar_tokenize(t) for t in search_df["search_text"].tolist()]
    bm25 = BM25Okapi(bm25_corpus)


def retrieve(query: str, top_k: int = 3) -> List[dict]:
    if search_df is None or embedding_model is None or faiss_index is None or bm25 is None:
        raise RuntimeError("Indexes are not initialized.")

    query_norm = normalize_ar(query)

    query_vec = embedding_model.encode(
        [query_norm],
        convert_to_numpy=True,
        normalize_embeddings=True,
    ).astype("float32")

    vector_scores, vector_indices = faiss_index.search(query_vec, 8)

    bm25_scores = bm25.get_scores(simple_ar_tokenize(query_norm))
    bm25_top_idx = np.argsort(bm25_scores)[::-1][:8]

    merged = {}

    for rank, (score, idx) in enumerate(zip(vector_scores[0], vector_indices[0]), start=1):
        merged[int(idx)] = {
            "vector_rank": rank,
            "vector_score": float(score),
            "bm25_rank": None,
        }

    for rank, idx in enumerate(bm25_top_idx, start=1):
        idx = int(idx)
        merged.setdefault(
            idx,
            {
                "vector_rank": None,
                "vector_score": 0.0,
                "bm25_rank": None,
            },
        )
        merged[idx]["bm25_rank"] = rank

    items = []
    for idx, score_obj in merged.items():
        v_rank_score = 1.0 / score_obj["vector_rank"] if score_obj["vector_rank"] else 0.0
        b_rank_score = 1.0 / score_obj["bm25_rank"] if score_obj["bm25_rank"] else 0.0
        hybrid_score = 0.65 * v_rank_score + 0.35 * b_rank_score

        row = search_df.iloc[idx]
        items.append(
            {
                "display_title": str(row.get("display_title", "")),
                "answer_text": str(row.get("answer_text", "")),
                "source_file": str(row.get("source_file", "")),
                "record_type": str(row.get("record_type", "")),
                "category_ar": str(row.get("category_ar", "")),
                "score": float(hybrid_score),
            }
        )

    return sorted(items, key=lambda x: x["score"], reverse=True)[:top_k]


def build_prompt(query: str, chunks: List[dict]) -> str:
    style = detect_response_style(query)
    response_style_instruction = style_instruction(style)

    context = []
    for i, c in enumerate(chunks, start=1):
        context.append(
            "\n".join(
                [
                    f"[Source {i}]",
                    f"Type: {c['record_type']}",
                    f"Category: {c['category_ar']}",
                    f"Title: {c['display_title']}",
                    f"Content: {c['answer_text']}",
                    f"File: {c['source_file']}",
                ]
            )
        )

    context_text = "\n\n".join(context)

    return (
        "You are an HR smart assistant inside a company.\n\n"
        f"{response_style_instruction}\n\n"
        "Use the provided sources when they are relevant and enough.\n"
        "If the sources are not enough, answer naturally from general knowledge.\n"
        "Do not mention retrieval or hidden reasoning.\n"
        "Keep answers short, clear, and practical.\n"
        "If you used sources, add one final source line in the same language style.\n\n"
        f"Sources:\n{context_text}\n\n"
        f"User question:\n{query}\n\n"
        "Final answer:"
    )


def ask_assistant(query: str) -> dict:
    chunks = retrieve(query, top_k=3)
    style = detect_response_style(query)
    source_label = source_label_for_style(style)

    if not chunks:
        prompt = (
            "You are a smart and friendly assistant. "
            f"{style_instruction(style)} "
            "Answer naturally and briefly."
        )
        answer = openrouter_chat(
            [
                {"role": "system", "content": prompt},
                {"role": "user", "content": query},
            ],
            temperature=0.4,
            max_tokens=260,
        )
        return {"answer": answer, "mode": "general_chat", "sources": []}

    prompt = build_prompt(query, chunks)
    answer = openrouter_chat(
        [{"role": "user", "content": prompt}],
        temperature=0.15,
        max_tokens=300,
    )

    answer = sanitize_model_output(answer)

    if source_label not in answer and chunks[0]["source_file"]:
        answer = f"{answer}\n{source_label}\n{chunks[0]['source_file']}"

    sources = [
        {
            "title": c["display_title"],
            "source_file": c["source_file"],
            "score": round(c["score"], 4),
        }
        for c in chunks
    ]

    return {"answer": answer, "mode": "rag", "sources": sources}


@app.on_event("startup")
def on_startup() -> None:
    build_indexes()


@app.get("/")
def root() -> dict:
    return {
        "name": "HR Genie RAG API",
        "status": "running",
        "endpoints": {
            "health": "/health",
            "chat": "/chat",
            "docs": "/docs",
        },
    }


@app.get("/health")
def health() -> dict:
    return {"status": "ok", "model": MODEL_NAME, "has_openrouter_key": bool(OPENROUTER_API_KEY)}


@app.post("/chat", response_model=ChatResponse)
def chat(payload: ChatRequest) -> ChatResponse:
    start = time.time()

    try:
        result = ask_assistant(payload.message.strip())
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc

    latency_ms = int((time.time() - start) * 1000)

    sources = [SourceItem(**src) for src in result.get("sources", [])]

    return ChatResponse(
        answer=result.get("answer", ""),
        mode=result.get("mode", "unknown"),
        sources=sources,
        latency_ms=latency_ms,
    )