Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155import osimport gradio as grfrom groq import Groqfrom langdetect import detectfrom dotenv import load_dotenv# Load environment variablesload_dotenv()# Initialize Groq clientclient = Groq(api_key=os.getenv("GROQ_API_KEY"))# Supported languages and their agricultural terminologySUPPORTED_LANGUAGES = {"en": "English","ur": "Urdu","pa": "Punjabi","sd": "Sindhi","ps": "Pashto"}# Agricultural knowledge base (can be expanded)AGRICULTURE_KB = {"pest_control": {"en": "For pest control, consider neem oil or biopesticides. Rotate crops to prevent pest buildup.","ur": "کیڑوں کے کنٹرول کے لیے، نیم کا تیل یا بائیو پیسٹیسائیڈز استعمال کریں۔ کیڑوں کی افزائش کو روکنے کے لیے فصلوں کو گھمائیں۔","pa": "کیڑوں دے کنٹرول لئی، نیم دے تیل یا بائیو پیسٹیسائیڈز استعمال کرو۔ کیڑےآں دی روک تھام لئی فصلاں گھماؤ۔","sd": "ڪيڙن جي ڪنٽرول لاءِ، نيم جو تيل يا بائيڪيڙا مار دوائون استعمال ڪريو. ڪيڙا جي روڪٿام لاءِ فصلون گهمايو.","ps": "د حشراتو د کنټرول لپاره، نیم تیل یا بایو پیسټیسایډونه وکاروئ. د حشراتو د مخنیوي لپاره فصلونه ګرځوئ."},"weather": {"en": "Check local weather forecasts regularly. Protect crops from extreme weather with proper covering.","ur": "مقامی موسم کی پیشگوئی کو باقاعدگی سے چیک کریں۔ مناسب ڈھکن کے ساتھ فصلوں کو شدید موسم سے بچائیں۔","pa": "مقامی موسم دی پیشن گوئی باقاعدگی نال چیک کرو۔ مناسب ڈھکن نال فصلاں نوں شدید موسم توں بچاؤ۔","sd": "مقامي موسم جي پيشگوئي باقاعده چيڪ ڪريو. مناسب ڍڪڻ سان فصلون شديد موسم کان بچايو.","ps": "محلي هواپېژندنه منظم ګوري. د فصلونو د سخت هوا څخه د مناسب پوښ سره ساتنه وکړئ."}}def detect_language(text):try:lang = detect(text)return lang if lang in SUPPORTED_LANGUAGES else "en"except:return "en"def get_agriculture_advice(query, language):"""Get context-specific advice based on query"""query_lower = query.lower()if any(word in query_lower for word in ["pest", "کیڑے", "ڪيڙا", "حشرات"]):return AGRICULTURE_KB["pest_control"].get(language, AGRICULTURE_KB["pest_control"]["en"])if any(word in query_lower for word in ["weather", "موسم", "هوا"]):return AGRICULTURE_KB["weather"].get(language, AGRICULTURE_KB["weather"]["en"])return Nonedef generate_response(message, history):# Detect language of the querylang = detect_language(message)# First check if we have predefined knowledge for this querykb_response = get_agriculture_advice(message, lang)if kb_response:return kb_response# If not in KB, use Groq API for generationsystem_prompt = f"""You are an agricultural expert assistant helping farmers in {SUPPORTED_LANGUAGES.get(lang, "English")}.Provide concise, practical advice in the same language as the question.Focus on crop cultivation, pest control, weather impact, and market prices.Use simple terms suitable for farmers with basic education."""try:chat_completion = client.chat.completions.create(messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": message}],model="mixtral-8x7b-32768",temperature=0.3,max_tokens=1024)return chat_completion.choices[0].message.contentexcept Exception as e:return f"Error: {str(e)}. Please try again later."# Custom CSS for better UIcss = """.gradio-container {font-family: 'Helvetica', Arial, sans-serif;background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);}.header {text-align: center;padding: 20px;background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%);color: white;border-radius: 8px;margin-bottom: 20px;}.footer {text-align: center;margin-top: 20px;font-size: 12px;color: #666;}.agriculture-theme {background: url('https://images.unsplash.com/photo-1500382017468-9049fed747ef?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80') no-repeat center center fixed;background-size: cover;}"""# Create Gradio interfacewith gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:with gr.Column():gr.Markdown("""<div class="header"><h1>🌾 Local Language Agri-Advisor</h1><p>Get farming advice in Urdu, Pashto, Sindhi, Punjabi, or English</p></div>""")chatbot = gr.Chatbot(label="Chat with Agri-Expert",bubble_full_width=False,avatar_images=("https://cdn-icons-png.flaticon.com/512/4474/4474755.png","https://cdn-icons-png.flaticon.com/512/4474/4474764.png"),height=400)msg = gr.Textbox(label="Type your farming question",placeholder="How to control pests in wheat crop? کیڑوں سے کیسے بچا جائے؟",lines=2)with gr.Row():submit_btn = gr.Button("Submit", variant="primary")clear_btn = gr.Button("Clear")gr.Markdown("""<div class="footer"><p>Supported languages: English, Urdu, Punjabi, Sindhi, Pashto</p><p>Note: For critical decisions, always consult local agriculture experts</p></div>""")submit_btn.click(generate_response, [msg, chatbot], [chatbot])msg.submit(generate_response, [msg, chatbot], [chatbot])clear_btn.click(lambda: None, None, chatbot, queue=False)# Run the appif __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# app.pyimport gradio as grimport requestsimport os# Set your GROQ API key heregroq_api_key = os.getenv("GROQ_API_KEY") or "your-groq-api-key"def translate_text(text, target_language):headers = {"Authorization": f"Bearer {groq_api_key}","Content-Type": "application/json"}data = {"model": "llama3-8b-8192","messages": [{"role": "system", "content": f"Translate the following message to {target_language}."},{"role": "user", "content": text}]}response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)if response.status_code == 200:return response.json()['choices'][0]['message']['content'].strip()else:return f"Error: {response.status_code} - {response.text}"def handle_submission(post_text, category, language):translated = translate_text(post_text, language)return f"**Category:** {category}\n\n**Original:** {post_text}\n\n**Translated to {language}:** {translated}"with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# Community HubShare local announcements, job posts, events, or lost & found items. Your message will be automatically translated!""")with gr.Row():post_text = gr.Textbox(label="Your Message", lines=4, placeholder="Write your announcement here...")with gr.Row():category = gr.Dropdown(choices=["Announcements", "Events", "Job Postings", "Lost & Found", "Community Initiatives"],label="Select Category")language = gr.Dropdown(choices=["Urdu", "Punjabi", "Sindhi", "Pashto", "Balochi", "Saraiki"],label="Translate To")submit_btn = gr.Button("Post")output = gr.Markdown()submit_btn.click(fn=handle_submission, inputs=[post_text, category, language], outputs=output)if __name__ == "__main__":demo.launch()
app.py+43-140