File size: 2,244 Bytes
05f1709
901777e
05f1709
 
 
 
 
789f39d
05f1709
789f39d
05f1709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901777e
05f1709
 
 
 
 
 
 
 
 
 
 
 
 
6edbce0
901777e
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
# app.py
import gradio as gr
import spaces
from transformers import pipeline
import os
from PyPDF2 import PdfReader
from dotenv import load_dotenv

load_dotenv()

@spaces.GPU
class ChatBot:
    def __init__(self):
        self.llm = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct-v0.1", token=os.getenv("HF_TOKEN"))
        self.context = ""

    def read_meal_plans(self, folder="meal_plans"):
        text = ""
        for file in os.listdir(folder):
            if file.endswith(".pdf"):
                reader = PdfReader(os.path.join(folder, file))
                for page in reader.pages:
                    text += page.extract_text() + "\n"
        return text

    def reply(self, message, history, preferences):
        diet, goal, allergens = preferences
        if not self.context:
            mealplan_text = self.read_meal_plans()
            self.context = f"Meal Plans: {mealplan_text}\nUser Preferences: Diet={diet}, Goal={goal}, Allergens={allergens}"

        prompt = f"{self.context}\nUser: {message}\nAI:"
        response = self.llm(prompt, max_new_tokens=100, do_sample=True, temperature=0.7)[0]['generated_text'].split("AI:")[-1].strip()
        return response

bot = ChatBot()

def chat(message, history, diet, goal, allergens):
    return bot.reply(message, history, (diet, goal, allergens))

diet_choices = ["Vegetarian", "Vegan", "Keto", "Paleo", "No Preference"]
goal_choices = ["Weight Loss", "Muscle Gain", "Maintenance"]
allergen_choices = ["Nuts", "Dairy", "Gluten", "Soy", "Eggs"]

with gr.Blocks() as demo:
    gr.Markdown("# 🥗 AI Meal Plan Assistant")
    with gr.Row():
        diet = gr.Dropdown(diet_choices, label="Diet Type")
        goal = gr.Dropdown(goal_choices, label="Goal")
        allergens = gr.CheckboxGroup(allergen_choices, label="Allergies")
    chatbot = gr.Chatbot()
    msg = gr.Textbox(placeholder="Ask me for meal ideas...", label="Message")
    send = gr.Button("Send")

    def user_input(message, chat_history):
        response = chat(message, chat_history, diet.value, goal.value, allergens.value)
        chat_history.append((message, response))
        return chat_history, ""

    send.click(user_input, [msg, chatbot], [chatbot, msg])

demo.launch()