Spaces:
Build error
Build error
Update src/streamlit_app.py
Browse files123456789102 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371384 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023118 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423436 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337437537620 unmodified lines3973983994004014024034044054064074084094104114124134144152 unmodified lines418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861import streamlit as stimport pandas as pdimport jsonimport uuidfrom datetime import datetimefrom collections import Counterimport base64# --- Page Configuration ---st.set_page_config(2 unmodified lineslayout="wide")# --- In-Memory Storage Functions ---def generate_recipe_id():"""Generate a unique ID for each recipe"""return str(uuid.uuid4())[:8]def save_image_to_memory(image_file, recipe_id):"""Save uploaded image to session state as base64"""if image_file is not None:try:# Convert image to base64 for storage in memoryimage_bytes = image_file.getvalue()image_b64 = base64.b64encode(image_bytes).decode()file_extension = image_file.name.split('.')[-1].lower()# Store in session stateif 'recipe_images' not in st.session_state:st.session_state['recipe_images'] = {}image_key = f"{recipe_id}.{file_extension}"st.session_state['recipe_images'][image_key] = {'data': image_b64,'type': image_file.type}return image_keyexcept Exception as e:st.error(f"Error saving image: {e}")return Nonereturn Nonedef load_image_from_memory(image_filename):"""Load image from session state"""if image_filename and 'recipe_images' in st.session_state:try:if image_filename in st.session_state['recipe_images']:image_data = st.session_state['recipe_images'][image_filename]return base64.b64decode(image_data['data'])except Exception as e:st.error(f"Error loading image: {e}")return Nonedef save_recipe_to_memory(recipe_data):"""Save recipe to session state"""try:if 'recipes' not in st.session_state:st.session_state['recipes'] = []# Add to the beginning of the list (newest first)st.session_state['recipes'].insert(0, recipe_data)return Trueexcept Exception as e:st.error(f"Error saving recipe: {e}")return Falsedef load_all_recipes_from_memory():"""Load all recipes from session state"""if 'recipes' not in st.session_state:st.session_state['recipes'] = []return st.session_state['recipes']def delete_recipe_from_memory(recipe_id):"""Delete a recipe and its associated image from memory"""try:# Delete recipeif 'recipes' in st.session_state:st.session_state['recipes'] = [r for r in st.session_state['recipes']if r.get('id') != recipe_id]# Delete associated imageif 'recipe_images' in st.session_state:keys_to_delete = [key for key in st.session_state['recipe_images'].keys()if key.startswith(recipe_id)]for key in keys_to_delete:del st.session_state['recipe_images'][key]return Trueexcept Exception as e:st.error(f"Error deleting recipe: {e}")return Falsedef get_recipe_stats():"""Get statistics about stored recipes"""try:recipes = load_all_recipes_from_memory()images = st.session_state.get('recipe_images', {})# Calculate approximate storage sizestorage_size = 0for recipe in recipes:storage_size += len(json.dumps(recipe, ensure_ascii=False).encode('utf-8'))for image_data in images.values():storage_size += len(image_data['data']) * 3 // 4 # Approximate decoded sizereturn {'total_recipes': len(recipes),'total_images': len(images),'storage_size': storage_size}except:return {'total_recipes': 0, 'total_images': 0, 'storage_size': 0}# --- Language and Text ---TEXT = {"en": {"title": "Ruchi Chudu","subtitle": "A Community Cookbook to Preserve Telugu Cuisine","language_select": "Choose Language","sidebar_header": "Contribute Your Recipe!","tab_submit": "📝 Submit Your Recipe","tab_gallery": "🍲 Community Gallery","tab_analytics": "📊 Recipe Analytics","tab_manage": "⚙️ Manage Recipes","form_header": "Tell us about your dish","dish_name": "Dish Name","your_name": "Your Name","district": "Your District","select_district": "--- Select a District ---","recipe_type": "Recipe Type (e.g., Curry, Pickle, Snack)",4 unmodified lines"submit_button": "Submit Recipe","success_message": "Thank you! Your recipe has been submitted successfully.","gallery_header": "Explore Recipes from the Community","gallery_empty": "No recipes submitted yet. Be the first to share!","submitted_by": "Submitted by","from_district": "from","submitted_on": "Submitted on","recipe_id": "Recipe ID","story_title": "📖 The Story","ingredients_title": "🌶️ Ingredients","instructions_title": "✍️ Instructions","tags_title": "AI-Generated Tags","error_dish_name": "Please enter a dish name before submitting.","search_placeholder": "Search recipes...","filter_by_district": "Filter by District","filter_by_type": "Filter by Recipe Type","all_districts": "All Districts","all_types": "All Recipe Types","total_recipes": "Total Recipes","total_images": "Total Images","storage_size": "Storage Used","top_districts": "Top Contributing Districts","popular_types": "Popular Recipe Types","recent_recipes": "Recent Submissions","clear_filters": "Clear All Filters","export_recipes": "Export All Recipes","manage_header": "Recipe Management","delete_recipe": "Delete Recipe","confirm_delete": "Are you sure you want to delete this recipe?","recipe_deleted": "Recipe deleted successfully!","backup_data": "Download All Data","backup_created": "Data downloaded successfully!","memory_storage_note": "Note: Data is stored in memory and will be lost when the session ends."},"te": {"title": "రుచి చూడు","subtitle": "మన తెలుగు వంటల సంస్కృతిని కాపాడుదాం","language_select": "భాషను ఎంచుకోండి","sidebar_header": "మీ వంటకాన్ని పంపండి!","tab_submit": "📝 మీ వంటకాన్ని పంపండి","tab_gallery": "🍲 కమ్యూనిటీ గ్యాలరీ","tab_analytics": "📊 వంటకాల విశ్లేషణ","tab_manage": "⚙️ ��ంటకాలను నిర్వహించండి","form_header": "మీ వంటకం గురించి చెప్పండి","dish_name": "వంటకం పేరు","your_name": "మీ పేరు","district": "మీ జిల్లా","select_district": "--- జిల్లాను ఎంచుకోండి ---","recipe_type": "వంటకం రకం (ఉదా. కూర, పచ్చడి, స్నాక్)","ingredients": "కావలసినవి (ఒకదానికి ఒకటి)","instructions": "తయారీ విధానం","story": "ఈ వంటతో మీ కథ (మీ జ్ఞాపకాలు, కుటుంబ సంప్రదాయాలు మొదలైనవి)","image_upload": "వంటకం ఫోటోను అప్లోడ్ చేయండి (ఐచ్ఛికం)","submit_button": "వంటకాన్ని పంపండి","success_message": "ధన్యవాదాలు! మీ వంటకం విజయవంతంగా సమర్పించబడింది.","gallery_header": "కమ్యూనిటీ నుండి వంటకాలను అన్వేషించండి","gallery_empty": "ఇంకా వంటకాలు సమర్పించబడలేదు. పంచుకున్న మొదటి వ్యక్తి మీరే అవ్వండి!","submitted_by": "సమర్పించిన వారు","from_district": "నుండి","submitted_on": "సమర్పించిన తేదీ","recipe_id": "వంటకం ID","story_title": "📖 కథ","ingredients_title": "🌶️ కావలసినవి","instructions_title": "✍️ తయారీ విధానం","tags_title": "AI ద్వారా రూపొందించబడిన ట్యాగ్లు","error_dish_name": "సమర్పించే ముందు దయచేసి వంటకం పేరును నమోదు చేయండి.","search_placeholder": "వంటకాలను వెతకండి...","filter_by_district": "జిల్లా ద్వారా ఫిల్టర్ చేయండి","filter_by_type": "వంటకం రకం ద్వారా ఫిల్టర్ చేయండి","all_districts": "అన్ని జిల్లాలు","all_types": "అన్ని వంటకాల రకాలు","total_recipes": "మొత్తం వంటకాలు","total_images": "మొత్తం చిత్రాలు","storage_size": "వాడిన స్టోరేజ్","top_districts": "అధిక సహకారం అందించిన జిల్లాలు","popular_types": "ప్రాచుర్యం పొందిన వంటకాల రకాలు","recent_recipes": "ఇటీవలి సమర్పణలు","clear_filters": "అన్ని ఫిల్టర్లను క్లియర్ చేయండి","export_recipes": "అన్ని వంటకాలను ఎగుమతి చేయండి","manage_header": "వంటకాల నిర్వహణ","delete_recipe": "వంటకాన్ని తొలగించండి","confirm_delete": "మీరు ఖచ్చితంగా ఈ వంటకాన్ని తొలగించాలనుకుంటున్నారా?","recipe_deleted": "వంటకం విజయవంతంగా తొలగించబడింది!","backup_data": "అన్ని డేటాను డౌన్లోడ్ చేయండి","backup_created": "డేటా విజయవంతంగా డౌన్లోడ్ చేయబడింది!","memory_storage_note": "గమనిక: డేటా మెమరీలో నిల్వ చేయబడుతుంది మరియు సెషన్ ముగిసినప్పుడు పోతుంది."}}18 unmodified linesif 'language' not in st.session_state:st.session_state['language'] = 'en'if 'recipes' not in st.session_state:st.session_state['recipes'] = []if 'recipe_images' not in st.session_state:st.session_state['recipe_images'] = {}# --- Helper Functions ---def get_text(key):"""Fetches text from the dictionary based on the selected language."""return TEXT[st.session_state['language']][key]def simulate_ai_tagging(story, ingredients):"""Simulate AI tagging based on content analysis"""tags = set()text_to_scan = (story + " " + ingredients).lower()keyword_map = {"festival": ["sankranti", "ugadi", "dasara", "diwali", "vinayaka chaviti"],"spicy": ["chilli", "karam", "mirapa", "pepper", "guntur"],"healthy": ["millet", "ragi", "jowar", "vegetable", "leafy", "greens"],"quick": ["15 min", "20 min", "quick", "easy", "tvaraga"],"traditional": ["grandma", "ammamma", "nanamma", "traditional", "sampradayam"],"summer": ["mango", "summer", "cool", "curd", "perugu"],"winter": ["winter", "warm", "hot", "sheeta"],"vegetarian": ["vegetable", "veg", "sabzi", "kura"],"non-vegetarian": ["chicken", "mutton", "fish", "egg", "kodi", "meka"]}for tag, keywords in keyword_map.items():if any(keyword in text_to_scan for keyword in keywords):tags.add(tag.capitalize())if not tags:tags.add("Community Recipe")return list(tags)def filter_recipes(recipes, search_term="", district_filter="", type_filter=""):"""Filter recipes based on search and filter criteria"""filtered = recipesif search_term:filtered = [r for r in filtered ifsearch_term.lower() in r['dish_name'].lower() orsearch_term.lower() in r.get('your_name', '').lower() orsearch_term.lower() in r.get('ingredients', '').lower()]if district_filter and district_filter != get_text('all_districts'):filtered = [r for r in filtered if r.get('district') == district_filter]if type_filter and type_filter != get_text('all_types'):filtered = [r for r in filtered if r.get('recipe_type') == type_filter]return filtereddef export_recipes_to_csv(recipes):"""Export recipes to CSV format"""if not recipes:return Noneexport_data = []for recipe in recipes:export_data.append({'Recipe ID': recipe.get('id', ''),'Dish Name': recipe['dish_name'],'Submitted By': recipe.get('your_name', ''),'District': recipe.get('district', ''),'Recipe Type': recipe.get('recipe_type', ''),'Ingredients': recipe.get('ingredients', ''),'Instructions': recipe.get('instructions', ''),'Story': recipe.get('story', ''),'Tags': ', '.join(recipe.get('tags', [])),'Submitted Date': recipe.get('submitted_date', ''),'Has Image': 'Yes' if recipe.get('image_filename') else 'No'})return pd.DataFrame(export_data)def format_storage_size(size_bytes):"""Convert bytes to human readable format"""for unit in ['B', 'KB', 'MB', 'GB']:if size_bytes < 1024.0:return f"{size_bytes:.1f} {unit}"size_bytes /= 1024.0return f"{size_bytes:.1f} TB"# --- Sidebar ---with st.sidebar:st.title(f"🍲 {get_text('title')}")st.markdown(get_text('subtitle'))st.markdown("---")# Language selector6 unmodified linesst.session_state['language'] = 'te' if lang_choice == 'తెలుగు' else 'en'st.info(get_text('sidebar_header'))# Storage statsstats = get_recipe_stats()st.metric(get_text('total_recipes'), stats['total_recipes'])st.metric(get_text('total_images'), stats['total_images'])st.metric(get_text('storage_size'), format_storage_size(stats['storage_size']))# Memory storage notest.warning(get_text('memory_storage_note'))# --- Main App Layout ---st.title(get_text('title'))tab_submit, tab_gallery, tab_analytics, tab_manage = st.tabs([get_text('tab_submit'),get_text('tab_gallery'),get_text('tab_analytics'),get_text('tab_manage')])# --- Submission Form Tab ---with tab_submit:st.header(get_text('form_header'))20 unmodified linesif submitted:if not dish_name:st.error(get_text('error_dish_name'))else:# Generate unique ID for this reciperecipe_id = generate_recipe_id()# Save image if providedimage_filename = save_image_to_memory(image_file, recipe_id)# Generate AI tagsai_tags = simulate_ai_tagging(story, ingredients)# Create new recipe with unique IDnew_recipe = {"id": recipe_id,"dish_name": dish_name,"your_name": your_name,2 unmodified lines"ingredients": ingredients,"instructions": instructions,"story": story,"image_filename": image_filename,"tags": ai_tags,"submitted_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}# Save recipe to memoryif save_recipe_to_memory(new_recipe):st.success(f"{get_text('success_message')} (ID: {recipe_id})")st.balloons()# Show recipe detailswith st.expander("Recipe Details", expanded=True):st.write(f"**{get_text('recipe_id')}:** `{recipe_id}`")st.write(f"**Storage:** In-memory (session-based)")if image_filename:st.write(f"**Image:** Stored as {image_filename}")else:st.error("Failed to save recipe. Please try again.")# --- Community Gallery Tab ---with tab_gallery:st.header(get_text('gallery_header'))# Filters and searchcol1, col2, col3, col4 = st.columns([2, 1, 1, 1])with col1:search_term = st.text_input(label="",placeholder=get_text('search_placeholder'),key="search_recipes")with col2:district_options = [get_text('all_districts')] + DISTRICTSdistrict_filter = st.selectbox(get_text('filter_by_district'),district_options,key="district_filter")with col3:type_options = [get_text('all_types')] + RECIPE_TYPEStype_filter = st.selectbox(get_text('filter_by_type'),type_options,key="type_filter")with col4:if st.button(get_text('clear_filters')):st.session_state.search_recipes = ""st.session_state.district_filter = get_text('all_districts')st.session_state.type_filter = get_text('all_types')st.rerun()st.markdown("---")# Filter recipesrecipes = load_all_recipes_from_memory()filtered_recipes = filter_recipes(recipes,search_term,district_filter,type_filter)if not filtered_recipes:if not recipes:st.info(get_text('gallery_empty'))else:st.info("No recipes match your search criteria. Try adjusting your filters.")else:st.write(f"**{len(filtered_recipes)}** recipes found")# Display recipesfor recipe in filtered_recipes:with st.container():st.markdown("""<style>.recipe-card {background-color: #f8f9fa;border-radius: 15px;padding: 25px;margin-bottom: 25px;border-left: 5px solid #ff6b6b;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}</style>""", unsafe_allow_html=True)with st.container():st.markdown('<div class="recipe-card">', unsafe_allow_html=True)# Header with recipe IDcol_header1, col_header2, col_header3 = st.columns([2, 1, 1])with col_header1:st.subheader(f"🍽️ {recipe['dish_name']}")st.code(f"ID: {recipe.get('id', 'N/A')}", language=None)with col_header2:if recipe.get('recipe_type'):st.info(recipe['recipe_type'])with col_header3:if recipe.get('submitted_date'):st.caption(f"{get_text('submitted_on')}: {recipe['submitted_date'][:10]}")# Metadatametadata_parts = []if recipe.get('your_name'):metadata_parts.append(f"**{recipe['your_name']}**")if recipe.get('district'):metadata_parts.append(f"{get_text('from_district')} **{recipe['district']}**")if metadata_parts:st.caption(f"{get_text('submitted_by')} " + " • ".join(metadata_parts))# Tagsif recipe.get('tags'):tag_display = " ".join([f"`{tag}`" for tag in recipe['tags']])st.markdown(tag_display)# Contentleft_col, right_col = st.columns([1, 1.2])with left_col:if recipe.get('image_filename'):try:image_data = load_image_from_memory(recipe['image_filename'])if image_data:st.image(image_data, caption=recipe['dish_name'], use_column_width=True)else:st.image("https://placehold.co/400x300/E8F4FD/31343C?text=Image+Not+Found")except:st.image("https://placehold.co/400x300/E8F4FD/31343C?text=Error+Loading+Image")else:st.image("https://placehold.co/400x300/E8F4FD/31343C?text=No+Image+Available")with right_col:if recipe.get('story'):with st.expander(get_text('story_title')):st.write(recipe['story'])with st.expander(get_text('ingredients_title')):if recipe.get('ingredients'):ingredients_list = recipe['ingredients'].split('\n')for ingredient in ingredients_list:if ingredient.strip():st.write(f"• {ingredient.strip()}")else:st.write("No ingredients listed.")with st.expander(get_text('instructions_title'), expanded=True):st.write(recipe.get('instructions', 'No instructions provided.'))st.markdown('</div>', unsafe_allow_html=True)st.markdown("---")# --- Analytics Tab ---with tab_analytics:st.header("📊 Recipe Analytics")recipes = load_all_recipes_from_memory()if not recipes:st.info("No data available yet. Submit some recipes to see analytics!")else:# Overview metricscol1, col2, col3, col4 = st.columns(4)stats = get_recipe_stats()with col1:st.metric(get_text('total_recipes'), len(recipes))with col2:unique_contributors = len(set(r.get('your_name', 'Anonymous') for r in recipes if r.get('your_name')))st.metric("Contributors", unique_contributors)with col3:unique_districts = len(set(r.get('district', '') for r in recipes if r.get('district')))st.metric("Districts Represented", unique_districts)with col4:recipes_with_images = len([r for r in recipes if r.get('image_filename')])st.metric("Recipes with Photos", recipes_with_images)st.markdown("---")# Storage informationst.subheader("💾 Memory Storage Information")col1, col2, col3 = st.columns(3)with col1:st.info(f"**Recipe Data:** {stats['total_recipes']} items")st.caption("Stored in session state")with col2:st.info(f"**Image Data:** {stats['total_images']} items")st.caption("Stored as base64 in memory")with col3:st.info(f"**Memory Usage:** {format_storage_size(stats['storage_size'])}")st.caption("Approximate size in memory")st.markdown("---")# Chartscol1, col2 = st.columns(2)with col1:st.subheader(get_text('top_districts'))district_counts = Counter(r.get('district', 'Unknown') for r in recipes if r.get('district'))if district_counts:district_df = pd.DataFrame(list(district_counts.items()), columns=['District', 'Count'])district_df = district_df.sort_values('Count', ascending=True).tail(10)st.bar_chart(district_df.set_index('District'))else:st.info("No district data available")with col2:st.subheader(get_text('popular_types'))type_counts = Counter(r.get('recipe_type', 'Unknown') for r in recipes)if type_counts:type_df = pd.DataFrame(list(type_counts.items()), columns=['Type', 'Count'])st.bar_chart(type_df.set_index('Type'))# Recent activityst.subheader(get_text('recent_recipes'))recent_recipes = sorted(recipes,key=lambda x: x.get('submitted_date', ''),reverse=True)[:10]for recipe in recent_recipes:col1, col2, col3, col4 = st.columns([2, 1, 1, 1])with col1:st.write(f"**{recipe['dish_name']}**")with col2:st.write(recipe.get('your_name', 'Anonymous'))with col3:st.write(recipe.get('submitted_date', 'Unknown')[:10] if recipe.get('submitted_date') else 'Unknown')with col4:st.code(recipe.get('id', 'N/A'), language=None)# Export functionalityst.markdown("---")col1, col2 = st.columns(2)with col1:if st.button(get_text('export_recipes')):csv_data = export_recipes_to_csv(recipes)if csv_data is not None:csv_string = csv_data.to_csv(index=False)st.download_button(label="Download CSV",data=csv_string,file_name=f"ruchi_chudu_recipes_{datetime.now().strftime('%Y%m%d')}.csv",mime="text/csv")else:st.error("No recipes to export")with col2:if st.button(get_text('backup_data')):try:# Create a comprehensive JSON backupbackup_data = {"recipes": recipes,"images": st.session_state.get('recipe_images', {}),"exported_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),"total_recipes": len(recipes),"total_images": len(st.session_state.get('recipe_images', {}))}backup_json = json.dumps(backup_data, ensure_ascii=False, indent=2)st.download_button(label="Download JSON Backup",data=backup_json,file_name=f"ruchi_chudu_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",mime="application/json")st.success(get_text('backup_created'))except Exception as e:st.error(f"Error creating backup: {e}")# --- Management Tab ---with tab_manage:st.header(get_text('manage_header'))recipes = load_all_recipes_from_memory()if not recipes:st.info("No recipes to manage yet.")else:st.write(f"Managing **{len(recipes)}** recipes")# Search for specific recipe to managesearch_manage = st.text_input("Search for recipe to manage", placeholder="Enter recipe name or ID...")# Filter recipes for managementmanage_recipes = recipesif search_manage:manage_recipes = [r for r in recipes ifsearch_manage.lower() in r['dish_name'].lower() orsearch_manage.lower() in r.get('id', '').lower()]if not manage_recipes and search_manage:st.warning("No recipes found matching your search.")# Display recipes for managementfor recipe in manage_recipes[:20]: # Limit to 20 for performancewith st.expander(f"🍽️ {recipe['dish_name']} (ID: {recipe.get('id', 'N/A')})"):col1, col2, col3 = st.columns([2, 1, 1])with col1:st.write(f"**Submitted by:** {recipe.get('your_name', 'Anonymous')}")st.write(f"**District:** {recipe.get('district', 'Not specified')}")st.write(f"**Type:** {recipe.get('recipe_type', 'Not specified')}")st.write(f"**Submitted:** {recipe.get('submitted_date', 'Unknown')}")with col2:st.write(f"**Storage Location:**")st.code("Session Memory")if recipe.get('image_filename'):st.write(f"**Image:**")st.code(f"Memory: {recipe['image_filename']}")# Show approximate sizerecipe_size = len(json.dumps(recipe, ensure_ascii=False).encode('utf-8'))st.caption(f"Size: {format_storage_size(recipe_size)}")with col3:# Delete button with confirmationdelete_key = f"delete_{recipe.get('id', 'unknown')}"confirm_key = f"confirm_delete_{recipe.get('id')}"if st.button(f"🗑️ {get_text('delete_recipe')}", key=delete_key):if st.session_state.get(confirm_key, False):if delete_recipe_from_memory(recipe.get('id')):st.success(get_text('recipe_deleted'))st.rerun()else:st.error("Failed to delete recipe.")else:st.session_state[confirm_key] = Truest.warning(get_text('confirm_delete'))if st.session_state.get(confirm_key, False):if st.button(f"✅ Confirm Delete", key=f"confirm_{recipe.get('id')}"):if delete_recipe_from_memory(recipe.get('id')):st.success(get_text('recipe_deleted'))# Clear the confirmation statest.session_state[confirm_key] = Falsest.rerun()else:st.error("Failed to delete recipe.")if len(manage_recipes) > 20:st.info(f"Showing first 20 recipes. Use search to find specific recipes. Total: {len(manage_recipes)}")# Bulk operationsst.markdown("---")st.subheader("🔧 Memory Management")col1, col2, col3 = st.columns(3)with col1:if st.button("📊 Refresh Stats"):stats = get_recipe_stats()st.success("Stats refreshed!")st.write(f"Total recipes: {stats['total_recipes']}")st.write(f"Total images: {stats['total_images']}")st.write(f"Memory usage: {format_storage_size(stats['storage_size'])}")with col2:if st.button("🔄 Reload Data"):st.success("Data reloaded from session state!")st.rerun()with col3:if st.button("🧹 Clear All Data", type="secondary"):if st.button("⚠️ Confirm Clear All", type="secondary"):st.session_state['recipes'] = []st.session_state['recipe_images'] = {}st.success("All data cleared!")st.rerun()# Session infost.markdown("---")st.subheader("📋 Session Information")col1, col2 = st.columns(2)with col1:st.info("**Storage Type:** Session Memory")st.caption("Data persists only during this browser session")st.info("**Data Persistence:** Temporary")st.caption("Data will be lost when you close the browser or refresh")with col2:st.info("**Session State Keys:**")session_keys = [key for key in st.session_state.keys() if key in ['recipes', 'recipe_images']]for key in session_keys:if key == 'recipes':st.caption(f"• {key}: {len(st.session_state[key])} items")elif key == 'recipe_images':st.caption(f"• {key}: {len(st.session_state[key])} items")# --- Footer Information ---st.markdown("---")st.markdown("""### 💡 Important Notes for Hugging Face Spaces:- **Data Storage**: All recipes and images are stored in memory (session state) only- **Persistence**: Data will be lost when the browser session ends or the space restarts- **File System**: Hugging Face Spaces has read-only file system, so we use in-memory storage- **Images**: Uploaded images are converted to base64 and stored in memory- **Export**: Use the export/backup features to save your data locally- **Session Sharing**: Each user has their own independent session and data**For Production Use**: Consider integrating with a database service or cloud storage for persistent data storage.""")# --- Debug Information (Optional) ---if st.sidebar.checkbox("Show Debug Info"):st.sidebar.markdown("---")st.sidebar.subheader("🔧 Debug Info")st.sidebar.write(f"Session recipes: {len(st.session_state.get('recipes', []))}")st.sidebar.write(f"Session images: {len(st.session_state.get('recipe_images', {}))}")st.sidebar.write(f"Current language: {st.session_state.get('language', 'en')}")# Show session state keysif st.sidebar.checkbox("Show all session keys"):st.sidebar.write("Session state keys:")for key in st.session_state.keys():st.sidebar.caption(f"• {key}")12345678910111213141516171819202122232425262 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373384 unmodified lines34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238318 unmodified lines4024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364376 unmodified lines44444544644744844945045145245345445545645745845946046146220 unmodified lines4834844854864874884894904914924934942 unmodified lines497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986import streamlit as stimport pandas as pdfrom collections import Counterimport jsonimport osimport uuidfrom datetime import datetimeimport base64import globimport refrom typing import List, Dict, Tuple# AI/ML imports - lightweight transformerstry:from sentence_transformers import SentenceTransformerfrom transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassificationimport torchimport numpy as npfrom sklearn.metrics.pairwise import cosine_similarityAI_AVAILABLE = Trueexcept ImportError:AI_AVAILABLE = Falsest.warning("⚠️ AI features require additional packages. Install with: pip install sentence-transformers transformers torch scikit-learn")# --- Page Configuration ---st.set_page_config(2 unmodified lineslayout="wide")# --- AI Model Management ---@st.cache_resourcedef load_ai_models():"""Load AI models with caching to prevent reloading"""if not AI_AVAILABLE:return None, None, Nonetry:# Lightweight sentence transformer for recipe similaritysimilarity_model = SentenceTransformer('all-MiniLM-L6-v2')# Sentiment analysis for recipe storiessentiment_analyzer = pipeline("sentiment-analysis",model="cardiffnlp/twitter-roberta-base-sentiment-latest",return_all_scores=True)# Text classification for cuisine type - using a lighter modelcuisine_classifier = pipeline("text-classification",model="cardiffnlp/twitter-roberta-base-sentiment-latest" # Reuse sentiment model)return similarity_model, sentiment_analyzer, cuisine_classifierexcept Exception as e:st.error(f"Error loading AI models: {e}")return None, None, None# --- Enhanced AI Functions ---def analyze_recipe_sentiment(story: str, sentiment_analyzer) -> Dict:"""Analyze the emotional tone of recipe stories"""if not story or not sentiment_analyzer:return {"sentiment": "neutral", "confidence": 0.5, "emotion": "nostalgic"}try:results = sentiment_analyzer(story[:500]) # Limit text length# Map sentiment labels to readable formatsentiment_map = {'LABEL_0': 'negative','LABEL_1': 'neutral','LABEL_2': 'positive','NEGATIVE': 'negative','NEUTRAL': 'neutral','POSITIVE': 'positive'}top_result = max(results[0], key=lambda x: x['score'])sentiment = sentiment_map.get(top_result['label'], 'neutral')confidence = top_result['score']# Add emotion context for Telugu recipesemotion_keywords = {'joyful': ['celebration', 'festival', 'happy', 'joy', 'smile', 'laugh'],'nostalgic': ['grandmother', 'childhood', 'memory', 'tradition', 'old', 'ammamma'],'proud': ['special', 'unique', 'best', 'famous', 'perfect', 'excellent'],'loving': ['family', 'mother', 'love', 'care', 'warmth', 'together']}story_lower = story.lower()emotion = 'nostalgic' # default for recipe storiesfor emotion_type, keywords in emotion_keywords.items():if any(keyword in story_lower for keyword in keywords):emotion = emotion_typebreakreturn {"sentiment": sentiment,"confidence": confidence,"emotion": emotion}except Exception as e:return {"sentiment": "neutral", "confidence": 0.5, "emotion": "nostalgic"}def extract_smart_tags(recipe_data: Dict, similarity_model) -> List[str]:"""Extract intelligent tags using NLP and pattern matching"""tags = set()# Combine text for analysistext_content = f"{recipe_data.get('dish_name', '')} {recipe_data.get('ingredients', '')} {recipe_data.get('instructions', '')} {recipe_data.get('story', '')}"# Traditional keyword-based tagging (enhanced)keyword_categories = {'spice_level': {'mild': ['mild', 'less spicy', 'children', 'sweet'],'medium': ['medium', 'moderate', 'balanced'],'hot': ['spicy', 'hot', 'chili', 'pepper', 'karam', 'guntur'],'very_hot': ['very spicy', 'extra hot', 'burning', 'fire']},'cooking_time': {'quick': ['quick', 'fast', 'minutes', '15 min', '20 min', 'instant'],'medium': ['30 min', '45 min', '1 hour', 'moderate time'],'slow': ['hours', 'slow cook', 'overnight', 'patience']},'meal_type': {'breakfast': ['breakfast', 'morning', 'tiffin', 'idli', 'dosa'],'lunch': ['lunch', 'meal', 'rice', 'curry', 'sambar'],'dinner': ['dinner', 'night', 'heavy'],'snack': ['snack', 'evening', 'tea time', 'biscuit']},'health': {'healthy': ['healthy', 'nutritious', 'vitamin', 'protein', 'fiber'],'diabetic_friendly': ['sugar free', 'diabetic', 'low sugar', 'jaggery'],'high_protein': ['protein', 'dal', 'lentils', 'sprouts'],'low_fat': ['oil free', 'steamed', 'boiled', 'grilled']},'occasion': {'festival': ['festival', 'celebration', 'ugadi', 'sankranti', 'diwali'],'wedding': ['wedding', 'marriage', 'function', 'ceremony'],'everyday': ['daily', 'regular', 'simple', 'routine'],'special': ['special', 'guest', 'party', 'occasion']}}text_lower = text_content.lower()for category, subcategories in keyword_categories.items():for tag, keywords in subcategories.items():if any(keyword in text_lower for keyword in keywords):tags.add(tag.replace('_', ' ').title())# Telugu-specific patternstelugu_patterns = {'Regional': ['Andhra', 'Telangana', 'Hyderabad', 'Vijayawada', 'Guntur'],'Traditional': ['traditional', 'authentic', 'original', 'sampradayam'],'Modern': ['fusion', 'modern', 'new style', 'innovative'],'Street Food': ['street', 'vendor', 'roadside', 'chat']}for tag, patterns in telugu_patterns.items():if any(pattern.lower() in text_lower for pattern in patterns):tags.add(tag)# Ingredient-based classificationingredient_text = recipe_data.get('ingredients', '').lower()# Detect vegetarian/non-vegetariannon_veg_ingredients = ['chicken', 'mutton', 'fish', 'egg', 'meat', 'prawn', 'crab']if any(ingredient in ingredient_text for ingredient in non_veg_ingredients):tags.add('Non-Vegetarian')else:tags.add('Vegetarian')# Detect main ingredientsmain_ingredients = {'Rice Based': ['rice', 'biryani', 'pulao', 'annam'],'Dal Based': ['dal', 'lentil', 'pappu', 'sambar'],'Vegetable': ['vegetable', 'curry', 'fry', 'kura'],'Sweet': ['sweet', 'sugar', 'jaggery', 'dessert', 'halwa'],'Pickle': ['pickle', 'achar', 'pachadi']}for tag, ingredients in main_ingredients.items():if any(ingredient in ingredient_text for ingredient in ingredients):tags.add(tag)return list(tags)def find_similar_recipes(current_recipe: Dict, all_recipes: List[Dict], similarity_model, top_k=3) -> List[Tuple[Dict, float]]:"""Find similar recipes using semantic similarity"""if not similarity_model or len(all_recipes) < 2:return []try:# Create text representationscurrent_text = f"{current_recipe.get('dish_name', '')} {current_recipe.get('ingredients', '')} {current_recipe.get('recipe_type', '')}"recipe_texts = []valid_recipes = []for recipe in all_recipes:if recipe.get('id') != current_recipe.get('id'): # Exclude current reciperecipe_text = f"{recipe.get('dish_name', '')} {recipe.get('ingredients', '')} {recipe.get('recipe_type', '')}"recipe_texts.append(recipe_text)valid_recipes.append(recipe)if not recipe_texts:return []# Generate embeddingscurrent_embedding = similarity_model.encode([current_text])recipe_embeddings = similarity_model.encode(recipe_texts)# Calculate similaritiessimilarities = cosine_similarity(current_embedding, recipe_embeddings)[0]# Get top similar recipessimilar_indices = np.argsort(similarities)[::-1][:top_k]similar_recipes = []for idx in similar_indices:if similarities[idx] > 0.3: # Minimum similarity thresholdsimilar_recipes.append((valid_recipes[idx], similarities[idx]))return similar_recipesexcept Exception as e:st.error(f"Error finding similar recipes: {e}")return []def generate_cooking_tips(recipe_data: Dict) -> List[str]:"""Generate contextual cooking tips based on recipe content"""tips = []ingredients = recipe_data.get('ingredients', '').lower()instructions = recipe_data.get('instructions', '').lower()dish_name = recipe_data.get('dish_name', '').lower()# Ingredient-specific tipsif 'oil' in ingredients:tips.append("🔥 Tip: Heat oil until it shimmers but doesn't smoke for best results")if 'onion' in ingredients:tips.append("🧅 Tip: Soak sliced onions in cold water for 10 minutes to reduce tears while cutting")if any(spice in ingredients for spice in ['turmeric', 'chili', 'coriander']):tips.append("🌶️ Tip: Dry roast spices lightly before grinding for enhanced flavor")if 'rice' in ingredients:tips.append("🍚 Tip: Soak rice for 20-30 minutes before cooking for better texture")# Cooking method tipsif 'fry' in instructions or 'deep fry' in instructions:tips.append("🍳 Tip: Maintain oil temperature at 350°F (175°C) for perfect frying")if 'boil' in instructions:tips.append("💧 Tip: Add salt to boiling water for vegetables to retain color and nutrients")# Dish-specific tipsif 'curry' in dish_name:tips.append("🍛 Tip: Let curry rest for 10 minutes after cooking to allow flavors to meld")if 'pickle' in dish_name:tips.append("🥒 Tip: Store pickle in airtight containers and use dry spoons to prevent spoilage")# Regional tipstips.append("🏠 Traditional Tip: Taste and adjust seasoning as family preferences vary by region")return tips[:3] # Return top 3 tips# --- Data Storage Functions ---RECIPES_FOLDER = "recipes"IMAGES_FOLDER = "recipe_images"def ensure_folders_exist():"""Create necessary folders if they don't exist"""os.makedirs(RECIPES_FOLDER, exist_ok=True)os.makedirs(IMAGES_FOLDER, exist_ok=True)def generate_recipe_id():"""Generate a unique ID for each recipe"""return str(uuid.uuid4())[:8]def save_recipe(recipe_data):"""Save individual recipe to its own JSON file"""try:ensure_folders_exist()recipe_id = recipe_data['id']filename = f"recipe_{recipe_id}.json"filepath = os.path.join(RECIPES_FOLDER, filename)with open(filepath, 'w', encoding='utf-8') as f:json.dump(recipe_data, f, ensure_ascii=False, indent=2)return Trueexcept Exception as e:st.error(f"Error saving recipe: {e}")return Falsedef load_all_recipes():"""Load all recipes from individual JSON files"""recipes = []try:ensure_folders_exist()recipe_files = glob.glob(os.path.join(RECIPES_FOLDER, "recipe_*.json"))for filepath in recipe_files:try:with open(filepath, 'r', encoding='utf-8') as f:recipe = json.load(f)recipes.append(recipe)except Exception as e:continuerecipes.sort(key=lambda x: x.get('submitted_date', ''), reverse=True)except Exception as e:st.error(f"Error loading recipes: {e}")return recipes# --- Language and Text ---TEXT = {"en": {"title": "Ruchi Chudu","subtitle": "AI-Powered Community Cookbook to Preserve Telugu Cuisine","language_select": "Choose Language","sidebar_header": "Contribute Your Recipe!","tab_submit": "📝 Submit Your Recipe","tab_gallery": "🍲 Community Gallery","tab_ai_insights": "🤖 AI Recipe Insights","tab_analytics": "📊 Recipe Analytics","form_header": "Tell us about your dish","dish_name": "Dish Name","your_name": "Your Name","district": "Your District","select_district": "--- Select a District ---","recipe_type": "Recipe Type (e.g., Curry, Pickle, Snack)",4 unmodified lines"submit_button": "Submit Recipe","success_message": "Thank you! Your recipe has been submitted successfully.","gallery_header": "Explore Recipes from the Community","ai_analysis": "🤖 AI Analysis","similar_recipes": "👥 Similar Recipes","cooking_tips": "💡 Smart Cooking Tips","recipe_sentiment": "😊 Recipe Story Mood","search_placeholder": "Search recipes or ask AI...","ai_search_help": "Try: 'spicy vegetarian curry' or 'quick breakfast recipe'",},"te": {"title": "రుచి చూడు","subtitle": "AI శక్తితో మన తెలుగు వంటల సంస్కృతిని కాపాడడం","language_select": "భాషను ఎంచుకోండి","sidebar_header": "మీ వంటకాన్ని పంపండి!","tab_submit": "📝 మీ వంటకాన్ని పంపండి","tab_gallery": "🍲 కమ్యూనిటీ గ్యాలరీ","tab_ai_insights": "🤖 AI వంటకాల విశ్లేషణ","tab_analytics": "📊 వంటకాల విశ్లేషణ","form_header": "మీ వంటకం గురించి చెప్పండి","dish_name": "వంటకం పేరు","your_name": "మీ పేరు","district": "మీ జిల్లా","select_district": "--- జిల్లాను ఎంచుకోండి ---","recipe_type": "వంటకం రకం (ఉదా. కూర, పచ్చడి, స్నాక్)","ingredients": "కావలసినవి (ఒకదానికి ఒకటి)","instructions": "తయారీ విధానం","story": "ఈ వంటతో మీ కథ (మీ జ్ఞాపకాలు, కుటుంబ సంప్రదాయాలు మొదలైనవి)","image_upload": "వంటకం ఫోటోను అప్లోడ్ చేయండి (ఐచ్ఛికం)","submit_button": "వంటకాన్ని పంపండి","success_message": "ధన్యవాదాలు! మీ వంటకం విజయవంతంగా సమర్పించబడింది.","gallery_header": "కమ్యూనిటీ నుంది వంటకాలను అన్వేషించండి","ai_analysis": "🤖 AI విశ్లేషణ","similar_recipes": "👥 సమాన వంటకాలు","cooking_tips": "💡 తెలివైన వంట చిట్కాలు","recipe_sentiment": "😊 వంటకం కథ భావం","search_placeholder": "వంటకాలను వెతకండి లేదా AI ని అడగండి...","ai_search_help": "ప్రయత్నించండ���: 'కారంగా వెజిటేరియన్ కూర' లేదా 'తొందర అల్పాహారం'",}}18 unmodified linesif 'language' not in st.session_state:st.session_state['language'] = 'en'if 'recipes' not in st.session_state:st.session_state['recipes'] = load_all_recipes()if 'ai_models_loaded' not in st.session_state:st.session_state['ai_models_loaded'] = False# --- Helper Functions ---def get_text(key):"""Fetches text from the dictionary based on the selected language."""return TEXT[st.session_state['language']][key]# --- Load AI Models ---similarity_model, sentiment_analyzer, cuisine_classifier = None, None, Noneif AI_AVAILABLE and not st.session_state.get('ai_models_loaded', False):with st.spinner("🤖 Loading AI models for the first time... This may take a moment."):similarity_model, sentiment_analyzer, cuisine_classifier = load_ai_models()if similarity_model:st.session_state['ai_models_loaded'] = Truest.success("✅ AI models loaded successfully!")else:similarity_model, sentiment_analyzer, cuisine_classifier = load_ai_models()# --- Sidebar ---with st.sidebar:st.title(f"🍲 {get_text('title')}")st.markdown(get_text('subtitle'))if AI_AVAILABLE and similarity_model:st.success("🤖 AI Features: Active")else:st.warning("🤖 AI Features: Limited")st.markdown("---")# Language selector6 unmodified linesst.session_state['language'] = 'te' if lang_choice == 'తెలుగు' else 'en'st.info(get_text('sidebar_header'))# --- Main App Layout ---st.title(get_text('title'))# Create tabs including the new AI insights tabtab_submit, tab_gallery, tab_ai, tab_analytics = st.tabs([get_text('tab_submit'),get_text('tab_gallery'),get_text('tab_ai_insights'),get_text('tab_analytics')])# --- Submission Form Tab (Enhanced with AI) ---with tab_submit:st.header(get_text('form_header'))20 unmodified linesif submitted:if not dish_name:st.error("Please enter a dish name before submitting.")else:recipe_id = generate_recipe_id()# Create recipe data for AI analysisrecipe_data = {"id": recipe_id,"dish_name": dish_name,"your_name": your_name,2 unmodified lines"ingredients": ingredients,"instructions": instructions,"story": story,"submitted_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}# AI Analysisif AI_AVAILABLE and sentiment_analyzer:with st.spinner("🤖 AI is analyzing your recipe..."):# Sentiment analysissentiment_data = analyze_recipe_sentiment(story, sentiment_analyzer)# Smart tag extractionai_tags = extract_smart_tags(recipe_data, similarity_model)# Add AI analysis to recipe datarecipe_data.update({"ai_tags": ai_tags,"sentiment_analysis": sentiment_data,"cooking_tips": generate_cooking_tips(recipe_data)})# Show AI insightsst.subheader("🤖 AI Analysis Results")col1, col2 = st.columns(2)with col1:st.metric("Recipe Mood", sentiment_data['emotion'].title(), f"{sentiment_data['confidence']:.0%} confidence")st.write("**AI Tags:**", ", ".join([f"`{tag}`" for tag in ai_tags]))with col2:st.write("**Smart Cooking Tips:**")for tip in recipe_data['cooking_tips']:st.write(f"• {tip}")else:# Fallback basic taggingrecipe_data["ai_tags"] = ["Community Recipe"]recipe_data["sentiment_analysis"] = {"sentiment": "positive", "emotion": "nostalgic"}recipe_data["cooking_tips"] = ["Follow the recipe step by step for best results."]# Save recipeif save_recipe(recipe_data):st.session_state.recipes.insert(0, recipe_data)st.success(f"{get_text('success_message')} (ID: {recipe_id})")st.balloons()else:st.error("Failed to save recipe. Please try again.")# --- Community Gallery Tab (Enhanced with AI) ---with tab_gallery:st.header(get_text('gallery_header'))# AI-powered searchif AI_AVAILABLE and similarity_model:st.subheader("🔍 AI-Powered Recipe Search")search_query = st.text_input("Search recipes with natural language:",placeholder=get_text('ai_search_help'),help="Ask in natural language like 'show me spicy vegetarian curries' or 'quick breakfast ideas'")if search_query and st.session_state.recipes:with st.spinner("🤖 AI is searching..."):# Use semantic searchquery_embedding = similarity_model.encode([search_query])recipe_texts = []valid_recipes = []for recipe in st.session_state.recipes:recipe_text = f"{recipe.get('dish_name', '')} {recipe.get('ingredients', '')} {recipe.get('recipe_type', '')} {' '.join(recipe.get('ai_tags', []))}"recipe_texts.append(recipe_text)valid_recipes.append(recipe)if recipe_texts:recipe_embeddings = similarity_model.encode(recipe_texts)similarities = cosine_similarity(query_embedding, recipe_embeddings)[0]# Get top matchestop_indices = np.argsort(similarities)[::-1][:10]matching_recipes = []for idx in top_indices:if similarities[idx] > 0.2: # Minimum similaritymatching_recipes.append((valid_recipes[idx], similarities[idx]))if matching_recipes:st.success(f"🎯 Found {len(matching_recipes)} recipes matching your search")display_recipes = [recipe for recipe, _ in matching_recipes]else:st.info("No recipes found matching your search. Try different keywords.")display_recipes = st.session_state.recipes[:5]else:display_recipes = st.session_state.recipeselse:display_recipes = st.session_state.recipeselse:# Fallback to basic searchsearch_term = st.text_input("Search recipes:", placeholder=get_text('search_placeholder'))if search_term:display_recipes = [r for r in st.session_state.recipes ifsearch_term.lower() in r['dish_name'].lower() orsearch_term.lower() in r.get('ingredients', '').lower()]else:display_recipes = st.session_state.recipes# Display recipes with AI insightsfor recipe in display_recipes[:10]: # Show top 10with st.expander(f"🍽️ {recipe['dish_name']} (ID: {recipe.get('id', 'N/A')})"):# Basic recipe infocol1, col2, col3 = st.columns(3)with col1:st.write(f"**By:** {recipe.get('your_name', 'Anonymous')}")st.write(f"**District:** {recipe.get('district', 'Not specified')}")st.write(f"**Type:** {recipe.get('recipe_type', 'Not specified')}")with col2:# AI Tagsif recipe.get('ai_tags'):st.write("**AI Tags:**")for tag in recipe['ai_tags'][:3]: # Show top 3 tagsst.badge(tag)# Sentiment analysisif recipe.get('sentiment_analysis'):sentiment = recipe['sentiment_analysis']st.write(f"**Story Mood:** {sentiment['emotion'].title()}")with col3:st.write(f"**Submitted:** {recipe.get('submitted_date', 'Unknown')}")if recipe.get('cooking_tips'):with st.popover("💡 Cooking Tips"):for tip in recipe['cooking_tips']:st.write(f"• {tip}")# Recipe contentst.markdown("### Ingredients:")st.text(recipe.get('ingredients', 'No ingredients provided'))st.markdown("### Instructions:")st.text(recipe.get('instructions', 'No instructions provided'))if recipe.get('story'):st.markdown("### Story:")st.text(recipe['story'])# AI-powered similar recipesif AI_AVAILABLE and similarity_model and len(st.session_state.recipes) > 1:similar_recipes = find_similar_recipes(recipe, st.session_state.recipes, similarity_model)if similar_recipes:st.markdown("### 👥 Similar Recipes:")sim_cols = st.columns(len(similar_recipes))for idx, (sim_recipe, similarity) in enumerate(similar_recipes):with sim_cols[idx]:st.write(f"**{sim_recipe['dish_name']}**")st.write(f"Similarity: {similarity:.0%}")st.caption(f"By {sim_recipe.get('your_name', 'Anonymous')}")# --- AI Insights Tab ---with tab_ai:st.header("🤖 AI Recipe Insights")if not AI_AVAILABLE or not similarity_model:st.warning("AI features are not available. Please install required packages to enable AI insights.")st.code("pip install sentence-transformers transformers torch scikit-learn")st.stop()if not st.session_state.recipes:st.info("No recipes available for analysis. Submit some recipes first!")st.stop()# AI Analysis Dashboardst.subheader("📊 Community Recipe Analysis")# Sentiment distributionsentiments = [recipe.get('sentiment_analysis', {}).get('emotion', 'nostalgic')for recipe in st.session_state.recipes]sentiment_counts = Counter(sentiments)col1, col2 = st.columns(2)with col1:st.markdown("**Recipe Story Moods:**")for emotion, count in sentiment_counts.most_common():percentage = (count / len(st.session_state.recipes)) * 100st.write(f"😊 {emotion.title()}: {count} recipes ({percentage:.1f}%)")with col2:# Most common AI tagsall_tags = []for recipe in st.session_state.recipes:all_tags.extend(recipe.get('ai_tags', []))if all_tags:tag_counts = Counter(all_tags)st.markdown("**Most Popular Recipe Types:**")for tag, count in tag_counts.most_common(5):st.write(f"🏷️ {tag}: {count} recipes")st.markdown("---")# Recipe Recommendation Enginest.subheader("🎯 AI Recipe Recommendations")col1, col2 = st.columns(2)with col1:preference = st.selectbox("What are you in the mood for?",["Spicy dishes", "Sweet treats", "Quick meals", "Traditional recipes","Healthy options", "Festival specials", "Comfort food"])with col2:dietary_pref = st.selectbox("Dietary preference:",["Any", "Vegetarian only", "Non-vegetarian", "Healthy options"])if st.button("🤖 Get AI Recommendations"):with st.spinner("🤖 AI is finding perfect recipes for you..."):# Create recommendation query based on preferencesquery_map = {"Spicy dishes": "spicy hot chili pepper karam","Sweet treats": "sweet jaggery sugar dessert halwa","Quick meals": "quick fast instant easy","Traditional recipes": "traditional authentic grandmother ammamma","Healthy options": "healthy nutritious protein vitamin","Festival specials": "festival celebration ugadi sankranti","Comfort food": "comfort home family love"}search_query = query_map.get(preference, preference)# Filter by dietary preferencefiltered_recipes = st.session_state.recipesif dietary_pref == "Vegetarian only":filtered_recipes = [r for r in filtered_recipes if 'Vegetarian' in r.get('ai_tags', [])]elif dietary_pref == "Non-vegetarian":filtered_recipes = [r for r in filtered_recipes if 'Non-Vegetarian' in r.get('ai_tags', [])]elif dietary_pref == "Healthy options":filtered_recipes = [r for r in filtered_recipes if any(tag in ['Healthy', 'High Protein', 'Low Fat'] for tag in r.get('ai_tags', []))]if filtered_recipes:# Use AI to find best matchesquery_embedding = similarity_model.encode([search_query])recipe_texts = []for recipe in filtered_recipes:recipe_text = f"{recipe.get('dish_name', '')} {recipe.get('ingredients', '')} {' '.join(recipe.get('ai_tags', []))}"recipe_texts.append(recipe_text)if recipe_texts:recipe_embeddings = similarity_model.encode(recipe_texts)similarities = cosine_similarity(query_embedding, recipe_embeddings)[0]# Get top recommendationstop_indices = np.argsort(similarities)[::-1][:3]st.success(f"🎯 Here are your personalized recommendations:")for idx in top_indices:if similarities[idx] > 0.1: # Minimum relevancerecipe = filtered_recipes[idx]match_score = similarities[idx] * 100with st.container():st.markdown(f"### 🍽️ {recipe['dish_name']}")col1, col2, col3 = st.columns(3)with col1:st.write(f"**Match Score:** {match_score:.0f}%")st.write(f"**By:** {recipe.get('your_name', 'Anonymous')}")with col2:st.write(f"**Type:** {recipe.get('recipe_type', 'N/A')}")st.write(f"**District:** {recipe.get('district', 'N/A')}")with col3:if recipe.get('ai_tags'):st.write("**Tags:**")for tag in recipe['ai_tags'][:2]:st.badge(tag)if recipe.get('story'):st.write(f"*{recipe['story'][:150]}...*")st.markdown("---")else:st.info("No recipes found matching your preferences. Try different criteria!")st.markdown("---")# Recipe Insightsst.subheader("🔍 Deep Recipe Analysis")if st.session_state.recipes:selected_recipe = st.selectbox("Select a recipe to analyze:",options=[f"{r['dish_name']} (by {r.get('your_name', 'Anonymous')})" for r in st.session_state.recipes],index=0)if selected_recipe:# Find the selected reciperecipe_idx = next(i for i, r in enumerate(st.session_state.recipes)if f"{r['dish_name']} (by {r.get('your_name', 'Anonymous')})" == selected_recipe)recipe = st.session_state.recipes[recipe_idx]col1, col2 = st.columns(2)with col1:st.markdown("**🤖 AI Analysis:**")# Sentiment analysis detailsif recipe.get('sentiment_analysis'):sentiment = recipe['sentiment_analysis']st.metric("Story Emotion",sentiment['emotion'].title(),f"{sentiment['confidence']:.0%} confidence")# AI tagsif recipe.get('ai_tags'):st.write("**AI-Detected Categories:**")for tag in recipe['ai_tags']:st.badge(tag)with col2:st.markdown("**💡 Smart Cooking Tips:**")if recipe.get('cooking_tips'):for tip in recipe['cooking_tips']:st.info(tip)else:# Generate tips on demandtips = generate_cooking_tips(recipe)for tip in tips:st.info(tip)# Similar recipesst.markdown("**👥 Similar Recipes:**")similar_recipes = find_similar_recipes(recipe, st.session_state.recipes, similarity_model, top_k=5)if similar_recipes:for sim_recipe, similarity in similar_recipes:with st.expander(f"{sim_recipe['dish_name']} - {similarity:.0%} similar"):st.write(f"**By:** {sim_recipe.get('your_name', 'Anonymous')}")st.write(f"**Type:** {sim_recipe.get('recipe_type', 'N/A')}")if sim_recipe.get('story'):st.write(f"**Story:** {sim_recipe['story'][:200]}...")else:st.info("No similar recipes found in the current database.")# --- Analytics Tab ---with tab_analytics:st.header("📊 Recipe Analytics Dashboard")if not st.session_state.recipes:st.info("No recipes available for analysis. Submit some recipes first!")st.stop()# Basic Statisticstotal_recipes = len(st.session_state.recipes)st.metric("Total Recipes", total_recipes)# Create dataframe for analysisdf_data = []for recipe in st.session_state.recipes:df_data.append({'dish_name': recipe.get('dish_name', ''),'your_name': recipe.get('your_name', 'Anonymous'),'district': recipe.get('district', 'Unknown'),'recipe_type': recipe.get('recipe_type', 'Other'),'submitted_date': recipe.get('submitted_date', ''),'ai_tags': recipe.get('ai_tags', []),'emotion': recipe.get('sentiment_analysis', {}).get('emotion', 'neutral')})df = pd.DataFrame(df_data)# District-wise distributioncol1, col2 = st.columns(2)with col1:st.subheader("📍 Recipes by District")district_counts = df['district'].value_counts().head(10)if not district_counts.empty:st.bar_chart(district_counts)else:st.info("No district data available")with col2:st.subheader("🍽️ Recipe Types Distribution")type_counts = df['recipe_type'].value_counts()if not type_counts.empty:st.bar_chart(type_counts)else:st.info("No recipe type data available")# Contributorsst.subheader("👥 Top Contributors")contributor_counts = df['your_name'].value_counts().head(5)for name, count in contributor_counts.items():st.write(f"🏆 {name}: {count} recipe(s)")# Emotional analysisif AI_AVAILABLE:st.subheader("😊 Recipe Story Emotions")emotion_counts = df['emotion'].value_counts()emotion_colors = {'joyful': '#FFD700','nostalgic': '#DDA0DD','proud': '#FF6347','loving': '#FF69B4','neutral': '#87CEEB'}emotion_data = []for emotion, count in emotion_counts.items():emotion_data.append({'Emotion': emotion.title(),'Count': count,'Percentage': f"{(count/total_recipes)*100:.1f}%"})emotion_df = pd.DataFrame(emotion_data)st.dataframe(emotion_df, use_container_width=True)# Recent activityst.subheader("📅 Recent Recipe Submissions")recent_recipes = st.session_state.recipes[:5] # Show 5 most recentfor recipe in recent_recipes:with st.container():col1, col2, col3 = st.columns([3, 2, 1])with col1:st.write(f"**{recipe['dish_name']}**")st.caption(f"by {recipe.get('your_name', 'Anonymous')}")with col2:st.write(f"{recipe.get('recipe_type', 'N/A')}")st.caption(f"{recipe.get('district', 'Unknown')}")with col3:st.write(recipe.get('submitted_date', 'Unknown')[:10]) # Show date onlyst.markdown("---")# Export functionalityst.subheader("📤 Export Data")if st.button("Download Recipe Database as CSV"):# Flatten the data for CSV exportexport_data = []for recipe in st.session_state.recipes:export_data.append({'ID': recipe.get('id', ''),'Dish Name': recipe.get('dish_name', ''),'Contributor': recipe.get('your_name', ''),'District': recipe.get('district', ''),'Recipe Type': recipe.get('recipe_type', ''),'Ingredients': recipe.get('ingredients', ''),'Instructions': recipe.get('instructions', ''),'Story': recipe.get('story', ''),'AI Tags': ', '.join(recipe.get('ai_tags', [])),'Emotion': recipe.get('sentiment_analysis', {}).get('emotion', ''),'Submitted Date': recipe.get('submitted_date', '')})export_df = pd.DataFrame(export_data)csv_data = export_df.to_csv(index=False)st.download_button(label="📥 Download CSV",data=csv_data,file_name=f"ruchi_chudu_recipes_{datetime.now().strftime('%Y%m%d')}.csv",mime="text/csv")# --- Footer ---st.markdown("---")st.markdown("""<div style='text-align: center; color: #666; padding: 20px;'><p>🍲 రుచి చూడు (Ruchi Chudu) - Preserving Telugu Cuisine Through Community & AI</p><p>Made with ❤️ for Telugu food lovers everywhere</p><p><small>AI Features powered by Hugging Face Transformers | Data stored locally</small></p></div>""", unsafe_allow_html=True)
src/streamlit_app.py+787-662