Update app/agents/crew_pipeline.py
Browse files- app/agents/crew_pipeline.py +283 -283
app/agents/crew_pipeline.py
CHANGED
|
@@ -1,283 +1,283 @@
|
|
| 1 |
-
# farmlingua/app/agents/crew_pipeline.pymemorysection
|
| 2 |
-
import os
|
| 3 |
-
import sys
|
| 4 |
-
import re
|
| 5 |
-
import uuid
|
| 6 |
-
import requests
|
| 7 |
-
import joblib
|
| 8 |
-
import faiss
|
| 9 |
-
import numpy as np
|
| 10 |
-
import torch
|
| 11 |
-
import fasttext
|
| 12 |
-
from huggingface_hub import hf_hub_download
|
| 13 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 14 |
-
from sentence_transformers import SentenceTransformer
|
| 15 |
-
from app.utils import config
|
| 16 |
-
from app.utils.memory import memory_store # memory module
|
| 17 |
-
from typing import List
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
hf_cache = "/models/huggingface"
|
| 21 |
-
os.environ["HF_HOME"] = hf_cache
|
| 22 |
-
os.environ["TRANSFORMERS_CACHE"] = hf_cache
|
| 23 |
-
os.environ["HUGGINGFACE_HUB_CACHE"] = hf_cache
|
| 24 |
-
os.makedirs(hf_cache, exist_ok=True)
|
| 25 |
-
|
| 26 |
-
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 27 |
-
if BASE_DIR not in sys.path:
|
| 28 |
-
sys.path.insert(0, BASE_DIR)
|
| 29 |
-
|
| 30 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
classifier = joblib.load(config.CLASSIFIER_PATH)
|
| 35 |
-
except Exception:
|
| 36 |
-
classifier = None
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
print(f"Loading expert model ({config.EXPERT_MODEL_NAME})...")
|
| 40 |
-
tokenizer = AutoTokenizer.from_pretrained(config.EXPERT_MODEL_NAME, use_fast=False)
|
| 41 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 42 |
-
config.EXPERT_MODEL_NAME,
|
| 43 |
-
torch_dtype="auto",
|
| 44 |
-
device_map="auto"
|
| 45 |
-
)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
embedder = SentenceTransformer(config.EMBEDDING_MODEL)
|
| 49 |
-
|
| 50 |
-
# language detector
|
| 51 |
-
print(f"Loading FastText language identifier ({config.LANG_ID_MODEL_REPO})...")
|
| 52 |
-
lang_model_path = hf_hub_download(
|
| 53 |
-
repo_id=config.LANG_ID_MODEL_REPO,
|
| 54 |
-
filename=getattr(config, "LANG_ID_MODEL_FILE", "model.bin")
|
| 55 |
-
)
|
| 56 |
-
lang_identifier = fasttext.load_model(lang_model_path)
|
| 57 |
-
|
| 58 |
-
def detect_language(text: str, top_k: int = 1):
|
| 59 |
-
if not text or not text.strip():
|
| 60 |
-
return [("eng_Latn", 1.0)]
|
| 61 |
-
clean_text = text.replace("\n", " ").strip()
|
| 62 |
-
labels, probs = lang_identifier.predict(clean_text, k=top_k)
|
| 63 |
-
return [(l.replace("__label__", ""), float(p)) for l, p in zip(labels, probs)]
|
| 64 |
-
|
| 65 |
-
# Translation model
|
| 66 |
-
print(f"Loading translation model ({config.TRANSLATION_MODEL_NAME})...")
|
| 67 |
-
translation_pipeline = pipeline(
|
| 68 |
-
"translation",
|
| 69 |
-
model=config.TRANSLATION_MODEL_NAME,
|
| 70 |
-
device=0 if DEVICE == "cuda" else -1,
|
| 71 |
-
max_new_tokens=400,
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
SUPPORTED_LANGS = {
|
| 75 |
-
"eng_Latn": "English",
|
| 76 |
-
"ibo_Latn": "Igbo",
|
| 77 |
-
"yor_Latn": "Yoruba",
|
| 78 |
-
"hau_Latn": "Hausa",
|
| 79 |
-
"swh_Latn": "Swahili",
|
| 80 |
-
"amh_Latn": "Amharic",
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
# Text chunking
|
| 84 |
-
_SENTENCE_SPLIT_RE = re.compile(r'(?<=[.!?])\s+')
|
| 85 |
-
|
| 86 |
-
def chunk_text(text: str, max_len: int = 400) -> List[str]:
|
| 87 |
-
if not text:
|
| 88 |
-
return []
|
| 89 |
-
sentences = _SENTENCE_SPLIT_RE.split(text)
|
| 90 |
-
chunks, current = [], ""
|
| 91 |
-
for s in sentences:
|
| 92 |
-
if not s:
|
| 93 |
-
continue
|
| 94 |
-
if len(current) + len(s) + 1 <= max_len:
|
| 95 |
-
current = (current + " " + s).strip()
|
| 96 |
-
else:
|
| 97 |
-
if current:
|
| 98 |
-
chunks.append(current.strip())
|
| 99 |
-
current = s.strip()
|
| 100 |
-
if current:
|
| 101 |
-
chunks.append(current.strip())
|
| 102 |
-
return chunks
|
| 103 |
-
|
| 104 |
-
def translate_text(text: str, src_lang: str, tgt_lang: str, max_chunk_len: int = 400) -> str:
|
| 105 |
-
if not text.strip():
|
| 106 |
-
return text
|
| 107 |
-
chunks = chunk_text(text, max_len=max_chunk_len)
|
| 108 |
-
translated_parts = []
|
| 109 |
-
for chunk in chunks:
|
| 110 |
-
res = translation_pipeline(chunk, src_lang=src_lang, tgt_lang=tgt_lang)
|
| 111 |
-
translated_parts.append(res[0]["translation_text"])
|
| 112 |
-
return " ".join(translated_parts).strip()
|
| 113 |
-
|
| 114 |
-
# RAG retrieval
|
| 115 |
-
def retrieve_docs(query: str, vs_path: str):
|
| 116 |
-
if not vs_path or not os.path.exists(vs_path):
|
| 117 |
-
return None
|
| 118 |
-
try:
|
| 119 |
-
index = faiss.read_index(str(vs_path))
|
| 120 |
-
except Exception:
|
| 121 |
-
return None
|
| 122 |
-
query_vec = np.array([embedder.encode(query)], dtype=np.float32)
|
| 123 |
-
D, I = index.search(query_vec, k=3)
|
| 124 |
-
if D[0][0] == 0:
|
| 125 |
-
return None
|
| 126 |
-
meta_path = str(vs_path) + "_meta.npy"
|
| 127 |
-
if os.path.exists(meta_path):
|
| 128 |
-
metadata = np.load(meta_path, allow_pickle=True).item()
|
| 129 |
-
docs = [metadata.get(str(idx), "") for idx in I[0] if str(idx) in metadata]
|
| 130 |
-
docs = [d for d in docs if d]
|
| 131 |
-
return "\n\n".join(docs) if docs else None
|
| 132 |
-
return None
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def get_weather(state_name: str) -> str:
|
| 136 |
-
url = "http://api.weatherapi.com/v1/current.json"
|
| 137 |
-
params = {"key": config.WEATHER_API_KEY, "q": f"{state_name}, Nigeria", "aqi": "no"}
|
| 138 |
-
r = requests.get(url, params=params, timeout=10)
|
| 139 |
-
if r.status_code != 200:
|
| 140 |
-
return f"Unable to retrieve weather for {state_name}."
|
| 141 |
-
data = r.json()
|
| 142 |
-
return (
|
| 143 |
-
f"Weather in {state_name}:\n"
|
| 144 |
-
f"- Condition: {data['current']['condition']['text']}\n"
|
| 145 |
-
f"- Temperature: {data['current']['temp_c']}°C\n"
|
| 146 |
-
f"- Humidity: {data['current']['humidity']}%\n"
|
| 147 |
-
f"- Wind: {data['current']['wind_kph']} kph"
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
def detect_intent(query: str):
|
| 152 |
-
q_lower = (query or "").lower()
|
| 153 |
-
if any(word in q_lower for word in ["weather", "temperature", "rain", "forecast"]):
|
| 154 |
-
for state in getattr(config, "STATES", []):
|
| 155 |
-
if state.lower() in q_lower:
|
| 156 |
-
return "weather", state
|
| 157 |
-
return "weather", None
|
| 158 |
-
|
| 159 |
-
if any(word in q_lower for word in ["latest", "update", "breaking", "news", "current", "predict"]):
|
| 160 |
-
return "live_update", None
|
| 161 |
-
|
| 162 |
-
if hasattr(classifier, "predict") and hasattr(classifier, "predict_proba"):
|
| 163 |
-
try:
|
| 164 |
-
predicted_intent = classifier.predict([query])[0]
|
| 165 |
-
confidence = max(classifier.predict_proba([query])[0])
|
| 166 |
-
if confidence < getattr(config, "CLASSIFIER_CONFIDENCE_THRESHOLD", 0.6):
|
| 167 |
-
return "low_confidence", None
|
| 168 |
-
return predicted_intent, None
|
| 169 |
-
except Exception:
|
| 170 |
-
pass
|
| 171 |
-
return "normal", None
|
| 172 |
-
|
| 173 |
-
# expert runner
|
| 174 |
-
def run_qwen(messages: List[dict], max_new_tokens: int = 1300) -> str:
|
| 175 |
-
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 176 |
-
inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 177 |
-
generated_ids = model.generate(
|
| 178 |
-
**inputs,
|
| 179 |
-
max_new_tokens=max_new_tokens,
|
| 180 |
-
temperature=0.4,
|
| 181 |
-
repetition_penalty=1.1
|
| 182 |
-
)
|
| 183 |
-
output_ids = generated_ids[0][len(inputs.input_ids[0]):].tolist()
|
| 184 |
-
return tokenizer.decode(output_ids, skip_special_tokens=True).strip()
|
| 185 |
-
|
| 186 |
-
# Memory
|
| 187 |
-
MAX_HISTORY_MESSAGES = getattr(config, "MAX_HISTORY_MESSAGES", 30)
|
| 188 |
-
|
| 189 |
-
def build_messages_from_history(history: List[dict], system_prompt: str) -> List[dict]:
|
| 190 |
-
msgs = [{"role": "system", "content": system_prompt}]
|
| 191 |
-
msgs.extend(history)
|
| 192 |
-
return msgs
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def strip_markdown(text: str) -> str:
|
| 196 |
-
"""
|
| 197 |
-
Remove Markdown formatting like **bold**, *italic*, and `inline code`.
|
| 198 |
-
"""
|
| 199 |
-
if not text:
|
| 200 |
-
return ""
|
| 201 |
-
text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
|
| 202 |
-
text = re.sub(r'(\*|_)(.*?)\1', r'\2', text)
|
| 203 |
-
text = re.sub(r'`(.*?)`', r'\1', text)
|
| 204 |
-
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 205 |
-
return text
|
| 206 |
-
|
| 207 |
-
# Main pipeline
|
| 208 |
-
def run_pipeline(user_query: str, session_id: str = None):
|
| 209 |
-
"""
|
| 210 |
-
Run FarmLingua pipeline with per-session memory.
|
| 211 |
-
Each session_id keeps its own history.
|
| 212 |
-
"""
|
| 213 |
-
if session_id is None:
|
| 214 |
-
session_id = str(uuid.uuid4()) # fallback unique session
|
| 215 |
-
|
| 216 |
-
# Language detection
|
| 217 |
-
lang_label, prob = detect_language(user_query, top_k=1)[0]
|
| 218 |
-
if lang_label not in SUPPORTED_LANGS:
|
| 219 |
-
lang_label = "eng_Latn"
|
| 220 |
-
|
| 221 |
-
translated_query = (
|
| 222 |
-
translate_text(user_query, src_lang=lang_label, tgt_lang="eng_Latn")
|
| 223 |
-
if lang_label != "eng_Latn"
|
| 224 |
-
else user_query
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
intent, extra = detect_intent(translated_query)
|
| 228 |
-
|
| 229 |
-
# Load conversation history
|
| 230 |
-
history = memory_store.get_history(session_id) or []
|
| 231 |
-
if len(history) > MAX_HISTORY_MESSAGES:
|
| 232 |
-
history = history[-MAX_HISTORY_MESSAGES:]
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
history.append({"role": "user", "content": translated_query})
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
system_prompt = (
|
| 239 |
-
"You are FarmLingua, an AI assistant for Nigerian farmers. "
|
| 240 |
-
"Answer directly without repeating the question. "
|
| 241 |
-
"Use clear farmer-friendly English with emojis . "
|
| 242 |
-
"Avoid jargon and irrelevant details. "
|
| 243 |
-
"If asked who built you, say: 'KawaFarm LTD developed me to help farmers.'"
|
| 244 |
-
|
| 245 |
-
)
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
if intent == "weather" and extra:
|
| 249 |
-
weather_text = get_weather(extra)
|
| 250 |
-
history.append({"role": "user", "content": f"Rewrite this weather update simply for farmers:\n{weather_text}"})
|
| 251 |
-
messages_for_qwen = build_messages_from_history(history, system_prompt)
|
| 252 |
-
english_answer = run_qwen(messages_for_qwen, max_new_tokens=256)
|
| 253 |
-
else:
|
| 254 |
-
if intent == "live_update":
|
| 255 |
-
context = retrieve_docs(translated_query, config.LIVE_VS_PATH)
|
| 256 |
-
if context:
|
| 257 |
-
history.append({"role": "user", "content": f"Latest agricultural updates:\n{context}"})
|
| 258 |
-
if intent == "low_confidence":
|
| 259 |
-
context = retrieve_docs(translated_query, config.STATIC_VS_PATH)
|
| 260 |
-
if context:
|
| 261 |
-
history.append({"role": "user", "content": f"Reference information:\n{context}"})
|
| 262 |
-
|
| 263 |
-
messages_for_qwen = build_messages_from_history(history, system_prompt)
|
| 264 |
-
english_answer = run_qwen(messages_for_qwen, max_new_tokens=700)
|
| 265 |
-
|
| 266 |
-
# Save assistant reply
|
| 267 |
-
history.append({"role": "assistant", "content": english_answer})
|
| 268 |
-
if len(history) > MAX_HISTORY_MESSAGES:
|
| 269 |
-
history = history[-MAX_HISTORY_MESSAGES:]
|
| 270 |
-
memory_store.save_history(session_id, history)
|
| 271 |
-
|
| 272 |
-
# Translate back if needed
|
| 273 |
-
final_answer = (
|
| 274 |
-
translate_text(english_answer, src_lang="eng_Latn", tgt_lang=lang_label)
|
| 275 |
-
if lang_label != "eng_Latn"
|
| 276 |
-
else english_answer
|
| 277 |
-
)
|
| 278 |
-
final_answer = strip_markdown(final_answer)
|
| 279 |
-
return {
|
| 280 |
-
"session_id": session_id,
|
| 281 |
-
"detected_language": SUPPORTED_LANGS.get(lang_label, "Unknown"),
|
| 282 |
-
"answer": final_answer
|
| 283 |
-
}
|
|
|
|
| 1 |
+
# farmlingua/app/agents/crew_pipeline.pymemorysection
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
import uuid
|
| 6 |
+
import requests
|
| 7 |
+
import joblib
|
| 8 |
+
import faiss
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import fasttext
|
| 12 |
+
from huggingface_hub import hf_hub_download
|
| 13 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 14 |
+
from sentence_transformers import SentenceTransformer
|
| 15 |
+
from app.utils import config
|
| 16 |
+
from app.utils.memory import memory_store # memory module
|
| 17 |
+
from typing import List
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
hf_cache = "/models/huggingface"
|
| 21 |
+
os.environ["HF_HOME"] = hf_cache
|
| 22 |
+
os.environ["TRANSFORMERS_CACHE"] = hf_cache
|
| 23 |
+
os.environ["HUGGINGFACE_HUB_CACHE"] = hf_cache
|
| 24 |
+
os.makedirs(hf_cache, exist_ok=True)
|
| 25 |
+
|
| 26 |
+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 27 |
+
if BASE_DIR not in sys.path:
|
| 28 |
+
sys.path.insert(0, BASE_DIR)
|
| 29 |
+
|
| 30 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
classifier = joblib.load(config.CLASSIFIER_PATH)
|
| 35 |
+
except Exception:
|
| 36 |
+
classifier = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
print(f"Loading expert model ({config.EXPERT_MODEL_NAME})...")
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(config.EXPERT_MODEL_NAME, use_fast=False)
|
| 41 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 42 |
+
config.EXPERT_MODEL_NAME,
|
| 43 |
+
torch_dtype="auto",
|
| 44 |
+
device_map="auto"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
embedder = SentenceTransformer(config.EMBEDDING_MODEL)
|
| 49 |
+
|
| 50 |
+
# language detector
|
| 51 |
+
print(f"Loading FastText language identifier ({config.LANG_ID_MODEL_REPO})...")
|
| 52 |
+
lang_model_path = hf_hub_download(
|
| 53 |
+
repo_id=config.LANG_ID_MODEL_REPO,
|
| 54 |
+
filename=getattr(config, "LANG_ID_MODEL_FILE", "model.bin")
|
| 55 |
+
)
|
| 56 |
+
lang_identifier = fasttext.load_model(lang_model_path)
|
| 57 |
+
|
| 58 |
+
def detect_language(text: str, top_k: int = 1):
|
| 59 |
+
if not text or not text.strip():
|
| 60 |
+
return [("eng_Latn", 1.0)]
|
| 61 |
+
clean_text = text.replace("\n", " ").strip()
|
| 62 |
+
labels, probs = lang_identifier.predict(clean_text, k=top_k)
|
| 63 |
+
return [(l.replace("__label__", ""), float(p)) for l, p in zip(labels, probs)]
|
| 64 |
+
|
| 65 |
+
# Translation model
|
| 66 |
+
print(f"Loading translation model ({config.TRANSLATION_MODEL_NAME})...")
|
| 67 |
+
translation_pipeline = pipeline(
|
| 68 |
+
"translation",
|
| 69 |
+
model=config.TRANSLATION_MODEL_NAME,
|
| 70 |
+
device=0 if DEVICE == "cuda" else -1,
|
| 71 |
+
max_new_tokens=400,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
SUPPORTED_LANGS = {
|
| 75 |
+
"eng_Latn": "English",
|
| 76 |
+
"ibo_Latn": "Igbo",
|
| 77 |
+
"yor_Latn": "Yoruba",
|
| 78 |
+
"hau_Latn": "Hausa",
|
| 79 |
+
"swh_Latn": "Swahili",
|
| 80 |
+
"amh_Latn": "Amharic",
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# Text chunking
|
| 84 |
+
_SENTENCE_SPLIT_RE = re.compile(r'(?<=[.!?])\s+')
|
| 85 |
+
|
| 86 |
+
def chunk_text(text: str, max_len: int = 400) -> List[str]:
|
| 87 |
+
if not text:
|
| 88 |
+
return []
|
| 89 |
+
sentences = _SENTENCE_SPLIT_RE.split(text)
|
| 90 |
+
chunks, current = [], ""
|
| 91 |
+
for s in sentences:
|
| 92 |
+
if not s:
|
| 93 |
+
continue
|
| 94 |
+
if len(current) + len(s) + 1 <= max_len:
|
| 95 |
+
current = (current + " " + s).strip()
|
| 96 |
+
else:
|
| 97 |
+
if current:
|
| 98 |
+
chunks.append(current.strip())
|
| 99 |
+
current = s.strip()
|
| 100 |
+
if current:
|
| 101 |
+
chunks.append(current.strip())
|
| 102 |
+
return chunks
|
| 103 |
+
|
| 104 |
+
def translate_text(text: str, src_lang: str, tgt_lang: str, max_chunk_len: int = 400) -> str:
|
| 105 |
+
if not text.strip():
|
| 106 |
+
return text
|
| 107 |
+
chunks = chunk_text(text, max_len=max_chunk_len)
|
| 108 |
+
translated_parts = []
|
| 109 |
+
for chunk in chunks:
|
| 110 |
+
res = translation_pipeline(chunk, src_lang=src_lang, tgt_lang=tgt_lang)
|
| 111 |
+
translated_parts.append(res[0]["translation_text"])
|
| 112 |
+
return " ".join(translated_parts).strip()
|
| 113 |
+
|
| 114 |
+
# RAG retrieval
|
| 115 |
+
def retrieve_docs(query: str, vs_path: str):
|
| 116 |
+
if not vs_path or not os.path.exists(vs_path):
|
| 117 |
+
return None
|
| 118 |
+
try:
|
| 119 |
+
index = faiss.read_index(str(vs_path))
|
| 120 |
+
except Exception:
|
| 121 |
+
return None
|
| 122 |
+
query_vec = np.array([embedder.encode(query)], dtype=np.float32)
|
| 123 |
+
D, I = index.search(query_vec, k=3)
|
| 124 |
+
if D[0][0] == 0:
|
| 125 |
+
return None
|
| 126 |
+
meta_path = str(vs_path) + "_meta.npy"
|
| 127 |
+
if os.path.exists(meta_path):
|
| 128 |
+
metadata = np.load(meta_path, allow_pickle=True).item()
|
| 129 |
+
docs = [metadata.get(str(idx), "") for idx in I[0] if str(idx) in metadata]
|
| 130 |
+
docs = [d for d in docs if d]
|
| 131 |
+
return "\n\n".join(docs) if docs else None
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_weather(state_name: str) -> str:
|
| 136 |
+
url = "http://api.weatherapi.com/v1/current.json"
|
| 137 |
+
params = {"key": config.WEATHER_API_KEY, "q": f"{state_name}, Nigeria", "aqi": "no"}
|
| 138 |
+
r = requests.get(url, params=params, timeout=10)
|
| 139 |
+
if r.status_code != 200:
|
| 140 |
+
return f"Unable to retrieve weather for {state_name}."
|
| 141 |
+
data = r.json()
|
| 142 |
+
return (
|
| 143 |
+
f"Weather in {state_name}:\n"
|
| 144 |
+
f"- Condition: {data['current']['condition']['text']}\n"
|
| 145 |
+
f"- Temperature: {data['current']['temp_c']}°C\n"
|
| 146 |
+
f"- Humidity: {data['current']['humidity']}%\n"
|
| 147 |
+
f"- Wind: {data['current']['wind_kph']} kph"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def detect_intent(query: str):
|
| 152 |
+
q_lower = (query or "").lower()
|
| 153 |
+
if any(word in q_lower for word in ["weather", "temperature", "rain", "forecast"]):
|
| 154 |
+
for state in getattr(config, "STATES", []):
|
| 155 |
+
if state.lower() in q_lower:
|
| 156 |
+
return "weather", state
|
| 157 |
+
return "weather", None
|
| 158 |
+
|
| 159 |
+
if any(word in q_lower for word in ["latest", "update", "breaking", "news", "current", "predict"]):
|
| 160 |
+
return "live_update", None
|
| 161 |
+
|
| 162 |
+
if hasattr(classifier, "predict") and hasattr(classifier, "predict_proba"):
|
| 163 |
+
try:
|
| 164 |
+
predicted_intent = classifier.predict([query])[0]
|
| 165 |
+
confidence = max(classifier.predict_proba([query])[0])
|
| 166 |
+
if confidence < getattr(config, "CLASSIFIER_CONFIDENCE_THRESHOLD", 0.6):
|
| 167 |
+
return "low_confidence", None
|
| 168 |
+
return predicted_intent, None
|
| 169 |
+
except Exception:
|
| 170 |
+
pass
|
| 171 |
+
return "normal", None
|
| 172 |
+
|
| 173 |
+
# expert runner
|
| 174 |
+
def run_qwen(messages: List[dict], max_new_tokens: int = 1300) -> str:
|
| 175 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 176 |
+
inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 177 |
+
generated_ids = model.generate(
|
| 178 |
+
**inputs,
|
| 179 |
+
max_new_tokens=max_new_tokens,
|
| 180 |
+
temperature=0.4,
|
| 181 |
+
repetition_penalty=1.1
|
| 182 |
+
)
|
| 183 |
+
output_ids = generated_ids[0][len(inputs.input_ids[0]):].tolist()
|
| 184 |
+
return tokenizer.decode(output_ids, skip_special_tokens=True).strip()
|
| 185 |
+
|
| 186 |
+
# Memory
|
| 187 |
+
MAX_HISTORY_MESSAGES = getattr(config, "MAX_HISTORY_MESSAGES", 30)
|
| 188 |
+
|
| 189 |
+
def build_messages_from_history(history: List[dict], system_prompt: str) -> List[dict]:
|
| 190 |
+
msgs = [{"role": "system", "content": system_prompt}]
|
| 191 |
+
msgs.extend(history)
|
| 192 |
+
return msgs
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def strip_markdown(text: str) -> str:
|
| 196 |
+
"""
|
| 197 |
+
Remove Markdown formatting like **bold**, *italic*, and `inline code`.
|
| 198 |
+
"""
|
| 199 |
+
if not text:
|
| 200 |
+
return ""
|
| 201 |
+
text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
|
| 202 |
+
text = re.sub(r'(\*|_)(.*?)\1', r'\2', text)
|
| 203 |
+
text = re.sub(r'`(.*?)`', r'\1', text)
|
| 204 |
+
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 205 |
+
return text
|
| 206 |
+
|
| 207 |
+
# Main pipeline
|
| 208 |
+
def run_pipeline(user_query: str, session_id: str = None):
|
| 209 |
+
"""
|
| 210 |
+
Run FarmLingua pipeline with per-session memory.
|
| 211 |
+
Each session_id keeps its own history.
|
| 212 |
+
"""
|
| 213 |
+
if session_id is None:
|
| 214 |
+
session_id = str(uuid.uuid4()) # fallback unique session
|
| 215 |
+
|
| 216 |
+
# Language detection
|
| 217 |
+
lang_label, prob = detect_language(user_query, top_k=1)[0]
|
| 218 |
+
if lang_label not in SUPPORTED_LANGS:
|
| 219 |
+
lang_label = "eng_Latn"
|
| 220 |
+
|
| 221 |
+
translated_query = (
|
| 222 |
+
translate_text(user_query, src_lang=lang_label, tgt_lang="eng_Latn")
|
| 223 |
+
if lang_label != "eng_Latn"
|
| 224 |
+
else user_query
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
intent, extra = detect_intent(translated_query)
|
| 228 |
+
|
| 229 |
+
# Load conversation history
|
| 230 |
+
history = memory_store.get_history(session_id) or []
|
| 231 |
+
if len(history) > MAX_HISTORY_MESSAGES:
|
| 232 |
+
history = history[-MAX_HISTORY_MESSAGES:]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
history.append({"role": "user", "content": translated_query})
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
system_prompt = (
|
| 239 |
+
"You are FarmLingua, an AI assistant for Nigerian farmers. "
|
| 240 |
+
"Answer directly without repeating the question. "
|
| 241 |
+
"Use clear farmer-friendly English with emojis . "
|
| 242 |
+
"Avoid jargon and irrelevant details. "
|
| 243 |
+
"If asked who built you, say: 'KawaFarm LTD developed me to help farmers.'"
|
| 244 |
+
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if intent == "weather" and extra:
|
| 249 |
+
weather_text = get_weather(extra)
|
| 250 |
+
history.append({"role": "user", "content": f"Rewrite this weather update simply for farmers:\n{weather_text}"})
|
| 251 |
+
messages_for_qwen = build_messages_from_history(history, system_prompt)
|
| 252 |
+
english_answer = run_qwen(messages_for_qwen, max_new_tokens=256)
|
| 253 |
+
else:
|
| 254 |
+
if intent == "live_update":
|
| 255 |
+
context = retrieve_docs(translated_query, config.LIVE_VS_PATH)
|
| 256 |
+
if context:
|
| 257 |
+
history.append({"role": "user", "content": f"Latest agricultural updates:\n{context}"})
|
| 258 |
+
if intent == "low_confidence":
|
| 259 |
+
context = retrieve_docs(translated_query, config.STATIC_VS_PATH)
|
| 260 |
+
if context:
|
| 261 |
+
history.append({"role": "user", "content": f"Reference information:\n{context}"})
|
| 262 |
+
|
| 263 |
+
messages_for_qwen = build_messages_from_history(history, system_prompt)
|
| 264 |
+
english_answer = run_qwen(messages_for_qwen, max_new_tokens=700)
|
| 265 |
+
|
| 266 |
+
# Save assistant reply
|
| 267 |
+
history.append({"role": "assistant", "content": english_answer})
|
| 268 |
+
if len(history) > MAX_HISTORY_MESSAGES:
|
| 269 |
+
history = history[-MAX_HISTORY_MESSAGES:]
|
| 270 |
+
memory_store.save_history(session_id, history)
|
| 271 |
+
|
| 272 |
+
# Translate back if needed
|
| 273 |
+
final_answer = (
|
| 274 |
+
translate_text(english_answer, src_lang="eng_Latn", tgt_lang=lang_label)
|
| 275 |
+
if lang_label != "eng_Latn"
|
| 276 |
+
else english_answer
|
| 277 |
+
)
|
| 278 |
+
final_answer = strip_markdown(final_answer)
|
| 279 |
+
return {
|
| 280 |
+
"session_id": session_id,
|
| 281 |
+
"detected_language": SUPPORTED_LANGS.get(lang_label, "Unknown"),
|
| 282 |
+
"answer": final_answer
|
| 283 |
+
}
|