File size: 20,048 Bytes
60ce207
2279fac
 
 
 
602c9fd
2279fac
 
60ce207
2279fac
 
60ce207
2279fac
 
 
 
 
 
 
 
 
602c9fd
2279fac
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
 
 
602c9fd
2279fac
 
 
602c9fd
2279fac
60ce207
2279fac
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
602c9fd
2279fac
 
 
602c9fd
2279fac
 
602c9fd
2279fac
 
 
 
60ce207
2279fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60ce207
2279fac
 
60ce207
2279fac
602c9fd
2279fac
 
 
 
 
 
 
602c9fd
 
2279fac
 
602c9fd
2279fac
 
 
602c9fd
2279fac
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
602c9fd
 
2279fac
602c9fd
2279fac
 
602c9fd
 
 
 
 
 
2279fac
 
 
 
 
 
 
602c9fd
 
 
2279fac
 
602c9fd
2279fac
 
 
 
 
602c9fd
 
 
 
2279fac
 
602c9fd
2279fac
602c9fd
2279fac
602c9fd
2279fac
 
602c9fd
2279fac
602c9fd
2279fac
 
 
 
 
602c9fd
 
2279fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
602c9fd
2279fac
 
 
 
 
602c9fd
 
 
 
 
2279fac
 
602c9fd
2279fac
602c9fd
2279fac
 
602c9fd
2279fac
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
602c9fd
2279fac
 
 
 
 
 
 
 
 
 
 
 
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
 
 
 
 
602c9fd
2279fac
 
 
 
602c9fd
2279fac
 
 
 
 
 
 
 
602c9fd
2279fac
 
60ce207
602c9fd
60ce207
602c9fd
 
 
 
2279fac
 
602c9fd
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import json
import os
from chicken_ai import AdvancedChickenAI

# إنشاء مثيل من نموذج الذكاء الاصطناعي
ai = AdvancedChickenAI()

# متغيرات عامة لتخزين البيانات
production_data = []
health_records = []
feed_consumption = []

def format_diagnosis_results(results):
    """تنسيق نتائج التشخيص"""
    if not results:
        return "لم يتم العثور على تشخيص مطابق للأعراض المدخلة."
    
    output = "## 🔍 نتائج التشخيص\n\n"
    
    for i, result in enumerate(results, 1):
        confidence_percentage = result.probability * 100
        confidence_emoji = "🔴" if confidence_percentage >= 80 else "🟡" if confidence_percentage >= 60 else "🟢"
        
        output += f"### {confidence_emoji} التشخيص {i}: {result.disease}\n"
        output += f"**نسبة الثقة:** {confidence_percentage:.1f}%\n"
        output += f"**الأعراض المطابقة:** {', '.join(result.symptoms_matched)}\n\n"
        
        output += f"**💊 العلاج:**\n{result.treatment}\n\n"
        output += f"**🛡️ الوقاية:**\n{result.prevention}\n\n"
        output += f"**🧼 النظافة:**\n{result.hygiene}\n\n"
        output += "---\n\n"
    
    return output

def format_nutrition_plan(plan):
    """تنسيق خطة التغذية"""
    output = f"## 🍽️ خطة التغذية المخصصة\n\n"
    output += f"**العمر:** {plan.age_weeks} أسبوع\n"
    output += f"**نوع الدجاج:** {plan.chicken_type}\n"
    output += f"**الحالة:** {plan.condition}\n\n"
    
    output += f"### 📊 المتطلبات الغذائية:\n"
    output += f"- **البروتين:** {plan.protein_percentage}%\n"
    output += f"- **الطاقة:** {plan.energy_kcal} كيلو كالوري/كجم\n"
    output += f"- **الكمية اليومية:** {plan.daily_amount} جرام\n"
    output += f"- **عدد الوجبات:** {plan.feeding_frequency} وجبات يومياً\n\n"
    
    output += f"### 💊 المكملات الغذائية:\n"
    for supplement in plan.supplements:
        output += f"- {supplement}\n"
    
    output += f"\n### 🌱 العلائق البديلة المقترحة:\n"
    for feed in plan.alternative_feeds:
        output += f"- {feed}\n"
    
    return output

def diagnose_disease_interface(symptoms):
    """واجهة تشخيص الأمراض"""
    if not symptoms.strip():
        return "يرجى إدخال الأعراض أولاً."
    
    results = ai.diagnose_disease(symptoms)
    return format_diagnosis_results(results)

def generate_nutrition_plan_interface(age, chicken_type, condition):
    """واجهة توليد خطة التغذية"""
    try:
        age_weeks = int(age)
        plan = ai.generate_nutrition_plan(age_weeks, chicken_type, condition)
        return format_nutrition_plan(plan)
    except ValueError:
        return "يرجى إدخال عمر صحيح بالأسابيع."

def answer_question_interface(question):
    """واجهة الأسئلة والأجوبة"""
    if not question.strip():
        return "يرجى كتابة سؤالك أولاً."
    
    answer = ai.answer_general_question(question)
    return f"## 💬 الإجابة:\n\n{answer}"

def get_daily_tips_interface():
    """واجهة النصائح اليومية"""
    tips = ai.get_daily_tips()
    output = "## 📝 نصائح يومية لتربية الدجاج\n\n"
    for i, tip in enumerate(tips, 1):
        output += f"{i}. {tip}\n\n"
    return output

def get_breed_info_interface(breed_name):
    """واجهة معلومات السلالات"""
    if not breed_name.strip():
        return "يرجى اختيار سلالة من القائمة."
    
    breed_info = ai.get_breed_info(breed_name)
    if not breed_info:
        return f"لم يتم العثور على معلومات عن سلالة {breed_name}."
    
    output = f"## 🐔 معلومات سلالة {breed_name}\n\n"
    output += f"**النوع:** {breed_info['type']}\n"
    
    if 'egg_production' in breed_info:
        output += f"**إنتاج البيض:** {breed_info['egg_production']}\n"
        output += f"**لون البيض:** {breed_info['egg_color']}\n"
    
    if 'growth_rate' in breed_info:
        output += f"**معدل النمو:** {breed_info['growth_rate']}\n"
    
    output += f"**الخصائص:** {breed_info['characteristics']}\n"
    output += f"**المناعة:** {breed_info['immunity']}\n"
    
    return output

def add_production_record(date, eggs_count, feed_consumed, notes):
    """إضافة سجل إنتاج"""
    global production_data
    
    try:
        record = {
            "date": date,
            "eggs": int(eggs_count) if eggs_count else 0,
            "feed": float(feed_consumed) if feed_consumed else 0.0,
            "notes": notes or ""
        }
        production_data.append(record)
        
        # حفظ البيانات في ملف
        with open('/home/ubuntu/chicken_assistant/production_data.json', 'w', encoding='utf-8') as f:
            json.dump(production_data, f, ensure_ascii=False, indent=2)
        
        return f"✅ تم إضافة السجل بنجاح!\nالتاريخ: {date}\nعدد البيض: {record['eggs']}\nالعلف المستهلك: {record['feed']} كجم"
    
    except ValueError:
        return "❌ خطأ في البيانات المدخلة. يرجى التأكد من صحة الأرقام."

def generate_production_chart():
    """إنشاء مخطط الإنتاج"""
    if not production_data:
        return None
    
    df = pd.DataFrame(production_data)
    df['date'] = pd.to_datetime(df['date'])
    df = df.sort_values('date')
    
    # مخطط إنتاج البيض
    fig = go.Figure()
    
    fig.add_trace(go.Scatter(
        x=df['date'],
        y=df['eggs'],
        mode='lines+markers',
        name='إنتاج البيض',
        line=dict(color='#FF6B6B', width=3),
        marker=dict(size=8)
    ))
    
    fig.update_layout(
        title='📈 تطور إنتاج البيض',
        xaxis_title='التاريخ',
        yaxis_title='عدد البيض',
        font=dict(family="Arial", size=12),
        plot_bgcolor='white',
        paper_bgcolor='white',
        showlegend=True
    )
    
    return fig

def generate_feed_consumption_chart():
    """إنشاء مخطط استهلاك العلف"""
    if not production_data:
        return None
    
    df = pd.DataFrame(production_data)
    df['date'] = pd.to_datetime(df['date'])
    df = df.sort_values('date')
    
    fig = go.Figure()
    
    fig.add_trace(go.Bar(
        x=df['date'],
        y=df['feed'],
        name='استهلاك العلف',
        marker_color='#4ECDC4'
    ))
    
    fig.update_layout(
        title='📊 استهلاك العلف اليومي',
        xaxis_title='التاريخ',
        yaxis_title='الكمية (كجم)',
        font=dict(family="Arial", size=12),
        plot_bgcolor='white',
        paper_bgcolor='white'
    )
    
    return fig

def load_existing_data():
    """تحميل البيانات الموجودة"""
    global production_data
    
    try:
        if os.path.exists('/home/ubuntu/chicken_assistant/production_data.json'):
            with open('/home/ubuntu/chicken_assistant/production_data.json', 'r', encoding='utf-8') as f:
                production_data = json.load(f)
    except:
        production_data = []

# تحميل البيانات عند بدء التطبيق
load_existing_data()

# إنشاء الواجهة الرئيسية
with gr.Blocks(
    title="🐔 مساعد تربية الدجاج الذكي",
    theme=gr.themes.Soft(
        primary_hue="emerald",
        secondary_hue="blue",
        neutral_hue="slate",
        font=[gr.themes.GoogleFont("Cairo"), "Arial", "sans-serif"]
    ),
    css="""
    .gradio-container {
        max-width: 1200px !important;
        margin: auto !important;
    }
    .main-header {
        text-align: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem;
        border-radius: 15px;
        margin-bottom: 2rem;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    }
    .feature-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border: 1px solid #e2e8f0;
        transition: transform 0.3s ease;
    }
    .feature-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }
    .tab-nav {
        background: #f8fafc;
        border-radius: 10px;
        padding: 0.5rem;
    }
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1rem;
        border-radius: 10px;
        text-align: center;
        margin: 0.5rem;
    }
    """
) as app:
    
    # العنوان الرئيسي
    gr.HTML("""
    <div class="main-header">
        <h1 style="font-size: 2.5rem; margin-bottom: 0.5rem; font-weight: bold;">
            🐔 مساعد تربية الدجاج الذكي
        </h1>
        <p style="font-size: 1.2rem; opacity: 0.9; margin: 0;">
            نظام متطور لإدارة ومراقبة تربية الدجاج مع ذكاء اصطناعي متقدم
        </p>
    </div>
    """)
    
    # التبويبات الرئيسية
    with gr.Tabs(elem_classes="tab-nav") as tabs:
        
        # تبويب التشخيص
        with gr.Tab("🔍 تشخيص الأمراض", elem_id="diagnosis-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 🩺 نظام التشخيص الذكي")
            gr.Markdown("أدخل الأعراض التي تلاحظها على الدجاج وسيقوم النظام بتحليلها وتقديم التشخيص المحتمل مع العلاج المناسب.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    symptoms_input = gr.Textbox(
                        label="الأعراض الملاحظة",
                        placeholder="مثال: خمول، فقدان شهية، إسهال أخضر، صعوبة في التنفس",
                        lines=3,
                        info="اكتب الأعراض مفصولة بفواصل"
                    )
                    diagnose_btn = gr.Button("🔍 تشخيص المرض", variant="primary", size="lg")
                
                with gr.Column(scale=3):
                    diagnosis_output = gr.Markdown(label="نتائج التشخيص")
            
            gr.HTML("</div>")
        
        # تبويب التغذية
        with gr.Tab("🍽️ خطط التغذية", elem_id="nutrition-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 🌾 مولد خطط التغذية المتقدم")
            gr.Markdown("احصل على خطة تغذية مخصصة تتضمن العلائق البديلة والمكملات الغذائية المناسبة.")
            
            with gr.Row():
                with gr.Column():
                    age_input = gr.Number(
                        label="العمر بالأسابيع",
                        value=10,
                        minimum=1,
                        maximum=100
                    )
                    chicken_type = gr.Dropdown(
                        label="نوع الدجاج",
                        choices=["بياض", "لاحم", "مختلط"],
                        value="بياض"
                    )
                    condition = gr.Dropdown(
                        label="الحالة الصحية",
                        choices=["صحي", "مريض", "نقاهة"],
                        value="صحي"
                    )
                    nutrition_btn = gr.Button("🍽️ إنشاء خطة التغذية", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    nutrition_output = gr.Markdown(label="خطة التغذية")
            
            gr.HTML("</div>")
        
        # تبويب الاستشارات
        with gr.Tab("💬 استشارات عامة", elem_id="consultation-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 🤖 مساعد الاستشارات الذكي")
            gr.Markdown("اطرح أي سؤال حول تربية الدجاج واحصل على إجابة مفصلة من خبير الذكاء الاصطناعي.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    question_input = gr.Textbox(
                        label="سؤالك",
                        placeholder="مثال: كيف أزيد من إنتاج البيض؟ أو ما هي أفضل طريقة لتنظيف الحظيرة؟",
                        lines=3
                    )
                    ask_btn = gr.Button("💬 اسأل الخبير", variant="primary", size="lg")
                
                with gr.Column(scale=3):
                    answer_output = gr.Markdown(label="الإجابة")
            
            gr.HTML("</div>")
        
        # تبويب السلالات
        with gr.Tab("🐔 معلومات السلالات", elem_id="breeds-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 📚 دليل سلالات الدجاج")
            gr.Markdown("تعرف على خصائص وإنتاجية السلالات المختلفة لاختيار الأنسب لمشروعك.")
            
            with gr.Row():
                with gr.Column():
                    breed_selector = gr.Dropdown(
                        label="اختر السلالة",
                        choices=list(ai.breeds_db.keys()),
                        value="ليجهورن"
                    )
                    breed_info_btn = gr.Button("📖 عرض المعلومات", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    breed_info_output = gr.Markdown(label="معلومات السلالة")
            
            gr.HTML("</div>")
        
        # تبويب النصائح
        with gr.Tab("📝 نصائح يومية", elem_id="tips-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 💡 نصائح الخبراء")
            gr.Markdown("احصل على نصائح يومية مفيدة لتحسين إدارة مزرعتك وزيادة الإنتاجية.")
            
            with gr.Row():
                with gr.Column():
                    tips_btn = gr.Button("📝 احصل على نصائح جديدة", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    tips_output = gr.Markdown(label="النصائح اليومية")
            
            gr.HTML("</div>")
        
        # تبويب لوحة التحكم
        with gr.Tab("📊 لوحة التحكم", elem_id="dashboard-tab"):
            gr.HTML("<div class='feature-card'>")
            gr.Markdown("### 📈 إدارة الإنتاج والمراقبة")
            gr.Markdown("سجل بيانات الإنتاج اليومية وراقب الأداء من خلال المخططات التفاعلية.")
            
            # قسم إدخال البيانات
            with gr.Row():
                with gr.Column():
                    gr.Markdown("#### ➕ إضافة سجل جديد")
                    record_date = gr.Textbox(label="التاريخ", value=datetime.now().strftime("%Y-%m-%d"), placeholder="YYYY-MM-DD")
                    eggs_count = gr.Number(label="عدد البيض", value=0, minimum=0)
                    feed_consumed = gr.Number(label="العلف المستهلك (كجم)", value=0.0, minimum=0, step=0.1)
                    notes = gr.Textbox(label="ملاحظات", placeholder="أي ملاحظات إضافية...")
                    add_record_btn = gr.Button("➕ إضافة السجل", variant="primary")
                    record_status = gr.Markdown()
                
                with gr.Column():
                    gr.Markdown("#### 📊 إحصائيات سريعة")
                    if production_data:
                        total_eggs = sum(record.get('eggs', 0) for record in production_data)
                        total_feed = sum(record.get('feed', 0) for record in production_data)
                        avg_eggs = total_eggs / len(production_data) if production_data else 0
                        
                        gr.HTML(f"""
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div class="metric-card">
                                <h3>🥚 إجمالي البيض</h3>
                                <h2>{total_eggs}</h2>
                            </div>
                            <div class="metric-card">
                                <h3>🌾 إجمالي العلف</h3>
                                <h2>{total_feed:.1f} كجم</h2>
                            </div>
                            <div class="metric-card">
                                <h3>📈 متوسط البيض</h3>
                                <h2>{avg_eggs:.1f}/يوم</h2>
                            </div>
                            <div class="metric-card">
                                <h3>📅 عدد السجلات</h3>
                                <h2>{len(production_data)}</h2>
                            </div>
                        </div>
                        """)
            
            # قسم المخططات
            with gr.Row():
                with gr.Column():
                    production_chart = gr.Plot(label="📈 مخطط إنتاج البيض")
                with gr.Column():
                    feed_chart = gr.Plot(label="📊 مخطط استهلاك العلف")
            
            # تحديث المخططات عند بدء التطبيق
            app.load(
                fn=lambda: (generate_production_chart(), generate_feed_consumption_chart()),
                outputs=[production_chart, feed_chart]
            )
            
            gr.HTML("</div>")
    
    # ربط الأحداث
    diagnose_btn.click(
        fn=diagnose_disease_interface,
        inputs=[symptoms_input],
        outputs=[diagnosis_output]
    )
    
    nutrition_btn.click(
        fn=generate_nutrition_plan_interface,
        inputs=[age_input, chicken_type, condition],
        outputs=[nutrition_output]
    )
    
    ask_btn.click(
        fn=answer_question_interface,
        inputs=[question_input],
        outputs=[answer_output]
    )
    
    breed_info_btn.click(
        fn=get_breed_info_interface,
        inputs=[breed_selector],
        outputs=[breed_info_output]
    )
    
    tips_btn.click(
        fn=get_daily_tips_interface,
        outputs=[tips_output]
    )
    
    add_record_btn.click(
        fn=add_production_record,
        inputs=[record_date, eggs_count, feed_consumed, notes],
        outputs=[record_status]
    ).then(
        fn=lambda: (generate_production_chart(), generate_feed_consumption_chart()),
        outputs=[production_chart, feed_chart]
    )
    
    # تحميل النصائح عند بدء التطبيق
    app.load(fn=get_daily_tips_interface, outputs=[tips_output])

# تشغيل التطبيق
if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
        quiet=False
    )