alaselababatunde commited on
Commit
f9dc634
·
1 Parent(s): fb015b4
Files changed (1) hide show
  1. app.py +36 -28
app.py CHANGED
@@ -1,15 +1,15 @@
1
  import os
2
  import logging
3
- import io
4
  from fastapi import FastAPI, Request, Header, HTTPException, UploadFile, File
5
  from fastapi.responses import JSONResponse
6
  from pydantic import BaseModel
7
  from transformers import pipeline
8
  from PIL import Image
 
9
  from vector import query_vector
10
 
11
  # ==============================
12
- # Logging
13
  # ==============================
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger("AgriCopilot")
@@ -24,7 +24,7 @@ async def root():
24
  return {"status": "AgriCopilot AI Backend is working perfectly"}
25
 
26
  # ==============================
27
- # Auth
28
  # ==============================
29
  PROJECT_API_KEY = os.getenv("PROJECT_API_KEY", "agricopilot404")
30
 
@@ -66,36 +66,45 @@ class VectorRequest(BaseModel):
66
  # ==============================
67
  # HuggingFace Pipelines
68
  # ==============================
69
- def load_pipeline(task, model_meta, model_fallback):
70
- """Try Meta model, fallback to public."""
71
  try:
72
  return pipeline(task, model=model_meta)
73
  except Exception as e:
74
- logger.warning(f"Meta model {model_meta} unavailable. Using fallback {model_fallback}.")
75
- return pipeline(task, model=model_fallback)
76
-
77
- chat_pipe = load_pipeline("conversational",
78
- model_meta="meta-llama/Llama-3.1-8B-Instruct",
79
- model_fallback="microsoft/DialoGPT-medium")
80
-
81
- disaster_pipe = load_pipeline("conversational",
82
- model_meta="meta-llama/Llama-3.1-8B-Instruct",
83
- model_fallback="microsoft/DialoGPT-medium")
84
-
85
- market_pipe = load_pipeline("conversational",
86
- model_meta="meta-llama/Llama-3.1-8B-Instruct",
87
- model_fallback="microsoft/DialoGPT-medium")
88
-
89
- crop_pipe = load_pipeline("image-to-text",
90
- model_meta="meta-llama/Llama-3.2-11B-Vision-Instruct",
91
- model_fallback="Salesforce/blip-image-captioning-large")
 
 
 
 
 
 
 
 
 
 
92
 
93
  # ==============================
94
  # Helper Functions
95
  # ==============================
96
  def run_conversational(pipe, prompt: str):
97
  try:
98
- output = pipe(prompt)
99
  if isinstance(output, list) and len(output) > 0:
100
  return output[0].get("generated_text", str(output))
101
  return str(output)
@@ -106,17 +115,17 @@ def run_conversational(pipe, prompt: str):
106
  def run_crop_doctor(image_bytes: bytes, symptoms: str):
107
  try:
108
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
109
- prompt = f"Farmer reports: {symptoms}. Diagnose the crop disease and suggest treatment in simple terms."
110
  output = crop_pipe(image, prompt=prompt)
111
  if isinstance(output, list) and len(output) > 0:
112
  return output[0].get("generated_text", str(output))
113
  return str(output)
114
  except Exception as e:
115
  logger.error(f"Crop Doctor pipeline error: {e}")
116
- return f"⚠️ Unexpected vision model error: {str(e)}"
117
 
118
  # ==============================
119
- # Endpoints
120
  # ==============================
121
  @app.post("/crop-doctor")
122
  async def crop_doctor(symptoms: str = Header(...), image: UploadFile = File(...), authorization: str | None = Header(None)):
@@ -150,5 +159,4 @@ async def vector_search(req: VectorRequest, authorization: str | None = Header(N
150
  results = query_vector(req.query)
151
  return {"results": results}
152
  except Exception as e:
153
- logger.error(f"Vector search error: {e}")
154
  return {"error": f"Vector search error: {str(e)}"}
 
1
  import os
2
  import logging
 
3
  from fastapi import FastAPI, Request, Header, HTTPException, UploadFile, File
4
  from fastapi.responses import JSONResponse
5
  from pydantic import BaseModel
6
  from transformers import pipeline
7
  from PIL import Image
8
+ import io
9
  from vector import query_vector
10
 
11
  # ==============================
12
+ # Setup Logging
13
  # ==============================
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger("AgriCopilot")
 
24
  return {"status": "AgriCopilot AI Backend is working perfectly"}
25
 
26
  # ==============================
27
+ # AUTH CONFIG
28
  # ==============================
29
  PROJECT_API_KEY = os.getenv("PROJECT_API_KEY", "agricopilot404")
30
 
 
66
  # ==============================
67
  # HuggingFace Pipelines
68
  # ==============================
69
+ def load_pipeline(task: str, model_meta: str, model_fallback: str = None):
 
70
  try:
71
  return pipeline(task, model=model_meta)
72
  except Exception as e:
73
+ logger.warning(f"Failed to load {model_meta}: {e}")
74
+ if model_fallback:
75
+ logger.info(f"Falling back to {model_fallback}")
76
+ return pipeline(task, model=model_fallback)
77
+ raise e
78
+
79
+ # Public LLM pipelines (text-generation)
80
+ chat_pipe = load_pipeline(
81
+ "text-generation",
82
+ model_meta="tiiuae/falcon-7b-instruct",
83
+ model_fallback="gpt2"
84
+ )
85
+ disaster_pipe = load_pipeline(
86
+ "text-generation",
87
+ model_meta="tiiuae/falcon-7b-instruct",
88
+ model_fallback="gpt2"
89
+ )
90
+ market_pipe = load_pipeline(
91
+ "text-generation",
92
+ model_meta="tiiuae/falcon-7b-instruct",
93
+ model_fallback="gpt2"
94
+ )
95
+
96
+ # Crop Doctor: image-to-text
97
+ crop_pipe = load_pipeline(
98
+ "image-to-text",
99
+ model_meta="Salesforce/blip-image-captioning-base"
100
+ )
101
 
102
  # ==============================
103
  # Helper Functions
104
  # ==============================
105
  def run_conversational(pipe, prompt: str):
106
  try:
107
+ output = pipe(prompt, max_new_tokens=200)
108
  if isinstance(output, list) and len(output) > 0:
109
  return output[0].get("generated_text", str(output))
110
  return str(output)
 
115
  def run_crop_doctor(image_bytes: bytes, symptoms: str):
116
  try:
117
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
118
+ prompt = f"Farmer reports: {symptoms}. Diagnose the crop disease and suggest treatment in simple language."
119
  output = crop_pipe(image, prompt=prompt)
120
  if isinstance(output, list) and len(output) > 0:
121
  return output[0].get("generated_text", str(output))
122
  return str(output)
123
  except Exception as e:
124
  logger.error(f"Crop Doctor pipeline error: {e}")
125
+ return f"⚠️ Unexpected model error: {str(e)}"
126
 
127
  # ==============================
128
+ # ENDPOINTS
129
  # ==============================
130
  @app.post("/crop-doctor")
131
  async def crop_doctor(symptoms: str = Header(...), image: UploadFile = File(...), authorization: str | None = Header(None)):
 
159
  results = query_vector(req.query)
160
  return {"results": results}
161
  except Exception as e:
 
162
  return {"error": f"Vector search error: {str(e)}"}