Spaces:
Sleeping
Sleeping
Commit ·
797572d
1
Parent(s): 0028114
done
Browse filesFiles changed (2)
- app.py+111-35
- requirements.txt+1
2 unmodified lines34567891011121314151617181920212223242 unmodified lines27282930313233343536373839404142434445464710 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181 unmodified line1201211221231241251261271281291304 unmodified lines1351361371381391401411421431444 unmodified lines1491501511521532 unmodified linesfrom PIL import Imagefrom huggingface_hub import InferenceClientimport osimport openai # Added importfrom openai.error import OpenAIError # For specific exception handling# Set page configurationst.set_page_config(page_title="Plate Mate - Your Culinary Assistant",page_icon="🍽️",layout="centered",initial_sidebar_state="expanded",)def local_css():st.markdown("""<style>/* Your existing CSS styles here */</style>""", unsafe_allow_html=True)2 unmodified lines# 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",10 unmodified linesexcept Exception as e:return f"Error generating ingredients: {e}"# **Set OpenAI API Key**openai.api_key = st.secrets["openai"] # Ensure you have this in your secrets# Main contentst.markdown('<div class="title"><h1>PlateMate - Your Culinary Assistant</h1></div>', unsafe_allow_html=True)# Add banner image with existence checkbanner_image_path = "IR_IMAGE.png"if os.path.exists(banner_image_path):st.image(banner_image_path, use_container_width=True)else:st.warning(f"Banner image '{banner_image_path}' not found.")# Sidebar for model information (hidden on small screens)with 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)# File uploaderst.subheader("Upload a food image:")uploaded_file = st.file_uploader("", type=["jpg", "png", "jpeg"])if uploaded_file is not None:# Display the uploaded imageif isinstance(uploaded_file, str): # Sample image selectedif os.path.exists(uploaded_file):image = Image.open(uploaded_file)else:st.error(f"Sample image '{uploaded_file}' not found.")image = Noneelse: # User uploaded imageimage = Image.open(uploaded_file)if image:st.image(image, caption="Uploaded Image", use_container_width=True)# Classification buttonif st.button("Classify"):with st.spinner("Classifying..."):try:# Make predictionspredictions = pipe_classification(image)if predictions:# Display only the top predictiontop_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 predictionst.subheader("📝 Ingredients")try:ingredients = get_ingredients_qwen(top_food)1 unmodified lineexcept Exception as e:st.error(f"Error generating ingredients: {e}")# **Healthier Alternatives using OpenAI API**st.subheader("💡 Healthier Alternatives")try:response = openai.ChatCompletion.create(model="gpt-4", # You can choose the model you prefermessages=[{"role": "system",4 unmodified lines"content": f"What's a healthy {top_food} recipe, and why is it healthy?"}],max_tokens=200, # Adjust as neededtemperature=0.7, # Adjust creativity level as needed)# Corrected access to 'content'result = response['choices'][0]['message']['content'].strip()st.write(result)except OpenAIError as e:4 unmodified linesst.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.")2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697982 unmodified lines10110210310410510610710810911011111211311411510 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941 unmodified line1961971981992002012022032042052064 unmodified lines2112122132142152162172182194 unmodified lines2242252262272282292 unmodified linesfrom PIL import Imagefrom huggingface_hub import InferenceClientimport osimport openaifrom openai.error import OpenAIError# 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)2 unmodified lines# 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",10 unmodified linesexcept 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.jpg","Salad": "sample_salad.jpg","Sushi": "sample_sushi.jpg"}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)1 unmodified lineexcept Exception as e:st.error(f"Error generating ingredients: {e}")# Healthier Alternativesst.subheader("💡 Healthier Alternatives")try:response = openai.ChatCompletion.create(model="gpt-4",messages=[{"role": "system",4 unmodified lines"content": f"What's a healthy {top_food} recipe, and why is it healthy?"}],max_tokens=200,temperature=0.7,)result = response['choices'][0]['message']['content'].strip()st.write(result)except OpenAIError as e:4 unmodified linesst.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.")
4 unmodified lines5674 unmodified lineshuggingface_hubgradio_clientopenai==0.28.04 unmodified lines56784 unmodified lineshuggingface_hubgradio_clientopenai==0.28.0ls
app.py+111-35
requirements.txt+1