CoolFace
Apppublic

Sustainable-Meal-Assistant/TreeBot

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py167 linesDownload Raw Back to root
1import gradio as gr2from sentence_transformers import SentenceTransformer, util3import webbrowser4import openai5import os6 7os.environ["TOKENIZERS_PARALLELISM"] = "false"8 9# Initialize paths and model identifiers for easy configuration and maintenance10filename = "output_topic_details.txt"  # Path to the file storing recipe-specific details11retrieval_model_name = 'output/sentence-transformer-finetuned/'12 13openai.api_key = os.environ["OPENAI_API_KEY"]14 15system_message = "You are a meal chatbot specialized in providing information on meals, recipes, and ingredients."16# Initial system message to set the behavior of the assistant17messages = [{"role": "system", "content": system_message}]18 19# Attempt to load the necessary models and provide feedback on success or failure20try:21    retrieval_model = SentenceTransformer(retrieval_model_name)22    print("Models loaded successfully.")23except Exception as e:24    print(f"Failed to load models: {e}")25 26def load_and_preprocess_text(filename):27    """28    Load and preprocess text from a file, removing empty lines and stripping whitespace.29    """30    try:31        with open(filename, 'r', encoding='utf-8') as file:32            segments = [line.strip() for line in file if line.strip()]33        print("Text loaded and preprocessed successfully.")34        return segments35    except Exception as e:36        print(f"Failed to load or preprocess text: {e}")37        return []38 39segments = load_and_preprocess_text(filename)40 41def find_relevant_segment(user_query, segments):42    """43    Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.44    This version finds the best match based on the content of the query.45    """46    try:47        # Lowercase the query for better matching48        lower_query = user_query.lower()49        50        # Encode the query and the segments51        query_embedding = retrieval_model.encode(lower_query)52        segment_embeddings = retrieval_model.encode(segments)53        54        # Compute cosine similarities between the query and the segments55        similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]56        57        # Find the index of the most similar segment58        best_idx = similarities.argmax()59        60        # Return the most relevant segment61        return segments[best_idx]62    except Exception as e:63        print(f"Error in finding relevant segment: {e}")64        return ""65 66def generate_response(user_query, relevant_segment):67    """68    Generate a response emphasizing the bot's capability in providing sustainable recipe information.69    """70    try:71        user_message = f"Here's the information on the recipe: {relevant_segment}"72 73        # Append user's message to messages list74        messages.append({"role": "user", "content": user_message})75        76        response = openai.ChatCompletion.create(77            model="gpt-3.5-turbo",78            messages=messages,79            max_tokens=500,80            temperature=0.2,81            top_p=1,82            frequency_penalty=0,83            presence_penalty=084        )85        86        # Extract the response text87        output_text = response['choices'][0]['message']['content'].strip()88        89        # Append assistant's message to messages list for context90        messages.append({"role": "assistant", "content": output_text})91        92        return output_text93        94    except Exception as e:95        print(f"Error in generating response: {e}")96        return f"Error in generating response: {e}"97 98def query_model(question):99    """100    Process a question, find relevant information, and generate a response.101    """102    if question == "":103        return "Welcome to SustAIBot! Ask me anything about recipes with mushrooms, carrots, kale, and tofu as the main ingredients."104    relevant_segment = find_relevant_segment(question, segments)105    if not relevant_segment:106        return "Could not find specific information. Please refine your question."107    response = generate_response(question, relevant_segment)108    return response109 110# Define the welcome message and specific topics the chatbot can provide information about111welcome_message = """112# Welcome to SustAIna-bot!113 114## Your AI-driven assistant for meat, veggie, and plant-based sustainable recipe-related queries. Created by Cecilia, Halle, and Elena of the Kode With Klossy Camp. 115"""116 117topics = """118### Feel Free to ask me anything from the topics below!119- Mushroom Recipes120- Carrot Recipes121- Kale Recipes122- Tofu Recipes123- Lentils Recipes124- Chickpea Reicpes125- Fish Recipes126- Chicken Recipes127- Beef Recipes128- Pork Recipes129"""130def display_image():131    return "https://huggingface.co/spaces/Sustainable-Meal-Assistant/TreeBot/resolve/main/sustainable-food-principles%C2%A9iStock-552584505.jpg"132 133theme = gr.themes.Base().set(134background_fill_primary='#C1D0B5',  # Light green background135    background_fill_primary_dark='#737373',  # Dark green background136    background_fill_secondary='#FFF8DE',  # Light off white background137    background_fill_secondary_dark='#99A98F',  # Dark green background138    border_color_accent='#FFF8DE',  # Accent border color139    border_color_accent_dark='#3C8181',  # Dark accent border color140    border_color_accent_subdued='#FF8A65',  # Subdued accent border color141    border_color_primary='#737373',  # Primary border color142    block_border_color='##3C8181',  # Block border color143    button_primary_background_fill='#FF9800',  # Primary button background color144    button_primary_background_fill_dark='#EF6C00'  # Dark primary button background color145 146)147 148 149    150# Setup the Gradio Blocks interface with custom layout components151with gr.Blocks(theme=theme) as demo:152    gr.Image(display_image(), show_label = False, show_share_button = False, show_download_button = False)153    gr.Markdown(welcome_message)  # Display the formatted welcome message154    with gr.Row():155        with gr.Column():156            gr.Markdown(topics)  # Show the topics on the left side157    with gr.Row():158        with gr.Column():159            question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")160            answer = gr.Textbox(label="SustainAIBot Response", placeholder="SustainAIBot will respond here...", interactive=False, lines=10)161            submit_button = gr.Button("Submit")162            submit_button.click(fn=query_model, inputs=question, outputs=answer)163    164 165# Launch the Gradio app to allow user interaction166demo.launch(share=True)167