File size: 6,699 Bytes
df46197
 
 
 
 
 
 
 
 
2a3bbc6
df46197
 
2a3bbc6
df46197
 
 
 
 
 
2a3bbc6
df46197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3bbc6
df46197
 
 
 
 
 
 
 
2a3bbc6
df46197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3bbc6
df46197
 
 
2a3bbc6
df46197
 
 
 
 
 
2a3bbc6
df46197
 
 
2a3bbc6
 
 
df46197
 
 
2a3bbc6
 
df46197
2a3bbc6
 
 
df46197
 
 
 
 
 
2a3bbc6
 
df46197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3bbc6
df46197
2a3bbc6
df46197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3bbc6
 
 
df46197
 
 
 
 
2a3bbc6
df46197
2a3bbc6
 
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
import os
import random
import uuid
import gradio as gr
from pydub import AudioSegment
import whisper
import asyncio
import platform

# Load Whisper model
whisper_model = whisper.load_model("tiny")

# Supported languages
lang_map = {
    "English": "en", "Hindi": "hi", "Telugu": "te", "Spanish": "es",
    "Tamil": "ta", "Gujarati": "gu", "Kannada": "kn", "Bengali": "bn",
    "Marathi": "mr", "Punjabi": "pa", "Urdu": "ur"
}

# Local food database
local_foods = {
    "vegetables": [
        {"name": "carrot", "calories": 41, "iron": 0.3, "fiber": 2.8, "vitamin_c": 6},
        {"name": "spinach", "calories": 23, "iron": 2.7, "fiber": 2.2, "vitamin_c": 28},
        {"name": "beetroot", "calories": 43, "iron": 0.8, "fiber": 2.0, "vitamin_c": 4}
    ],
    "grains": [
        {"name": "rice", "calories": 130, "iron": 1.2, "fiber": 0.4, "protein": 2.7},
        {"name": "wheat", "calories": 340, "iron": 3.2, "fiber": 12.2, "protein": 13},
        {"name": "millet", "calories": 119, "iron": 3.0, "fiber": 8.5, "protein": 3.5}
    ],
    "proteins": [
        {"name": "lentils", "calories": 116, "iron": 3.3, "fiber": 7.9, "protein": 9},
        {"name": "chicken", "calories": 239, "iron": 1.3, "fiber": 0.0, "protein": 27},
        {"name": "tofu", "calories": 76, "iron": 1.6, "fiber": 0.3, "protein": 8}
    ]
}

# Select random foods
def precompute_foods():
    return {
        "grain": random.choice(local_foods['grains']),
        "veg1": random.choice(local_foods['vegetables']),
        "veg2": random.choice(local_foods['vegetables']),
        "protein": random.choice(local_foods['proteins'])
    }

# Output templates (shortened for brevity here, use your full dictionary)
def get_output_template(lang):
    templates = {
        "English": """
🌾 Personalized Diet Plan
────────────────────────────
πŸ‘€ Age: {age}, Gender: {gender}
πŸ’Ό Occupation: {occupation}
πŸƒ Activity Level: {activity_level}
βš•οΈ Health Conditions: {health_conditions}
🍽️ Preferences: {dietary_preferences}
⚠️ Allergies: {allergies}
πŸ’° Budget: β‚Ή{budget}/day

πŸ₯£ Breakfast:
{breakfast}

πŸ› Lunch:
{lunch}

πŸ₯— Dinner:
{dinner}

πŸ“Š Summary: Balanced meals with local ingredients.
"""
    }
    return templates.get(lang, templates["English"])

# Transcription
async def transcribe_audio(audio_path, lang):
    try:
        if not audio_path or not os.path.exists(audio_path):
            return ""
        temp_wav = f"temp_{uuid.uuid4().hex}.wav"
        audio = AudioSegment.from_file(audio_path)
        audio = audio.set_frame_rate(16000).set_channels(1)
        audio.export(temp_wav, format="wav")
        result = whisper_model.transcribe(temp_wav, language=lang_map.get(lang, "en"), fp16=False)
        os.remove(temp_wav)
        return result.get("text", "").strip()
    except Exception as e:
        return f"❌ Error: {str(e)}"

# Full pipeline
async def full_pipeline(health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text,
                        age, gender, weight, height, occupation, activity, budget, lang):
    health_conditions = health_text or await transcribe_audio(health_audio, lang)
    dietary_preferences = diet_text or await transcribe_audio(diet_audio, lang)
    allergies = allergy_text or await transcribe_audio(allergy_audio, lang)
    return generate_diet(age, gender, weight, height, occupation, activity,
                         health_conditions, dietary_preferences, allergies, budget, lang)

# Diet generator
def generate_diet(age, gender, weight, height, occupation, activity_level,
                  health_conditions, dietary_preferences, allergies, budget, lang):
    foods = precompute_foods()
    grain, veg1, veg2, protein = foods['grain'], foods['veg1'], foods['veg2'], foods['protein']
    breakfast = f"{grain['name']} porridge with {veg1['name']}"
    lunch = f"{protein['name']} with {grain['name']} and {veg2['name']}"
    dinner = f"{veg1['name']} curry, {veg2['name']} salad, and {protein['name']}"
    nutrients = ["calories", "iron", "fiber", "protein", "vitamin_c"]
    nutrition = {n: round(grain.get(n, 0) * 2 + veg1.get(n, 0) + veg2.get(n, 0) * 2 + protein.get(n, 0) * 2, 1)
                 for n in nutrients}
    plan = get_output_template(lang).format(
        age=age, gender=gender, occupation=occupation, activity_level=activity_level,
        health_conditions=health_conditions or "None",
        dietary_preferences=dietary_preferences or "None",
        allergies=allergies or "None", budget=budget,
        breakfast=breakfast, lunch=lunch, dinner=dinner
    )
    nutrition_summary = f"""
🍽️ Nutritional Summary:
------------------------------
πŸ”₯ Calories: {nutrition['calories']} kcal
🩸 Iron: {nutrition['iron']} mg
🧬 Protein: {nutrition['protein']} g
🌾 Fiber: {nutrition['fiber']} g
🍊 Vitamin C: {nutrition['vitamin_c']} mg
"""
    return plan + nutrition_summary

# UI
def render_ui(default_lang="English"):
    with gr.Blocks() as demo:
        lang_sel = gr.Dropdown(label="Language", choices=list(lang_map.keys()), value=default_lang)
        age = gr.Number(label="Age", value=30, minimum=1)
        gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
        weight = gr.Number(label="Weight (kg)", value=70, minimum=1)
        height = gr.Number(label="Height (cm)", value=170, minimum=1)
        occupation = gr.Textbox(label="Occupation")
        activity = gr.Radio(["Low", "Moderate", "High"], label="Activity Level")

        with gr.Row():
            health_audio = gr.Audio(label="🎀 Speak Health Conditions", type="filepath")
            health_text = gr.Textbox(label="Or Type Health Conditions")
        with gr.Row():
            diet_audio = gr.Audio(label="🎀 Speak Dietary Preferences", type="filepath")
            diet_text = gr.Textbox(label="Or Type Dietary Preferences")
        with gr.Row():
            allergy_audio = gr.Audio(label="🎀 Speak Allergies", type="filepath")
            allergy_text = gr.Textbox(label="Or Type Allergies")

        budget = gr.Number(label="Daily Budget (β‚Ή)", value=200, minimum=0)
        output = gr.Textbox(label="Generated Diet Plan", lines=15)

        gr.Button("🎯 Generate Plan").click(
            full_pipeline,
            inputs=[health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text,
                    age, gender, weight, height, occupation, activity, budget, lang_sel],
            outputs=output
        )
    return demo

async def main():
    demo = render_ui()
    await demo.launch(server_name="0.0.0.0", server_port=7860)

if __name__ == "__main__":
    asyncio.run(main())