Ayatullah-hanif commited on
Commit
0609674
·
1 Parent(s): d4b050a

fix huggingface config

Browse files
Files changed (1) hide show
  1. app_fastapi.py +50 -92
app_fastapi.py CHANGED
@@ -21,6 +21,7 @@ import requests
21
  from PIL import Image
22
  from fastapi import FastAPI, UploadFile, File, Form
23
  from fastapi.middleware.cors import CORSMiddleware
 
24
  import uvicorn
25
 
26
  # -------------------------------------------------------
@@ -39,13 +40,25 @@ app.add_middleware(
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
@@ -68,47 +81,34 @@ IMG_SIZE = 300
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"
@@ -133,17 +133,11 @@ def preprocess(image_bytes):
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(
@@ -152,53 +146,18 @@ Text:
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
171
  # -------------------------------------------------------
172
-
173
- from fastapi.responses import HTMLResponse
174
-
175
- @app.get("/", response_class=HTMLResponse)
176
- async def root():
177
- return """
178
- <!DOCTYPE html>
179
- <html>
180
- <head>
181
- <meta http-equiv="refresh" content="0; url=/docs" />
182
- <title>AgriCare API</title>
183
- <style>
184
- body {
185
- font-family: Arial, sans-serif;
186
- text-align: center;
187
- margin-top: 20%;
188
- }
189
- </style>
190
- </head>
191
- <body>
192
- <h2>AgriCare Disease Detection API</h2>
193
- <p>Redirecting to API documentation…</p>
194
- <p>
195
- If not redirected,
196
- <a href="/docs">click here to open Swagger Docs</a>.
197
- </p>
198
- </body>
199
- </html>
200
- """
201
-
202
  async def predict(
203
  file: UploadFile = File(...),
204
  language: str = Form("english")
@@ -220,14 +179,13 @@ async def predict(
220
  "status": "low_confidence" if confidence < LOW_CONF_THRESHOLD else "ok",
221
  "predicted_class": predicted,
222
  "confidence": round(confidence, 4),
223
- "route_to_expert": confidence < LOW_CONF_THRESHOLD,
224
  "language": language,
225
  "recommendation_text": final_text,
226
  "probabilities": probs.tolist()
227
  }
228
 
229
  # -------------------------------------------------------
230
- # Run
231
  # -------------------------------------------------------
232
  if __name__ == "__main__":
233
  uvicorn.run("app_fastapi:app", host="0.0.0.0", port=7860)
 
21
  from PIL import Image
22
  from fastapi import FastAPI, UploadFile, File, Form
23
  from fastapi.middleware.cors import CORSMiddleware
24
+ from fastapi.responses import HTMLResponse
25
  import uvicorn
26
 
27
  # -------------------------------------------------------
 
40
  logging.basicConfig(level=logging.INFO)
41
  logger = logging.getLogger("agricare_api")
42
 
43
+ # -------------------------------------------------------
44
+ # ROOT → REDIRECT TO DOCS
45
+ # -------------------------------------------------------
46
+ @app.get("/", response_class=HTMLResponse)
47
+ async def root():
48
+ return """
49
+ <!DOCTYPE html>
50
+ <html>
51
+ <head>
52
+ <meta http-equiv="refresh" content="0; url=/docs" />
53
+ <title>AgriCare API</title>
54
+ </head>
55
+ <body style="font-family: Arial; text-align:center; margin-top:20%">
56
+ <h2>AgriCare Disease Detection API</h2>
57
+ <p>Redirecting to API documentation…</p>
58
+ <p><a href="/docs">Open Swagger Docs</a></p>
59
+ </body>
60
+ </html>
61
+ """
62
 
63
  # -------------------------------------------------------
64
  # Model Setup
 
81
  LOW_CONF_THRESHOLD = 0.60
82
 
83
  # -------------------------------------------------------
84
+ # Disease Recommendations (ENGLISH SOURCE)
85
  # -------------------------------------------------------
86
  DISEASE_RECOMMENDATIONS = {
87
+ "Cassava Bacterial Blight":
88
+ "Cassava Bacterial Blight was detected. Remove and destroy infected plants. "
89
+ "Use clean disease-free planting materials. Apply copper-based bactericides "
90
+ "such as Copper Oxychloride. Avoid overhead irrigation.",
91
+
92
+ "Cassava Brown Streak Disease":
93
+ "Cassava Brown Streak Disease was detected. There is no chemical cure. "
94
+ "Control whiteflies using Imidacloprid or Thiamethoxam. "
95
+ "Plant resistant varieties and remove infected plants early.",
96
+
97
+ "Cassava Green Mottle":
98
+ "Cassava Green Mottle was detected. Control aphids and whiteflies using "
99
+ "Lambda-cyhalothrin or Cypermethrin. Maintain field hygiene.",
100
+
101
+ "Cassava Mosaic Disease":
102
+ "Cassava Mosaic Disease was detected. No direct chemical cure exists. "
 
 
 
 
 
 
 
 
103
  "Control whiteflies using Imidacloprid or Acetamiprid. "
104
+ "Uproot infected plants immediately.",
105
+
106
+ "Healthy Leaf":
107
+ "The cassava leaf is healthy. No treatment is required. Continue monitoring."
 
 
 
 
 
108
  }
109
 
110
  # -------------------------------------------------------
111
+ # Hugging Face N-ATLaS (Translation)
112
  # -------------------------------------------------------
113
  HF_TOKEN = os.getenv("HF_TOKEN")
114
  NATLAS_URL = "https://router.huggingface.co/hf-inference/models/NCAIR1/N-ATLaS"
 
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):
137
  if language.lower() == "english":
138
  return text
139
 
140
+ prompt = f"Translate this agricultural advice into {language}:\n{text}"
 
 
 
 
 
 
141
 
142
  try:
143
  r = requests.post(
 
146
  json={"inputs": prompt},
147
  timeout=20
148
  )
149
+ if r.status_code == 200:
150
+ data = r.json()
 
 
 
 
 
151
  return data[0].get("generated_text", text)
 
152
  except Exception as e:
153
+ logger.error(e)
154
 
155
  return text
156
 
157
  # -------------------------------------------------------
158
+ # PREDICT ENDPOINT ✅
159
  # -------------------------------------------------------
160
+ @app.post("/predict")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  async def predict(
162
  file: UploadFile = File(...),
163
  language: str = Form("english")
 
179
  "status": "low_confidence" if confidence < LOW_CONF_THRESHOLD else "ok",
180
  "predicted_class": predicted,
181
  "confidence": round(confidence, 4),
 
182
  "language": language,
183
  "recommendation_text": final_text,
184
  "probabilities": probs.tolist()
185
  }
186
 
187
  # -------------------------------------------------------
188
+ # Run (HF Compatible)
189
  # -------------------------------------------------------
190
  if __name__ == "__main__":
191
  uvicorn.run("app_fastapi:app", host="0.0.0.0", port=7860)