Ayatullah-hanif commited on
Commit
1baf335
Β·
1 Parent(s): cf380e1

fix huggingface config

Browse files
Files changed (1) hide show
  1. app_fastapi.py +58 -75
app_fastapi.py CHANGED
@@ -7,11 +7,9 @@ Production-grade AI backend for cassava disease detection.
7
  Features:
8
  βœ“ ONNX EfficientNet-B3 inference
9
  βœ“ Proper softmax probabilities
10
- βœ“ English-first agricultural guidance
11
  βœ“ Multilingual translation via N-ATLaS
12
  βœ“ Human-in-the-loop escalation
13
-
14
- Designed for real-world Nigerian agriculture.
15
  """
16
 
17
  import os
@@ -41,6 +39,14 @@ app.add_middleware(
41
  logging.basicConfig(level=logging.INFO)
42
  logger = logging.getLogger("agricare_api")
43
 
 
 
 
 
 
 
 
 
44
  # -------------------------------------------------------
45
  # Model Setup
46
  # -------------------------------------------------------
@@ -62,66 +68,50 @@ IMG_SIZE = 300
62
  LOW_CONF_THRESHOLD = 0.60
63
 
64
  # -------------------------------------------------------
65
- # Disease Recommendations (ENGLISH SOURCE OF TRUTH)
66
  # -------------------------------------------------------
67
  DISEASE_RECOMMENDATIONS = {
68
- "Cassava Bacterial Blight": {
69
- "english": (
70
- "Cassava Bacterial Blight was detected.\n"
71
- "β€’ Remove and destroy infected plants.\n"
72
- "β€’ Use clean, disease-free planting materials.\n"
73
- "β€’ Apply copper-based bactericides such as Copper Oxychloride.\n"
74
- "β€’ Avoid overhead irrigation to reduce disease spread."
75
- )
76
- },
77
-
78
- "Cassava Brown Streak Disease": {
79
- "english": (
80
- "Cassava Brown Streak Disease was detected.\n"
81
- "β€’ There is no chemical cure for this disease.\n"
82
- "β€’ Control whiteflies using insecticides like Imidacloprid or Thiamethoxam.\n"
83
- "β€’ Plant resistant cassava varieties.\n"
84
- "β€’ Remove and destroy infected plants early."
85
- )
86
- },
87
-
88
- "Cassava Green Mottle": {
89
- "english": (
90
- "Cassava Green Mottle was detected.\n"
91
- "β€’ Control insect vectors such as aphids and whiteflies.\n"
92
- "β€’ Use insecticides like Lambda-cyhalothrin or Cypermethrin.\n"
93
- "β€’ Maintain field hygiene.\n"
94
- "β€’ Use certified disease-free planting materials."
95
- )
96
- },
97
-
98
- "Cassava Mosaic Disease": {
99
- "english": (
100
- "Cassava Mosaic Disease was detected.\n"
101
- "β€’ No direct chemical cure exists.\n"
102
- "β€’ Control whiteflies using Imidacloprid or Acetamiprid.\n"
103
- "β€’ Uproot and destroy infected plants immediately.\n"
104
- "β€’ Plant resistant cassava varieties."
105
- )
106
- },
107
-
108
- "Healthy Leaf": {
109
- "english": (
110
- "The cassava leaf is healthy.\n"
111
- "β€’ No treatment is required.\n"
112
- "β€’ Continue monitoring your farm.\n"
113
- "β€’ Maintain good agricultural practices."
114
- )
115
- }
116
  }
117
 
118
  # -------------------------------------------------------
119
  # Hugging Face – N-ATLaS (TEXT TRANSLATION ONLY)
120
  # -------------------------------------------------------
121
  HF_TOKEN = os.getenv("HF_TOKEN")
122
-
123
- HF_BASE = "https://router.huggingface.co/hf-inference/models"
124
- NATLAS_TEXT_URL = f"{HF_BASE}/NCAIR1/N-ATLaS"
125
 
126
  HEADERS = {
127
  "Authorization": f"Bearer {HF_TOKEN}",
@@ -138,46 +128,43 @@ def softmax(x):
138
  def preprocess(image_bytes):
139
  img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
140
  img = img.resize((IMG_SIZE, IMG_SIZE))
141
-
142
  arr = np.array(img).astype("float32") / 255.0
143
  arr = (arr - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
144
  arr = np.transpose(arr, (2, 0, 1))
145
  return arr[np.newaxis, :].astype(MODEL_DTYPE)
146
 
147
- # -------------------------------------------------------
148
- # Translation via N-ATLaS
149
- # -------------------------------------------------------
150
  def translate_text(text: str, language: str) -> str:
151
  if language.lower() == "english":
152
  return text
153
 
154
  prompt = f"""
155
- Translate the following agricultural advice into {language}.
156
- Keep it simple and farmer-friendly.
157
 
158
- Text:
159
- {text}
160
- """
161
 
162
  try:
163
  r = requests.post(
164
- NATLAS_TEXT_URL,
165
  headers=HEADERS,
166
  json={"inputs": prompt},
167
  timeout=20
168
  )
169
 
170
- r.raise_for_status()
 
 
171
 
172
  data = r.json()
173
  if isinstance(data, list) and data:
174
  return data[0].get("generated_text", text)
175
 
176
- return text
177
-
178
  except Exception as e:
179
  logger.error(f"N-ATLaS translation failed: {e}")
180
- return text
 
181
 
182
  # -------------------------------------------------------
183
  # API Endpoint
@@ -197,10 +184,7 @@ async def predict(
197
  confidence = float(probs[idx])
198
  predicted = CLASS_NAMES[idx]
199
 
200
- # English source text
201
- base_text = DISEASE_RECOMMENDATIONS[predicted]["english"]
202
-
203
- # Translate if needed
204
  final_text = translate_text(base_text, language)
205
 
206
  return {
@@ -210,12 +194,11 @@ async def predict(
210
  "route_to_expert": confidence < LOW_CONF_THRESHOLD,
211
  "language": language,
212
  "recommendation_text": final_text,
213
- "audio_available": False,
214
  "probabilities": probs.tolist()
215
  }
216
 
217
  # -------------------------------------------------------
218
- # Run (HF-compatible)
219
  # -------------------------------------------------------
220
  if __name__ == "__main__":
221
  uvicorn.run("app_fastapi:app", host="0.0.0.0", port=7860)
 
7
  Features:
8
  βœ“ ONNX EfficientNet-B3 inference
9
  βœ“ Proper softmax probabilities
10
+ βœ“ English-first medical guidance
11
  βœ“ Multilingual translation via N-ATLaS
12
  βœ“ Human-in-the-loop escalation
 
 
13
  """
14
 
15
  import os
 
39
  logging.basicConfig(level=logging.INFO)
40
  logger = logging.getLogger("agricare_api")
41
 
42
+ @app.get("/")
43
+ def root():
44
+ return {
45
+ "status": "ok",
46
+ "service": "AgriCare Disease Detection API",
47
+ "endpoint": "/predict"
48
+ }
49
+
50
  # -------------------------------------------------------
51
  # Model Setup
52
  # -------------------------------------------------------
 
68
  LOW_CONF_THRESHOLD = 0.60
69
 
70
  # -------------------------------------------------------
71
+ # Disease Recommendation Dictionary (ENGLISH SOURCE OF TRUTH)
72
  # -------------------------------------------------------
73
  DISEASE_RECOMMENDATIONS = {
74
+ "Cassava Bacterial Blight": (
75
+ "Cassava Bacterial Blight was detected. "
76
+ "Remove and destroy infected plants. "
77
+ "Use clean disease-free planting materials. "
78
+ "Apply copper-based bactericides such as Copper Oxychloride. "
79
+ "Avoid overhead irrigation to reduce spread."
80
+ ),
81
+
82
+ "Cassava Brown Streak Disease": (
83
+ "Cassava Brown Streak Disease was detected. "
84
+ "There is no chemical cure for this disease. "
85
+ "Control whiteflies using insecticides like Imidacloprid or Thiamethoxam. "
86
+ "Plant resistant cassava varieties and remove infected plants early."
87
+ ),
88
+
89
+ "Cassava Green Mottle": (
90
+ "Cassava Green Mottle was detected. "
91
+ "Control aphids and whiteflies using Lambda-cyhalothrin or Cypermethrin. "
92
+ "Maintain field hygiene and use certified disease-free cuttings."
93
+ ),
94
+
95
+ "Cassava Mosaic Disease": (
96
+ "Cassava Mosaic Disease was detected. "
97
+ "There is no direct chemical cure. "
98
+ "Control whiteflies using Imidacloprid or Acetamiprid. "
99
+ "Uproot and destroy infected plants immediately. "
100
+ "Plant resistant varieties recommended by extension officers."
101
+ ),
102
+
103
+ "Healthy Leaf": (
104
+ "The cassava leaf is healthy. "
105
+ "No treatment is required. "
106
+ "Continue regular monitoring and good farm hygiene."
107
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  }
109
 
110
  # -------------------------------------------------------
111
  # Hugging Face – N-ATLaS (TEXT TRANSLATION ONLY)
112
  # -------------------------------------------------------
113
  HF_TOKEN = os.getenv("HF_TOKEN")
114
+ NATLAS_URL = "https://router.huggingface.co/hf-inference/models/NCAIR1/N-ATLaS"
 
 
115
 
116
  HEADERS = {
117
  "Authorization": f"Bearer {HF_TOKEN}",
 
128
  def preprocess(image_bytes):
129
  img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
130
  img = img.resize((IMG_SIZE, IMG_SIZE))
 
131
  arr = np.array(img).astype("float32") / 255.0
132
  arr = (arr - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
133
  arr = np.transpose(arr, (2, 0, 1))
134
  return arr[np.newaxis, :].astype(MODEL_DTYPE)
135
 
 
 
 
136
  def translate_text(text: str, language: str) -> str:
137
  if language.lower() == "english":
138
  return text
139
 
140
  prompt = f"""
141
+ Translate the following agricultural advice into {language}.
142
+ Keep it simple, clear, and farmer-friendly.
143
 
144
+ Text:
145
+ {text}
146
+ """
147
 
148
  try:
149
  r = requests.post(
150
+ NATLAS_URL,
151
  headers=HEADERS,
152
  json={"inputs": prompt},
153
  timeout=20
154
  )
155
 
156
+ if r.status_code != 200:
157
+ logger.error(f"N-ATLaS error {r.status_code}: {r.text}")
158
+ return text
159
 
160
  data = r.json()
161
  if isinstance(data, list) and data:
162
  return data[0].get("generated_text", text)
163
 
 
 
164
  except Exception as e:
165
  logger.error(f"N-ATLaS translation failed: {e}")
166
+
167
+ return text
168
 
169
  # -------------------------------------------------------
170
  # API Endpoint
 
184
  confidence = float(probs[idx])
185
  predicted = CLASS_NAMES[idx]
186
 
187
+ base_text = DISEASE_RECOMMENDATIONS[predicted]
 
 
 
188
  final_text = translate_text(base_text, language)
189
 
190
  return {
 
194
  "route_to_expert": confidence < LOW_CONF_THRESHOLD,
195
  "language": language,
196
  "recommendation_text": final_text,
 
197
  "probabilities": probs.tolist()
198
  }
199
 
200
  # -------------------------------------------------------
201
+ # Run
202
  # -------------------------------------------------------
203
  if __name__ == "__main__":
204
  uvicorn.run("app_fastapi:app", host="0.0.0.0", port=7860)