Spaces:
Sleeping
Sleeping
made change
#7
by LuckyHappyFish - opened
2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410111051061410710817181910911011111224113262728291141151163 unmodified lines1201211223940411231244312512612712812948491301315152132133545556571341351361371381391401411421435960144145146147148149150151152153154155156157158159160161162163164165166167168169636465661701711721731741751761771781796869180181182717273183184185186187188189190191757677787980811921931941951961971981992002012028384858687888920320420520620720820921021121221321421521691922172182 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 experience initial_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"]
# 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 model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, max_tokens=50 ) generated_text = completion.choices[0].message["content"].strip() generated_text = completion.choices[0]['message']['content'].strip() return generated_text except Exception as e: return f"Error generating ingredients: {e}"
# Streamlit app setupst.title("Food Image Recognition with Ingredients")openai.api_key = st.secrets["openai"]
# Add banner imagest.image("IR_IMAGE.png", caption="Food Recognition Model", use_container_width=True)st.markdown('<div class="title"><h1>PlateMate - Your Culinary Assistant</h1></div>', unsafe_allow_html=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")# Banner Image (Smaller or optional)banner_image_path = "IR_IMAGE.png"if os.path.exists(banner_image_path): # Display a smaller version of the banner col1, 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.")
# Upload imageuploaded_file = st.file_uploader("Choose a food image...", type=["jpg", "png", "jpeg"])# 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: # Display the uploaded image image = Image.open(uploaded_file) st.image(image, caption="Uploaded Image", use_container_width=True) st.write("Classifying...") if isinstance(uploaded_file, str): # Use the preset image if os.path.exists(uploaded_file): image = Image.open(uploaded_file) else: st.error(f"Sample image '{uploaded_file}' not found.") image = None else: image = Image.open(uploaded_file)
# Make predictions predictions = pipe_classification(image) if image: st.image(image, caption="Selected Image", use_container_width=True)
# Display only the top prediction top_food = predictions[0]['label'] st.header(f"Food: {top_food}") 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 and display ingredients for the top prediction st.subheader("Ingredients") try: ingredients = get_ingredients_qwen(top_food) st.write(ingredients) except Exception as e: st.error(f"Error generating ingredients: {e}") # Generate ingredients st.subheader("📝 Ingredients") try: ingredients = get_ingredients_qwen(top_food) st.write(ingredients) except Exception as e: st.error(f"Error generating ingredients: {e}")
# Healthier Alternatives st.subheader("💡 Healthier Alternatives") try: 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}") # ONLY THIS PART CHANGED: # Use the RAG calling method instead of the OpenAI function client_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}")
# Footerst.sidebar.markdown("Developed by Muhammad Hassan Butt.")else: st.info("Please select or upload an image to get started.")app.py+176-50