RushiMane2003 commited on
Commit
8cadfdd
·
verified ·
1 Parent(s): 3cb9724

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -84
app.py CHANGED
@@ -44,6 +44,26 @@ def load_csv_data():
44
 
45
  # Load CSV data
46
  csv_data = load_csv_data()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  class RetellRequest(BaseModel):
49
  name: str # Function name
@@ -73,55 +93,40 @@ def search_csv_data(df: pd.DataFrame, search_terms: Dict[str, str]) -> pd.DataFr
73
  return result
74
 
75
  @app.post("/api/market-prices")
76
- async def market_prices_endpoint(
77
- request: Request,
78
- x_retell_signature: str = Header(None, alias="X-Retell-Signature")
79
- ):
80
- """Handle market prices function call from Retell.ai"""
81
- request_body = await request.body()
82
- retell_request = json.loads(request_body.decode('utf-8'))
83
-
84
- # Extract arguments
85
- crop_name = retell_request["args"].get("crop_name", "")
86
- state = retell_request["args"].get("state", "")
87
- district = retell_request["args"].get("district", "")
88
-
89
- try:
90
- # Check if we have relevant data in CSVs
91
- crop_data = None
92
- if not csv_data['crop_advisory'].empty:
93
- search_terms = {'crop_name': crop_name}
94
- if state:
95
- search_terms['state'] = state
96
- crop_data = search_csv_data(csv_data['crop_advisory'], search_terms)
97
-
98
- # Mock response - replace with actual API integration
99
- if not crop_data.empty:
100
- # Use data from CSV if available
101
- base_price = "₹2,180 per quintal"
102
- location_text = f" in {district or ''} {state}".strip()
103
- else:
104
- base_price = "₹2,180 per quintal"
105
- location_text = f" in {district or ''} {state}".strip()
106
-
107
- response_data = {
108
- "current_price": f"{base_price} for {crop_name}",
109
- "trend": "Prices increased by ₹50 in last week",
110
- "msp": "₹2,125 per quintal",
111
- "advice": "Current prices are above MSP. Good time to sell.",
112
- "location": location_text
113
- }
114
-
115
- return {
116
- "result": f"The current price of {crop_name}{location_text} is {response_data['current_price']}. {response_data['trend']}. MSP is {response_data['msp']}. {response_data['advice']}",
117
- "response_data": response_data
118
- }
119
-
120
- except Exception as e:
121
- return {
122
- "result": f"I'm sorry, I couldn't get the current market prices for {crop_name}. Please try again later or contact your local mandi for current rates.",
123
- "error": str(e)
124
- }
125
 
126
  @app.post("/api/scheme-eligibility")
127
  async def scheme_eligibility_endpoint(
@@ -207,42 +212,43 @@ async def scheme_eligibility_endpoint(
207
  }
208
 
209
  @app.post("/api/weather-advisory")
210
- async def weather_advisory_endpoint(
211
- request: Request,
212
- x_retell_signature: str = Header(None, alias="X-Retell-Signature")
213
- ):
214
- """Handle weather advisory function call from Retell.ai"""
215
- request_body = await request.body()
216
- retell_request = json.loads(request_body.decode('utf-8'))
217
-
218
- location = retell_request["args"].get("location", "")
219
- state = retell_request["args"].get("state", "")
220
- advisory_type = retell_request["args"].get("advisory_type", "general")
221
-
222
- try:
223
- # Mock weather data - integrate with IMD API
224
- weather_info = {
225
- "forecast": "Light to moderate rainfall expected in next 2-3 days",
226
- "temperature": "Maximum 28°C, Minimum 18°C",
227
- "advisory": "Avoid irrigation for next 3 days due to expected rainfall. Good time for land preparation for rabi sowing.",
228
- "warning": None
229
- }
230
-
231
- advisory_text = f"Weather forecast for {location}, {state}: {weather_info['forecast']}. Temperature: {weather_info['temperature']}. Advisory: {weather_info['advisory']}"
232
-
233
- if weather_info["warning"]:
234
- advisory_text += f" Warning: {weather_info['warning']}"
235
-
236
- return {
237
- "result": advisory_text,
238
- "weather_data": weather_info
239
- }
240
-
241
- except Exception as e:
242
- return {
243
- "result": f"I couldn't get weather information for {location} right now. Please check local weather updates or contact your agriculture department.",
244
- "error": str(e)
245
  }
 
246
 
247
  @app.post("/api/crop-advisory")
248
  async def crop_advisory_endpoint(
 
44
 
45
  # Load CSV data
46
  csv_data = load_csv_data()
47
+ WEATHER_API_KEY = "ee75ffd59875aa5ca6c207e594336b30"
48
+
49
+ def get_weather(city: str):
50
+ """Fetches weather data from OpenWeatherMap API."""
51
+ url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"
52
+ try:
53
+ response = requests.get(url, timeout=5)
54
+ response.raise_for_status()
55
+ data = response.json()
56
+
57
+ if data.get("cod") == 200:
58
+ weather_description = data['weather'][0]['description']
59
+ temperature = data['main']['temp']
60
+ humidity = data['main']['humidity']
61
+ pressure = data['main']['pressure']
62
+ return temperature, humidity, weather_description, pressure
63
+ except Exception as e:
64
+ print(f"Error fetching weather data: {e}")
65
+
66
+ return None, None, None, None
67
 
68
  class RetellRequest(BaseModel):
69
  name: str # Function name
 
93
  return result
94
 
95
  @app.post("/api/market-prices")
96
+ async def market_prices(request: dict):
97
+ crop_name = request.get("query", {}).get("crop_name", "").strip()
98
+ state = request.get("query", {}).get("state", "").strip()
99
+ district = request.get("query", {}).get("district", "").strip()
100
+
101
+ if "crop_advisory" in csv_data:
102
+ df = csv_data["crop_advisory"]
103
+ mask = (
104
+ df["crop_name"].str.lower() == crop_name.lower()
105
+ ) & (df["state"].str.lower() == state.lower()) & (
106
+ df["district"].str.lower() == district.lower()
107
+ )
108
+ matches = df[mask]
109
+
110
+ if not matches.empty:
111
+ try:
112
+ avg_price = matches["price"].astype(float).mean()
113
+ result = (
114
+ f"The average market price of {crop_name} in {district}, {state} "
115
+ f"is ₹{avg_price:.2f} per quintal."
116
+ )
117
+ except Exception:
118
+ result = f"Market data found but price column not numeric for {crop_name} in {district}, {state}."
119
+
120
+ return {
121
+ "success": True,
122
+ "result": result,
123
+ "data": matches.to_dict(orient="records")
124
+ }
125
+
126
+ return {
127
+ "success": False,
128
+ "result": f"No market price data found for {crop_name} in {district}, {state}."
129
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  @app.post("/api/scheme-eligibility")
132
  async def scheme_eligibility_endpoint(
 
212
  }
213
 
214
  @app.post("/api/weather-advisory")
215
+ async def weather_advisory(request: dict):
216
+ city = request.get("query", {}).get("location", "").strip()
217
+
218
+ temperature, humidity, description, pressure = get_weather(city)
219
+ if temperature is None:
220
+ # Fallback values
221
+ temperature, humidity, description, pressure = 32.0, 60, "Not Available", 1012
222
+ weather_condition = "NORMAL"
223
+ else:
224
+ desc_lower = description.lower()
225
+ if "clear" in desc_lower:
226
+ weather_condition = "SUNNY"
227
+ elif "rain" in desc_lower:
228
+ weather_condition = "RAINY"
229
+ elif "wind" in desc_lower:
230
+ weather_condition = "WINDY"
231
+ else:
232
+ weather_condition = "NORMAL"
233
+
234
+ result = (
235
+ f"Weather in {city}: {description}. "
236
+ f"Temperature {temperature}°C, Humidity {humidity}%, Pressure {pressure} hPa. "
237
+ f"Condition classified as {weather_condition}."
238
+ )
239
+
240
+ return {
241
+ "success": True,
242
+ "result": result,
243
+ "data": {
244
+ "city": city,
245
+ "temperature": temperature,
246
+ "humidity": humidity,
247
+ "pressure": pressure,
248
+ "description": description,
249
+ "condition": weather_condition
250
  }
251
+ }
252
 
253
  @app.post("/api/crop-advisory")
254
  async def crop_advisory_endpoint(