File size: 4,740 Bytes
c22088c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import faiss
import torch
import numpy as np

from fastapi import FastAPI
from contextlib import asynccontextmanager
from pydantic import BaseModel
from huggingface_hub import snapshot_download
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForCausalLM

# ─────────────────────────────
# CONFIG
# ─────────────────────────────
MODEL_REPO = "Qwen/Qwen2.5-0.5B-Instruct"
RAG_REPO = "Rady10/Agriculture-Rag-Data-Index"
EMBED_MODEL = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"

DEVICE = "cpu"
MAX_TOKENS = 256

os.environ["TOKENIZERS_PARALLELISM"] = "false"

# ─────────────────────────────
# GLOBALS
# ─────────────────────────────
tokenizer = None
model = None
embedder = None
faiss_index = None
rag_chunks = None

# ─────────────────────────────
# SYSTEM PROMPT
# ─────────────────────────────
SYSTEM_PROMPT = """
You are an agriculture assistant.
Answer clearly and concisely in English or Arabic.
Focus on plant diseases, pests, irrigation, and farming advice.
"""

# ─────────────────────────────
# FASTAPI LIFESPAN (IMPORTANT)
# ─────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):

    global tokenizer, model, embedder, faiss_index, rag_chunks

    print("Loading RAG...")

    rag_dir = snapshot_download(
        repo_id=RAG_REPO,
        repo_type="dataset",
        local_dir="./rag"
    )

    faiss_index = faiss.read_index(
        os.path.join(rag_dir, "agro.index")
    )

    with open(os.path.join(rag_dir, "chunks.json"), "r", encoding="utf-8") as f:
        rag_chunks = json.load(f)

    print("Loading embedder...")
    embedder = SentenceTransformer(EMBED_MODEL)

    print("Loading tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(
        MODEL_REPO,
        trust_remote_code=True
    )

    print("Loading model...")
    model = AutoModelForCausalLM.from_pretrained(
        MODEL_REPO,
        device_map="cpu",
        torch_dtype=torch.float32,
        trust_remote_code=True
    )

    model.eval()

    print("ALL LOADED")

    yield

app = FastAPI(lifespan=lifespan)

# ─────────────────────────────
# REQUEST MODEL
# ─────────────────────────────
class ChatRequest(BaseModel):
    message: str

# ─────────────────────────────
# RAG
# ─────────────────────────────
def retrieve(query, k=3):

    if not query:
        return ""

    emb = embedder.encode([query], normalize_embeddings=True).astype(np.float32)

    scores, idxs = faiss_index.search(emb, k)

    results = []

    for score, idx in zip(scores[0], idxs[0]):
        if idx != -1 and score > 0.3:
            results.append(rag_chunks[idx]["text"])

    return "\n\n".join(results)

# ─────────────────────────────
# GENERATION
# ─────────────────────────────
def generate(text):

    context = retrieve(text)

    prompt = SYSTEM_PROMPT
    if context:
        prompt += "\n\nKnowledge:\n" + context

    messages = [
        {"role": "system", "content": prompt},
        {"role": "user", "content": text}
    ]

    input_text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = tokenizer(input_text, return_tensors="pt").to(model.device)

    with torch.no_grad():
        output = model.generate(
            **inputs,
            max_new_tokens=MAX_TOKENS,
            temperature=0.7,
            top_p=0.9
        )

    return tokenizer.decode(
        output[0][inputs.input_ids.shape[1]:],
        skip_special_tokens=True
    )

# ─────────────────────────────
# API ROUTES
# ─────────────────────────────
@app.get("/")
def home():
    return {"status": "running"}

@app.post("/chat")
def chat(req: ChatRequest):

    response = generate(req.message)

    return {"response": response}