PkAgroMindAIPro / app.py
zakaullahAI's picture
Update app.py
b7744d8 verified
Raw History Blame Contribute Delete
4.75 kB
# app.py
import gradio as gr
import pandas as pd
import requests
from datasets import load_dataset
from transformers import pipeline
from PIL import Image
import io
# ---------------------------
# 1️⃣ Load Cloud / Colab Dataset (Dynamic)
# ---------------------------
# Example Hugging Face text dataset (can extend to Colab CSV datasets)
dataset = load_dataset("ag_news", split="train[:500]") # small sample for free-tier
df_text = pd.DataFrame(dataset)
# CSV-based crop yield dataset (example dynamic placeholder)
try:
csv_url = "https://raw.githubusercontent.com/username/fake-agri-yield/main/yield_data.csv"
df_yield = pd.read_csv(csv_url)
except:
df_yield = pd.DataFrame({"crop": ["Wheat", "Rice"], "avg_yield": [2.5, 3.0]})
# Display first few rows
print(df_text.head())
print(df_yield.head())
# ---------------------------
# 2️⃣ Text Classification Model
# ---------------------------
text_classifier = pipeline(
"text-classification",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
# ---------------------------
# 3️⃣ Weather Info Function
# ---------------------------
def get_weather(city_name):
try:
api_url = f"https://wttr.in/{city_name}?format=3" # Free API
response = requests.get(api_url)
if response.status_code == 200:
return response.text
return "Weather API Error!"
except Exception as e:
return str(e)
# ---------------------------
# 4️⃣ Crop Yield Prediction (CSV & Text-based logic)
# ---------------------------
def predict_yield(text_input, crop_name):
# Use CSV if crop exists
if crop_name in df_yield['crop'].values:
avg_yield = df_yield[df_yield['crop'] == crop_name]['avg_yield'].values[0]
return f"Predicted Yield for {crop_name}: {avg_yield:.2f} tons"
# Otherwise, dummy logic from text
words = len(text_input.split())
return f"Predicted Yield (text-based demo): {words * 0.5:.2f} tons"
# ---------------------------
# 5️⃣ Image-Based Crop Disease Detection (Lightweight CNN placeholder)
# ---------------------------
def detect_disease(image):
if image is None:
return "No image provided"
# Placeholder logic: In real production, replace with lightweight CNN
return "Detected Disease: Healthy (demo placeholder)"
# ---------------------------
# 6️⃣ Urdu AI Chatbot for Farmers
# ---------------------------
# Using a small T5 model (lightweight) for demonstration
try:
chatbot_model = pipeline("text-generation", model="google/flan-t5-small")
except:
chatbot_model = None # fallback if model fails in free tier
def urdu_chatbot(user_input):
if chatbot_model:
response = chatbot_model(f"Answer in Urdu: {user_input}", max_length=50)[0]['generated_text']
return response
return "Chatbot unavailable in free-tier"
# ---------------------------
# 7️⃣ Gradio Interface
# ---------------------------
def agro_ai_pipeline(text_input, crop_name, city_name, image_input, farmer_question):
# Text classification
cls_result = text_classifier(text_input)[0]
# Yield prediction
yield_result = predict_yield(text_input, crop_name)
# Weather info
weather_result = get_weather(city_name)
# Disease detection
disease_result = detect_disease(image_input)
# Urdu chatbot
chatbot_result = urdu_chatbot(farmer_question)
return cls_result, yield_result, weather_result, disease_result, chatbot_result
title = "🌾 Agriculture AI Assistant - Pakistan Hackathon Level"
description = """
Welcome to **Agriculture AI**!
Features:
- ✅ Dynamic text classification (advice, articles, etc.)
- ✅ Crop yield prediction (CSV + demo logic)
- ✅ Weather info for any Pakistani city
- ✅ Image-based crop disease detection (lightweight CNN placeholder)
- ✅ Urdu AI chatbot for farmers
All powered by **free Hugging Face models**, cloud datasets, and dynamic Colab/CSV sources!
"""
iface = gr.Interface(
fn=agro_ai_pipeline,
inputs=[
gr.Textbox(label="Enter Text (Crop Info / Advice)"),
gr.Textbox(label="Enter Crop Name"),
gr.Textbox(label="Enter City Name for Weather Info"),
gr.Image(label="Upload Crop Image for Disease Detection"),
gr.Textbox(label="Ask a Question in Urdu")
],
outputs=[
gr.Label(label="Text Classification"),
gr.Textbox(label="Predicted Crop Yield"),
gr.Textbox(label="Weather Info"),
gr.Textbox(label="Crop Disease Detection"),
gr.Textbox(label="Urdu AI Chatbot Response")
],
title=title,
description=description,
theme="default",
allow_flagging="never"
)
if __name__ == "__main__":
iface.launch()