Spaces:
Sleeping
Sleeping
Download app.py from nischal5490/Turmeric_ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/spaces/nischal5490/Turmeric_ChatBot/resolve/main/app.py
- Command line
-
hf download hf://spaces/nischal5490/Turmeric_ChatBot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nischal5490/Turmeric_ChatBot/resolve/main/app.py
20.6 kB
| import os | |
| import io | |
| from datetime import datetime, date | |
| import gradio as gr | |
| from PIL import Image | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import torch | |
| import torch.nn as nn | |
| import torchvision.transforms as transforms | |
| from torchvision.models import resnet18 | |
| # ================================ | |
| # Speed knobs (env overridable) | |
| # ================================ | |
| SMALL_LLM_MODEL = os.getenv("SMALL_LLM_MODEL", "google/flan-t5-small") # fast default | |
| MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "80")) | |
| TEMPERATURE = float(os.getenv("TEMPERATURE", "0.4")) | |
| TOP_P = float(os.getenv("TOP_P", "0.9")) | |
| REPETITION_PENALTY = float(os.getenv("REPETITION_PENALTY", "1.15")) | |
| # ====================================================== | |
| # 1) Load your local disease model (no HF token required) | |
| # ====================================================== | |
| MODEL_LOCAL_PATH = os.path.join(os.path.dirname(__file__), "turmeric_model.pth") | |
| DISEASE_CLASSES = ['Dry_Leaf', 'Healthy_Leaf', 'Leaf_Blotch', 'Rhizome_Disease', 'Rhizome_Healthy'] | |
| transform_img = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor() | |
| ]) | |
| disease_model = resnet18(weights=None) | |
| disease_model.fc = nn.Linear(disease_model.fc.in_features, len(DISEASE_CLASSES)) | |
| disease_model.load_state_dict(torch.load(MODEL_LOCAL_PATH, map_location=torch.device("cpu"))) | |
| disease_model.eval() | |
| # ========================================== | |
| # 2) Agronomy logic (growth stages & advice) | |
| # ========================================== | |
| GROWTH_STAGES = { | |
| "Planting": (0, 30), | |
| "Vegetative": (31, 120), | |
| "Rhizome Bulking": (121, 200), | |
| "Maturity": (201, 240) | |
| } | |
| STAGE_DETAILS = { | |
| "Planting": "Initial planting and establishment of turmeric rhizomes.", | |
| "Vegetative": "Rapid leaf and shoot growth. High water and light needs.", | |
| "Rhizome Bulking": "Main rhizome expansion phase. Needs stable soil moisture.", | |
| "Maturity": "Leaves yellow and die back. Rhizomes mature underground." | |
| } | |
| BASE_CONDITIONS = { | |
| "Planting": {"temp": (25, 32), "humidity": (70, 90), "soil": (65, 105), "light": (200, 300), "ph": (6.0, 6.8)}, | |
| "Vegetative": {"temp": (20, 30), "humidity": (60, 80), "soil": (45, 75), "light": (300, 500), "ph": (6.0, 6.8)}, | |
| "Rhizome Bulking": {"temp": (22, 28), "humidity": (60, 70), "soil": (45, 65), "light": (400, 600), "ph": (6.0, 6.8)}, | |
| "Maturity": {"temp": (18, 30), "humidity": (50, 60), "soil": (25, 45), "light": (200, 300), "ph": (6.0, 6.8)} | |
| } | |
| def highlight_text(text): | |
| if text.startswith("✅"): | |
| return "<span style='color:green; font-weight:bold; animation: blink-green 1s infinite;'>{}</span>".format(text) | |
| else: | |
| return "<span style='color:red; font-weight:bold; animation: blink-red 1s infinite;'>{}</span>".format(text) | |
| def turmeric_advisor(planting_date, temp, humidity, soil_moisture, light_intensity, ph): | |
| try: | |
| planting_date = datetime.strptime(planting_date, "%Y-%m-%d").date() | |
| except Exception: | |
| return ["❌ Invalid planting date format.", "", "", "", "", "", "", None, ""] | |
| days_since = (date.today() - planting_date).days | |
| current_stage = "Unknown" | |
| for stage, (start, end) in GROWTH_STAGES.items(): | |
| if start <= days_since <= end: | |
| current_stage = stage | |
| break | |
| if current_stage == "Unknown": | |
| return ["⚠️ Could not estimate stage. Check date.", "", "", "", "", "", "", None, ""] | |
| stage_description = STAGE_DETAILS[current_stage] | |
| stage_ideal = BASE_CONDITIONS[current_stage] | |
| def feedback(val, low, high, ok_text, low_text, high_text): | |
| if val < low: | |
| return f"🔻 {low_text}" | |
| elif val > high: | |
| return f"🔺 {high_text}" | |
| else: | |
| return f"✅ {ok_text}" | |
| temp_msg = feedback(temp, *stage_ideal['temp'], "Temperature OK", "Too Cold – Consider warming", "Too Hot – Consider shading") | |
| hum_msg = feedback(humidity, *stage_ideal['humidity'], "Humidity OK", "Humidity Too Dry – Mist/spray", "Humidity Too Humid – Ventilate") | |
| soil_msg = feedback(soil_moisture, *stage_ideal['soil'], "Soil Moisture OK", "Soil Moisture Too Dry – Water", "Soil Moisture Too Wet – Drain excess") | |
| light_msg = feedback(light_intensity, *stage_ideal['light'], "Light Intensity OK", "Too Low – Increase light", "Too High – Reduce light") | |
| ph_msg = feedback(ph, *stage_ideal['ph'], "pH OK", "Too Low – Add base", "Too High – Add acid") | |
| table_md = f""" | |
| ### 📊 Turmeric Growth Stage Parameter Ranges – Current Stage: **{current_stage}** | |
| | Parameter | Ideal Range | | |
| |-----------------|------------------| | |
| | 🌡️ Temperature | {stage_ideal['temp'][0]} – {stage_ideal['temp'][1]} °C | | |
| | 💧 Humidity | {stage_ideal['humidity'][0]} – {stage_ideal['humidity'][1]} % | | |
| | 🌱 Soil Moisture| {stage_ideal['soil'][0]} – {stage_ideal['soil'][1]} % | | |
| | 💡 Light Intensity | {stage_ideal['light'][0]} – {stage_ideal['light'][1]} µmol/m²/s | | |
| | 🧪 pH | {stage_ideal['ph'][0]} – {stage_ideal['ph'][1]} | | |
| """ | |
| stages = list(GROWTH_STAGES.keys()) | |
| days = [GROWTH_STAGES[s][1] for s in stages] | |
| colors = ["green" if d >= days_since else "lightgray" for d in days] | |
| fig, ax = plt.subplots() | |
| ax.bar(stages, days, color=colors) | |
| ax.axhline(days_since, color="red", linestyle="--") | |
| ax.set_ylabel("Days") | |
| ax.set_title("Estimated Growth Progress") | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', bbox_inches="tight") | |
| buf.seek(0) | |
| chart_img = Image.open(buf) | |
| return [ | |
| f"🌱 Stage: {current_stage} ({days_since} days since planting)", | |
| stage_description, | |
| highlight_text(temp_msg), | |
| highlight_text(hum_msg), | |
| highlight_text(soil_msg), | |
| highlight_text(light_msg), | |
| highlight_text(ph_msg), | |
| chart_img, | |
| table_md | |
| ] | |
| def detect_disease(image): | |
| image = image.convert("RGB") | |
| img_tensor = transform_img(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| outputs = disease_model(img_tensor) | |
| _, predicted = torch.max(outputs, 1) | |
| return f"🩺 Prediction: {DISEASE_CLASSES[predicted.item()]}" | |
| # ====================================== | |
| # 3) Mini-LLM chat (fast CPU default) | |
| # ====================================== | |
| from typing import List, Tuple | |
| import re | |
| SYSTEM_PROMPT = ( | |
| "You are a concise, practical assistant for turmeric farming and vertical farming. " | |
| "Answer in 2–5 sentences using metric units. If unsure, say so briefly. " | |
| "Ignore or refuse unrelated topics and keep focus on turmeric cultivation, environment, pests, and processing." | |
| ) | |
| _llm_kind = None | |
| _tokenizer = None | |
| _model = None | |
| _gen_pipe = None | |
| def _clean_text(s: str) -> str: | |
| s = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]", " ", s) | |
| s = s.replace("�", "") | |
| s = re.sub(r"\s+", " ", s).strip() | |
| return s | |
| def _load_small_llm(): | |
| """Prefer fast seq2seq on CPU; allow user to point to a chat model via SMALL_LLM_MODEL.""" | |
| global _llm_kind, _tokenizer, _model, _gen_pipe | |
| try: | |
| # Try seq2seq first for speed (flan-t5-small default) | |
| from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline, AutoConfig | |
| cfg = AutoConfig.from_pretrained(SMALL_LLM_MODEL) | |
| if "T5" in cfg.model_type.upper() or "seq2seq" in cfg.__class__.__name__.lower() or "t5" in SMALL_LLM_MODEL.lower(): | |
| _tokenizer = AutoTokenizer.from_pretrained(SMALL_LLM_MODEL) | |
| _model = AutoModelForSeq2SeqLM.from_pretrained(SMALL_LLM_MODEL) | |
| _gen_pipe = pipeline("text2text-generation", model=_model, tokenizer=_tokenizer) | |
| _llm_kind = "t2t" | |
| print(f"[mini-llm] Loaded seq2seq model: {SMALL_LLM_MODEL}") | |
| return | |
| except Exception as e: | |
| print(f"[mini-llm] Seq2Seq load attempt failed: {e}") | |
| # Fallback: try a causal chat model (slower on CPU) | |
| try: | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| _tokenizer = AutoTokenizer.from_pretrained(SMALL_LLM_MODEL, use_fast=True) | |
| if _tokenizer.pad_token is None and _tokenizer.eos_token: | |
| _tokenizer.pad_token = _tokenizer.eos_token | |
| _model = AutoModelForCausalLM.from_pretrained( | |
| SMALL_LLM_MODEL, | |
| low_cpu_mem_usage=True, | |
| torch_dtype=torch.float32 | |
| ) | |
| _llm_kind = "chat" | |
| print(f"[mini-llm] Loaded causal chat model: {SMALL_LLM_MODEL}") | |
| except Exception as e: | |
| print(f"[mini-llm] Causal model load failed: {e}") | |
| _llm_kind = None | |
| _load_small_llm() | |
| def _build_chat_prompt(history: List[Tuple[str, str]], user_msg: str): | |
| # For t2t we build a compact instruction prompt; for chat we try apply_chat_template | |
| if _llm_kind == "t2t": | |
| context = " ".join([f"Q:{u} A:{a}" for (u, a) in (history or [])[-3:]]) | |
| context_str = f"Context: {context}\n" if context else "" | |
| prompt = ( | |
| f"{SYSTEM_PROMPT}\n" | |
| f"{context_str}" | |
| f"Question: {user_msg}\n" | |
| f"Answer:" | |
| ) | |
| return prompt | |
| else: | |
| # chat-style | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] | |
| for u, a in (history or []): | |
| if u: | |
| messages.append({"role": "user", "content": u}) | |
| if a: | |
| messages.append({"role": "assistant", "content": a}) | |
| messages.append({"role": "user", "content": user_msg}) | |
| try: | |
| return _tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt") | |
| except Exception: | |
| # Plain prompt fallback | |
| txt = "System: " + SYSTEM_PROMPT + "\n" | |
| for u, a in (history or []): | |
| txt += f"User: {u}\nAssistant: {a}\n" | |
| txt += f"User: {user_msg}\nAssistant:" | |
| return _tokenizer([txt], return_tensors="pt").input_ids | |
| def _llm_answer_one_shot(question: str) -> str: | |
| """Generate a short answer without chat history.""" | |
| if _llm_kind is None: | |
| return "" | |
| if _llm_kind == "t2t": | |
| prompt = _build_chat_prompt([], question) | |
| out = _gen_pipe( | |
| prompt, | |
| max_new_tokens=MAX_NEW_TOKENS, | |
| temperature=TEMPERATURE, | |
| top_p=TOP_P, | |
| repetition_penalty=REPETITION_PENALTY, | |
| ) | |
| return _clean_text(out[0]["generated_text"]) | |
| else: | |
| # chat causal (may be slower on CPU) | |
| input_ids = _build_chat_prompt([], question).to(_model.device) | |
| with torch.no_grad(): | |
| out_ids = _model.generate( | |
| input_ids=input_ids, | |
| max_new_tokens=MAX_NEW_TOKENS, | |
| temperature=TEMPERATURE, | |
| top_p=TOP_P, | |
| repetition_penalty=REPETITION_PENALTY, | |
| do_sample=True, | |
| eos_token_id=_tokenizer.eos_token_id, | |
| pad_token_id=_tokenizer.pad_token_id, | |
| ) | |
| gen_text = _tokenizer.decode(out_ids[0][input_ids.shape[-1]:], skip_special_tokens=True) | |
| for stop in ["\nUser:", "\n<|user|>", "\n### User:"]: | |
| pos = gen_text.find(stop) | |
| if pos != -1: | |
| gen_text = gen_text[:pos] | |
| break | |
| return _clean_text(gen_text) | |
| # --------------------------- | |
| # Region → Rule-based windows | |
| # --------------------------- | |
| REGION_CHOICES = [ | |
| "Tropical monsoon (e.g., Kerala, Sri Lanka)", | |
| "Subtropical (e.g., Maharashtra, Vietnam lowlands)", | |
| "Equatorial humid (e.g., Malaysia, Singapore)", | |
| "Mediterranean/Temperate outdoors", | |
| "Temperate greenhouse/polyhouse", | |
| "Arid or semi-arid with irrigation", | |
| "Europe indoor vertical farm (e.g., Germany)" | |
| ] | |
| def _region_window_text(region: str) -> str: | |
| if region == "Tropical monsoon (e.g., Kerala, Sri Lanka)": | |
| return ( | |
| "**Best window:** Late May – early July (just before/at monsoon onset)\n" | |
| "**Why:** Warm soil + reliable rainfall aids sprouting and early vegetative growth.\n" | |
| "**Tip:** Use sprouted rhizome sets; ensure drainage in heavy rains." | |
| ) | |
| if region == "Subtropical (e.g., Maharashtra, Vietnam lowlands)": | |
| return ( | |
| "**Best window:** Late May – July (align with monsoon); minor window: Feb–Mar with irrigation.\n" | |
| "**Why:** Heat and humidity drive vigorous vegetative growth.\n" | |
| "**Tip:** Mulch to retain moisture; manage shade if temps >35 °C." | |
| ) | |
| if region == "Equatorial humid (e.g., Malaysia, Singapore)": | |
| return ( | |
| "**Best window:** Year-round possible; best results Feb–Apr or Aug–Oct to avoid peak storms.\n" | |
| "**Why:** Stable warmth/humidity; choose calmer weather windows.\n" | |
| "**Tip:** Elevate beds, ensure drainage; manage leaf diseases in wet spells." | |
| ) | |
| if region == "Mediterranean/Temperate outdoors": | |
| return ( | |
| "**Best window:** Mid–late spring (Apr–May) after frost risk; harvest by Oct–Nov.\n" | |
| "**Why:** Needs 7–9 warm months; nights >18 °C improve establishment.\n" | |
| "**Tip:** Pre-sprout rhizomes indoors 4–6 weeks; use black plastic/mulch for soil heat." | |
| ) | |
| if region == "Temperate greenhouse/polyhouse": | |
| return ( | |
| "**Best window:** Feb–Apr under protection; maintain 22–30 °C, RH 60–80%.\n" | |
| "**Why:** Controlled warmth extends season and stabilizes bulking phase.\n" | |
| "**Tip:** Provide 300–600 µmol m⁻² s⁻¹ PPFD; keep pH 6.0–6.8; steady moisture." | |
| ) | |
| if region == "Arid or semi-arid with irrigation": | |
| return ( | |
| "**Best window:** Feb–Mar or Aug–Sep with reliable drip irrigation and wind/sun protection.\n" | |
| "**Why:** Heat is available; moisture must be managed precisely.\n" | |
| "**Tip:** Shade net 30–40%, heavy mulch, and EC-controlled fertigation." | |
| ) | |
| if region == "Europe indoor vertical farm (e.g., Germany)": | |
| return ( | |
| "**Best window:** Any time (controlled environment).\n" | |
| "**Why:** Closed-loop control on temp 22–28 °C, RH 60–75%, PPFD 300–600.\n" | |
| "**Tip:** 16 h light/8 h dark vegetative; 12–14 h late bulking; harvest 7–9 months." | |
| ) | |
| return "Select a region to see planting guidance." | |
| def planting_calendar_tip(region: str) -> str: | |
| base = _region_window_text(region) | |
| ai_note = "" | |
| question = ( | |
| "In 2–3 sentences, summarize the best planting window for turmeric and key reasons and tips " | |
| f"for this region: {region}. Use months and metric units. Keep it concise." | |
| ) | |
| model_resp = _llm_answer_one_shot(question) | |
| if model_resp: | |
| ai_note = f"\n\n**AI note:** {model_resp}" | |
| return f"### 🗓️ Planting Calendar — {region}\n\n{base}{ai_note}" | |
| # ==================== | |
| # 4) Gradio UI (Blocks) | |
| # ==================== | |
| action_log = [] | |
| def simulate_action(action): | |
| log = f"✅ Simulated: {action} activated." | |
| action_log.append(log) | |
| return "\n".join(action_log[-10:]) | |
| def public_chat_turmeric(query): | |
| return f"🤖 This is a simulated response. You asked: '{query}'\nFor more accurate insights, integrate ChatGPT with your OpenAI API key." | |
| with gr.Blocks(css=""" | |
| @keyframes blink-red { 0% {opacity: 1;} 50% {opacity: 0.3;} 100% {opacity: 1;} } | |
| @keyframes blink-green { 0% {opacity: 1;} 50% {opacity: 0.7;} 100% {opacity: 1;} } | |
| .blinking-red { animation: blink-red 1s infinite; border: 2px solid red; } | |
| .blinking-green { animation: blink-green 1s infinite; border: 2px solid green; } | |
| """, title="🌿 Smart Turmeric Farming Advisor") as demo: | |
| with gr.Tab("🌱 Growth Advisor"): | |
| gr.Markdown("## 🌿 Turmeric Growth Advisor") | |
| # Region selector + Tip button | |
| with gr.Row(): | |
| region_dd = gr.Dropdown( | |
| choices=REGION_CHOICES, | |
| value="Temperate greenhouse/polyhouse", | |
| label="🌍 Region / Growing context" | |
| ) | |
| tip_btn = gr.Button("🗓️ Planting Calendar Tip", variant="secondary") | |
| calendar_tip_md = gr.Markdown("") | |
| with gr.Row(): | |
| planting_date = gr.Textbox(label="📅 Planting Date (YYYY-MM-DD)", value=str(date.today())) | |
| soil_moisture = gr.Slider(0, 100, value=60, label="🌱 Soil Moisture (%)") | |
| with gr.Row(): | |
| temp = gr.Slider(10, 45, value=28, label="🌡️ Temperature (°C)") | |
| humidity = gr.Slider(30, 100, value=70, label="💧 Humidity (%)") | |
| light_intensity = gr.Slider(100, 700, value=300, label="💡 Light Intensity (µmol/m²/s)") | |
| ph = gr.Slider(4.0, 8.0, value=6.5, step=0.1, label="🧪 Soil pH") | |
| submit_btn = gr.Button("🔍 Get Recommendations") | |
| with gr.Column(): | |
| stage_out = gr.HTML() | |
| stage_desc = gr.HTML() | |
| temp_out = gr.HTML() | |
| hum_out = gr.HTML() | |
| soil_out = gr.HTML() | |
| light_out = gr.HTML() | |
| ph_out = gr.HTML() | |
| range_table = gr.Markdown() | |
| chart_out = gr.Image(type="pil") | |
| gr.Markdown("### ⚙️ Simulated Adjustments") | |
| with gr.Row(): | |
| fan_btn = gr.Button("🌀 Activate Fan", elem_classes=["blinking-red"]) | |
| humidifier_btn = gr.Button("💨 Turn On Humidifier", elem_classes=["blinking-red"]) | |
| light_btn = gr.Button("💡 Adjust Light", elem_classes=["blinking-red"]) | |
| pump_btn = gr.Button("💧 Water Pump", elem_classes=["blinking-red"]) | |
| ph_btn = gr.Button("🧪 Apply pH Solution", elem_classes=["blinking-red"]) | |
| action_result = gr.Textbox(label="📝 Simulated Action Log", lines=8) | |
| submit_btn.click( | |
| turmeric_advisor, | |
| inputs=[planting_date, temp, humidity, soil_moisture, light_intensity, ph], | |
| outputs=[stage_out, stage_desc, temp_out, hum_out, soil_out, light_out, ph_out, chart_out, range_table] | |
| ) | |
| tip_btn.click(planting_calendar_tip, inputs=[region_dd], outputs=calendar_tip_md) | |
| fan_btn.click(lambda: simulate_action("Fan"), outputs=action_result) | |
| humidifier_btn.click(lambda: simulate_action("Humidifier"), outputs=action_result) | |
| light_btn.click(lambda: simulate_action("Light Adjustment"), outputs=action_result) | |
| pump_btn.click(lambda: simulate_action("Water Pump"), outputs=action_result) | |
| ph_btn.click(lambda: simulate_action("pH Balancer"), outputs=action_result) | |
| with gr.Tab("🩺 Disease Detection"): | |
| gr.Markdown("## 🩺 Turmeric Disease Detection") | |
| image_input = gr.Image(type="pil", label="📷 Upload Leaf or Rhizome Image") | |
| prediction_output = gr.Textbox(label="Prediction") | |
| detect_btn = gr.Button("🧠 Analyze Disease") | |
| detect_btn.click(fn=detect_disease, inputs=image_input, outputs=prediction_output) | |
| with gr.Tab("🤖 Public AI Help"): | |
| gr.Markdown("## 🤖 Ask the AI about turmeric farming (demo only)") | |
| public_input = gr.Textbox(label="💬 Ask something about turmeric") | |
| public_output = gr.Textbox(label="🤖 AI Response") | |
| gr.Button("💡 Ask").click(fn=public_chat_turmeric, inputs=public_input, outputs=public_output) | |
| with gr.Tab("🧪 Local Mini-LLM Chat"): | |
| gr.Markdown("### Fast mini-LLM chat (CPU). Defaults to flan-t5-small.") | |
| chatbot = gr.Chatbot(height=360) | |
| msg = gr.Textbox(label="Your question", placeholder="e.g., When to plant turmeric in a subtropical climate?") | |
| send = gr.Button("Send") | |
| clear = gr.Button("Clear chat") | |
| def user_submit(user_message, chat_history): | |
| return "", (chat_history or []) + [(user_message, "")] | |
| def small_llm_reply(message, chat_history): | |
| ans = _llm_answer_one_shot(message) | |
| if not ans: | |
| ans = "Mini-LLM unavailable right now. Try again or keep questions short." | |
| return "", (chat_history or []) + [(message, ans)] | |
| send.click(user_submit, [msg, chatbot], [msg, chatbot]).then( | |
| small_llm_reply, [msg, chatbot], [msg, chatbot] | |
| ) | |
| msg.submit(user_submit, [msg, chatbot], [msg, chatbot]).then( | |
| small_llm_reply, [msg, chatbot], [msg, chatbot] | |
| ) | |
| clear.click(lambda: None, None, chatbot) | |
| # Queue to prevent CPU thrash | |
| demo.queue() | |
| if __name__ == "__main__": | |
| demo.launch() |