from flask import Flask, render_template, request, jsonify from keras.models import load_model from PIL import Image, ImageOps import numpy as np import io import base64 from groq import Groq from deep_translator import GoogleTranslator import os from dotenv import load_dotenv # Load environment variables load_dotenv() app = Flask(__name__) # Load the model for disease detection MODEL_PATH = os.path.join(os.path.dirname(__file__), "s3", "keras_model.h5") model = load_model(MODEL_PATH, compile=False) # Load the labels for disease detection class_names = open("s3/labels.txt", "r").readlines() # Medication suggestions medications = { "1 LUMPY SKIN": "Tips for Lumpy Skin Disease (LSD):" "Isolation: Immediately isolate affected animals to prevent the spread of the disease to other livestock." "Hygiene: Maintain a clean environment by disinfecting animal housing, feeding equipment, and water troughs regularly." "Supportive Care: Ensure animals are well-fed with a nutritious diet to strengthen their immune systems. Providing fresh, clean water is essential." "Reduce Stress: Keep the animals in a calm and stress-free environment. Stress can worsen disease symptoms." "Monitor for Secondary Infections: Keep an eye on skin lesions and prevent further infection by cleaning any open wounds.", "4 RINGWORM": "Management Tips for Ringworm:" "Isolate Infected Animals to prevent spread." "Maintain Cleanliness by changing bedding and disinfecting equipment." "Improve Nutrition with a balanced diet and supplements like zinc and vitamin A." "Use Topical Antifungal Ointments like clotrimazole or sulfur dips." "Sun Exposure can help kill fungi." "Groom Regularly to remove scabs and infected fur." "Reduce Stress by providing a comfortable environment." "Monitor Other Animals for signs and consult a vet if needed.", "6 MASTITIS": "Tips and management for Mastitis" "Frequent Milking: Regular milking helps prevent milk build-up and reduces the chances of infection." "Proper Hygiene: Clean the udder and teats before and after milking to prevent bacterial entry. Use sanitized towels and gloves." "Dry Cow Therapy: After the lactating period, administer dry cow therapy to prevent mastitis and keep the udder healthy." "Diet Management: Ensure a balanced nutrition with adequate amounts of vitamins and minerals to maintain good udder health." "Massaging: Gently massage the udder to improve circulation and promote milk flow, which can help reduce the risk of mastitis.", "3 SHEEP SCABIES": "Tips for Sheep Scabies (For Mouth Area)" "Keep Sheep Clean: Regularly bathe the sheep in mild antiseptic solutions to help remove mites from the skin." "Maintain Bedding: Change bedding frequently to prevent mite infestations. Clean the stalls with a disinfectant to kill any remaining mites." "Improve Nutrition: Provide a balanced diet with minerals and vitamins that help strengthen the immune system and promote skin healing." "Reduce Stress: Avoid overcrowding, and provide adequate space, ventilation, and quiet surroundings to reduce stress, which can worsen scabies." "Skin Care: Apply soothing oils like neem oil or coconut oil to the affected areas, especially around the mouth, to help calm irritation and moisturize the skin." "Monitor and Isolate: Isolate any affected animals to prevent the spread of the disease to healthy sheep.", "10 GREASY DISEASE": "Prevention and Management Tips for Greasy Disease:" "Clean and Dry Conditions: Keep pens and bedding dry to prevent bacterial growth." "Isolate: Separate infected pigs to avoid spreading." "Boost Immunity: Provide a balanced diet with vitamins A, E, and omega-3 fatty acids." "Skin Care: Clean affected areas with antiseptic and apply antibacterial ointments." "Herbal Remedies: Use neem oil and turmeric paste for their antibacterial properties." "Hydration: Ensure access to fresh, clean water." "Monitor: Watch for early signs and isolate any affected animals." } # Groq API initialization from .env API_KEY = os.getenv("GROQ_API_KEY") if not API_KEY: raise ValueError("GROQ_API_KEY is missing from the .env file") client = Groq(api_key=API_KEY) def translate_text(text, target_language): return GoogleTranslator(source="auto", target=target_language).translate(text) @app.route("/") def home(): return render_template("home.html") @app.route("/rearing-guidance") def rearing_guidance(): return render_template('s1.html') @app.route('/result', methods=['POST']) def result(): animal_type = request.form['animal_type'] number_of_animals = int(request.form['number_of_animals']) area_size, feed_type, feed_quantity, cost_in_inr, water_supply, hygiene_tips, seasonal_tips = get_animal_data(animal_type, number_of_animals) return render_template('s1.html', area_size=area_size, feed_type=feed_type, feed_quantity=feed_quantity, cost_in_inr=cost_in_inr, water_supply=water_supply, hygiene_tips=hygiene_tips, seasonal_tips=seasonal_tips, animal_type=animal_type, number_of_animals=number_of_animals) def get_animal_data(animal_type, count): data = { 'Cow': (19.81, 'Green Feed', 24.85, 6652.15, 68.52, 'Clean barn daily, vaccinate regularly', 'Summer: Provide shade, Winter: Warmth, Rainy: Avoid damp.'), 'Buffalo': (24.58, 'Dry Feed', 31.45, 7483.52, 81.23, 'Ensure proper ventilation', 'Summer: Shade, Winter: Shelter, Rainy: Dry bedding.'), 'Pig': (15.25, 'Concentrates', 5.15, 4989.25, 50.60, 'Use disinfectants weekly', 'Summer: Cool & dry, Winter: Warmth, Rainy: Dry pens.'), 'Goat': (10.21, 'Green Feed', 3.25, 3325.60, 20.55, 'Provide clean bedding', 'Summer: Shade, Winter: Warm shelter, Rainy: Avoid damp.'), 'Sheep': (12.50, 'Green Feed', 4.75, 3741.75, 25.80, 'Check for parasites', 'Summer: Water, Winter: Shelter, Rainy: Dry conditions.'), 'Poultry': (1.5, 'Grain-based Feed', 0.25, 120, 0.5, 'Keep coop clean', 'Summer: Ventilation, Winter: Heat, Rainy: Dry coop.'), 'Bee Hiving': (10.25, 'Sugar Syrup', 0.5, 1500.55, 0.25, 'Check for pests', 'Summer: Water, Winter: Food stores, Rainy: Avoid disturbance.'), 'Sericulture': (4.85, 'Mulberry Leaves', 0.1, 198.25, 0.2, 'Clean & dry environment', 'Summer: Cool & dry, Winter: Warm, Rainy: Airflow.') } base_values = data.get(animal_type) return tuple(v * count if isinstance(v, (int, float)) else v for v in base_values) @app.route("/ai-chatbot") def ai_chatbot(): return render_template("s2.html") @app.route("/chat", methods=["POST"]) def chat(): data = request.json user_message = data.get("message") target_language = data.get("language", "en") try: user_message_en = translate_text(user_message, "en") response = client.chat.completions.create( messages=[{"role": "user", "content": user_message_en}], model="llama-3.3-70b-versatile" ) bot_response_en = response.choices[0].message.content bot_response_translated = translate_text(bot_response_en, target_language) return jsonify({"response": bot_response_translated}) except Exception as e: return jsonify({"response": f"Error: {str(e)}"}), 500 @app.route("/disease-detection", methods=["GET", "POST"]) def disease_detection(): prediction, confidence, medication, img_data, error = None, None, None, None, None if request.method == "POST" and 'file' in request.files: file = request.files["file"] if file.filename: try: image_bytes = file.read() image = Image.open(io.BytesIO(image_bytes)).convert("RGB") image = ImageOps.fit(image, (224, 224), Image.Resampling.LANCZOS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) data[0] = normalized_image_array prediction_raw = model.predict(data) index = np.argmax(prediction_raw) class_name = class_names[index].strip() confidence_score = prediction_raw[0][index] * 100 prediction = f"Predicted Disease: {class_name}" confidence = f"{confidence_score:.2f}%" medication = medications.get(class_name) img_byte_array = io.BytesIO() image.save(img_byte_array, format="PNG") img_data = base64.b64encode(img_byte_array.getvalue()).decode("utf-8") except Exception as e: error = f"Error processing image: {e}" else: error = "No file selected." return render_template("s3.html", prediction=prediction, confidence=confidence, medication=medication, img_data=img_data, error=error) @app.route("/information") def information(): return render_template("information.html") @app.route("/latest-innovations") def latest_innovations(): return render_template("latest-innovations.html") @app.route("/govt-schemes") def govt_schemes(): return render_template("govt-schemes.html") @app.route("/veterinary_map") def veterinary_map(): return render_template("veterinary_map.html") if __name__ == "__main__": port = int(os.environ.get("PORT", 7860)) app.run(host="0.0.0.0", port=port, debug=True)