Spaces:
Sleeping
Sleeping
Commit ·
f78eb01
1
Parent(s): 6fdb57d
ds
Browse filesFiles changed (2)
- app.py+79-51
- requirements.txt+1-1
3 unmodified lines4567897 unmodified lines1718192021222328 unmodified lines525354555657585960616263646566676869705 unmodified lines767778798081828384858687883 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421433 unmodified linesfrom huggingface_hub import InferenceClientimport osimport openai # Added import# Set page configurationst.set_page_config(7 unmodified linesst.markdown("""<style>/* [Your existing CSS styles here] */</style>""", unsafe_allow_html=True)28 unmodified linescompletion = 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}"# **Set OpenAI API Key**openai.api_key = st.secrets["openai"] # Ensure you have this in your secrets# Main contentst.markdown('<div class="title"><h1>DelishAI - Your Culinary Assistant</h1></div>', unsafe_allow_html=True)# Add banner imagest.image("IR_IMAGE.png", use_container_width=True)# Sidebar for model information (hidden on small screens)with st.sidebar:5 unmodified linesst.markdown("---")st.markdown("<p style='text-align: center;'>Developed by Muhammad Hassan Butt.</p>", unsafe_allow_html=True)# Assuming `sample_images` is defined somewhere in your codesample_images = {"Pizza": "path_to_pizza_image.jpg","Salad": "path_to_salad_image.jpg",# Add more sample images as needed}cols = st.columns(len(sample_images))for idx, (name, file_path) in enumerate(sample_images.items()):with cols[idx]:3 unmodified lines# File uploaderst.subheader("Upload a food image:")uploaded_file = st.file_uploader("", type=["jpg", "png", "jpeg"])if 'uploaded_file' in locals() and uploaded_file is not None:# Display the uploaded imageif isinstance(uploaded_file, str): # Sample image selectedimage = Image.open(uploaded_file)else: # User uploaded imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_container_width=True)# Classification buttonif st.button("Classify"):with st.spinner("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}")# **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","content": "You are a helpful assistant specializing in providing healthy alternatives to various dishes."},{"role": "user","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)result = response.choices[0].message.content.strip()st.write(result)except Exception as e:st.error(f"Unable to generate healthier alternatives: {e}")else:st.info("Please select or upload an image to get started.")3 unmodified lines456789107 unmodified lines1819202122232428 unmodified lines53545556575859606162636465666768697071727374755 unmodified lines818283848586878889909192939495969798993 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701713 unmodified linesfrom huggingface_hub import InferenceClientimport osimport openai # Added importfrom openai.error import OpenAIError # For specific exception handling# Set page configurationst.set_page_config(7 unmodified linesst.markdown("""<style>/* Your existing CSS styles here */</style>""", unsafe_allow_html=True)28 unmodified linescompletion = 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}"# **Set OpenAI API Key**openai.api_key = st.secrets["openai"] # Ensure you have this in your secrets# Main contentst.markdown('<div class="title"><h1>DelishAI - 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:5 unmodified linesst.markdown("---")st.markdown("<p style='text-align: center;'>Developed by Muhammad Hassan Butt.</p>", unsafe_allow_html=True)# Define sample images with correct pathssample_images = {"Pizza": "sample_images/pizza.jpg","Salad": "sample_images/salad.jpg",# Add more sample images as needed}# Ensure sample images existfor name, path in sample_images.items():if not os.path.exists(path):st.warning(f"Sample image '{path}' for '{name}' not found.")# Create columns for sample image buttonscols = st.columns(len(sample_images))for idx, (name, file_path) in enumerate(sample_images.items()):with cols[idx]:3 unmodified lines# 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)st.write(ingredients)except 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","content": "You are a helpful assistant specializing in providing healthy alternatives to various dishes."},{"role": "user","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: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.")
3 unmodified lines45673 unmodified linesPillowhuggingface_hubgradio_clientopenai>=1.0.03 unmodified lines45673 unmodified linesPillowhuggingface_hubgradio_clientopenai==0.28.0
app.py+79-51
requirements.txt+1-1