Spaces:
Sleeping
Sleeping
made change
#7
by LuckyHappyFish - opened
2 unmodified lines345678910111213141516171819202122232425262728293031323 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091922 unmodified linesfrom PIL import Imagefrom huggingface_hub import InferenceClientimport osfrom gradio_client import Client# Hugging Face API keyAPI_KEY = st.secrets["HF_API_KEY"]# Initialize the Hugging Face Inference Clientclient = InferenceClient(api_key=API_KEY)# Load the image classification pipeline@st.cache_resourcedef load_image_classification_pipeline():"""Load the image classification pipeline using a pretrained model."""return pipeline("image-classification", model="Shresthadev403/food-image-classification")pipe_classification = load_image_classification_pipeline()# Function to generate ingredients using Hugging Face Inference Clientdef get_ingredients_qwen(food_name):"""Generate a list of ingredients for the given food item using Qwen NLP model.Returns a clean, comma-separated list of ingredients."""messages = [{"role": "user",3 unmodified lines]try:completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct",messages=messages,max_tokens=50)generated_text = completion.choices[0].message["content"].strip()return generated_textexcept Exception as e:return f"Error generating ingredients: {e}"# Streamlit app setupst.title("Food Image Recognition with Ingredients")# Add banner imagest.image("IR_IMAGE.png", caption="Food Recognition Model", use_container_width=True)# Sidebar for model informationst.sidebar.title("Model Information")st.sidebar.write("**Image Classification Model**: Shresthadev403/food-image-classification")st.sidebar.write("**LLM for Ingredients**: Qwen/Qwen2.5-Coder-32B-Instruct")# Upload imageuploaded_file = st.file_uploader("Choose a food image...", type=["jpg", "png", "jpeg"])if uploaded_file is not None:# Display the uploaded imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_container_width=True)st.write("Classifying...")# Make predictionspredictions = pipe_classification(image)# Display only the top predictiontop_food = predictions[0]['label']st.header(f"Food: {top_food}")# Generate and display ingredients for the top predictionst.subheader("Ingredients")try:ingredients = get_ingredients_qwen(top_food)st.write(ingredients)except Exception as e:st.error(f"Error generating ingredients: {e}")st.subheader("Healthier alternatives:")try:client = Client("https://66cd04274e7fd11327.gradio.live/")result = client.predict(query=f"What's a healthy {top_food} recipe, and why is it healthy?", api_name="/get_response")st.write(result)except Exception as e:st.error(f"Unable to contact RAG: {e}")# Footerst.sidebar.markdown("Developed by Muhammad Hassan Butt.")2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151163 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182 unmodified linesfrom PIL import Imagefrom huggingface_hub import InferenceClientimport osimport openaifrom openai.error import OpenAIErrorfrom gradio_client import Client# Set page configurationst.set_page_config(page_title="Plate Mate - Your Culinary Assistant",page_icon="🍽️",layout="centered", # center content for better mobile experienceinitial_sidebar_state="collapsed",)def local_css():st.markdown("""<style>/* General resets */body, html {margin: 0;padding: 0;font-family: "Helvetica Neue", Arial, sans-serif;background-color: #f9f9f9;}/* Container and spacing */.css-1aumxhk, .css-keje6w, .css-18e3th9, .css-12oz5g7 {padding-left: 0 !important;padding-right: 0 !important;}/* Title styling */.title h1 {text-align: center;font-size: 2.5em;margin-bottom: 0.5em;color: #333;}/* Subheader styling */h2, h3, h4, h5, h6 {color: #555;margin-bottom: 0.5em;}/* Adjust image styling */img {max-width: 100%;height: auto;border-radius: 8px;}/* On mobile, reduce font sizes and margins */@media (max-width: 600px) {.title h1 {font-size: 1.8em;}h2, h3, h4 {font-size: 1em;}.stButton button {width: 100%;}}/* Sidebar adjustments */[data-testid="stSidebar"] {width: 250px;background: #fff;}/* Preset images container */.preset-container {display: flex;flex-wrap: wrap;gap: 10px;justify-content: center;margin: 1em 0;}.preset-container img {width: 80px;height: 80px;object-fit: cover;cursor: pointer;border: 2px solid transparent;}.preset-container img:hover {border: 2px solid #007BFF;}</style>""", unsafe_allow_html=True)local_css() # Apply the CSS# Hugging Face API keyAPI_KEY = st.secrets["HF_API_KEY"]client = InferenceClient(api_key=API_KEY)@st.cache_resourcedef load_image_classification_pipeline():return pipeline("image-classification", model="Shresthadev403/food-image-classification")pipe_classification = load_image_classification_pipeline()def get_ingredients_qwen(food_name):messages = [{"role": "user",3 unmodified lines]try:completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, max_tokens=50)generated_text = completion.choices[0]['message']['content'].strip()return generated_textexcept Exception as e:return f"Error generating ingredients: {e}"openai.api_key = st.secrets["openai"]st.markdown('<div class="title"><h1>PlateMate - Your Culinary Assistant</h1></div>', unsafe_allow_html=True)# Banner Image (Smaller or optional)banner_image_path = "IR_IMAGE.png"if os.path.exists(banner_image_path):# Display a smaller version of the bannercol1, col2, col3 = st.columns([1,3,1])with col2:st.image(banner_image_path, use_container_width=True)else:st.warning(f"Banner image '{banner_image_path}' not found.")# Sidebar Infowith st.sidebar:st.title("Model Information")st.write("**Image Classification Model:**")st.write("Shresthadev403/food-image-classification")st.write("**LLM for Ingredients:**")st.write("Qwen/Qwen2.5-Coder-32B-Instruct")st.markdown("---")st.markdown("<p style='text-align: center;'>Developed by Muhammad Hassan Butt.</p>", unsafe_allow_html=True)st.subheader("Upload a food image:")# Preset Imagespreset_images = {"Pizza": "sample_pizza.png","Salad": "sample_salad.png","Sushi": "sample_sushi.png"}selected_preset = st.selectbox("Or choose a preset sample image:", ["None"] + list(preset_images.keys()))if selected_preset != "None":uploaded_file = preset_images[selected_preset]else:uploaded_file = st.file_uploader("", type=["jpg", "png", "jpeg"])if uploaded_file is not None:if isinstance(uploaded_file, str):# Use the preset imageif os.path.exists(uploaded_file):image = Image.open(uploaded_file)else:st.error(f"Sample image '{uploaded_file}' not found.")image = Noneelse:image = Image.open(uploaded_file)if image:st.image(image, caption="Selected Image", use_container_width=True)if st.button("Classify"):with st.spinner("Classifying..."):try:predictions = pipe_classification(image)if predictions:top_food = predictions[0]['label']confidence = predictions[0]['score']st.header(f"🍽️ Food: {top_food} ({confidence*100:.2f}% confidence)")# Generate ingredientsst.subheader("📝 Ingredients")try:ingredients = get_ingredients_qwen(top_food)st.write(ingredients)except Exception as e:st.error(f"Error generating ingredients: {e}")# Healthier Alternativesst.subheader("💡 Healthier Alternatives")try:# ONLY THIS PART CHANGED:# Use the RAG calling method instead of the OpenAI functionclient_rag = Client("https://66cd04274e7fd11327.gradio.live/")result = client_rag.predict(query=f"What's a healthy {top_food} recipe, and why is it healthy?", api_name="/get_response")st.write(result)except OpenAIError as e:st.error(f"OpenAI API error: {e}")except Exception as e:st.error(f"Unable to generate healthier alternatives: {e}")else:st.error("No predictions returned from the classification model.")except Exception as e:st.error(f"Error during classification: {e}")else:st.info("Please select or upload an image to get started.")
app.py+176-50