Muthu4all commited on
Commit
3ebe5ef
·
verified ·
1 Parent(s): a549c02

created app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import google.generativeai as genai
4
+ import os
5
+ import pandas as pd
6
+ import json
7
+ import re
8
+ from PIL import Image
9
+
10
+ # Configure Gemini using environment variable
11
+ def configure_gemini():
12
+ api_key = os.getenv("GEMINI_API_KEY")
13
+ if not api_key:
14
+ raise ValueError("GEMINI_API_KEY environment variable not set")
15
+ genai.configure(api_key=api_key)
16
+ return genai.GenerativeModel('gemini-1.5-flash-latest')
17
+
18
+ # Process image with Gemini
19
+ def process_image(model, image):
20
+ prompt = """Analyze this restaurant menu image and extract structured data in this exact JSON format. Image could have dishes in multiple columns and rows. Verify and make sure none is missed. For example this image having around 4 to 5 categories and in total around 40 to 50 dishes in total. The dishes could have name, description, price, likes percentage, rating percentage. The extracted data should be in JSON format as shown below:
21
+ [
22
+ {
23
+ "category": "Category Name",
24
+ "items": [
25
+ {
26
+ "name": "Dish Name",
27
+ "description": "Dish description (optional)",
28
+ "price": "Price"
29
+ }
30
+ ]
31
+ }
32
+ ]
33
+ Return ONLY the JSON, no other text. If no menu found, return empty JSON."""
34
+
35
+ response = model.generate_content([prompt, image])
36
+ return response.text
37
+
38
+ def extract_json(response_text):
39
+ # Debugging: Log the response text to see its format before processing
40
+ #st.write("Received response_text:", response_text)
41
+
42
+ response_text = response_text.strip('`')
43
+ response_text = response_text.strip('`')
44
+
45
+ # Remove any non-JSON prefixes
46
+ prefix = 'json'
47
+ if response_text.startswith(prefix):
48
+ response_text = response_text[len(prefix):].strip()
49
+
50
+ # Attempt to parse JSON
51
+ try:
52
+ json_data = json.loads(response_text)
53
+ #st.write("Parsed JSON data:", json_data)
54
+ return json_data
55
+ except json.JSONDecodeError as e:
56
+ st.error(f"Failed to decode JSON from the response. Error: {str(e)}")
57
+ return []
58
+
59
+ def main():
60
+ st.title("🍽️ Menu Digitizer")
61
+ st.write("Upload menu images to generate consolidated CSV")
62
+
63
+ try:
64
+ model = configure_gemini()
65
+ except ValueError as e:
66
+ st.error(f"Configuration error: {str(e)}")
67
+ st.info("Please set the GEMINI_API_KEY environment variable")
68
+ return
69
+
70
+ uploaded_files = st.file_uploader("Upload menu images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
71
+ all_items = [] # Initialize outside the loop to accumulate items from all files
72
+
73
+ if uploaded_files:
74
+ with st.spinner("Processing menus..."):
75
+ for uploaded_file in uploaded_files:
76
+ image = Image.open(uploaded_file)
77
+ try:
78
+ response = process_image(model, image)
79
+ #st.write(f"Raw response for {uploaded_file.name}:")
80
+ #st.code(response, language='json') # Display raw response
81
+
82
+ menu_data = extract_json(response)
83
+ #st.write(f"menu_data response for {menu_data}:")
84
+ #st.code(menu_data) # Display raw response
85
+
86
+ for category in menu_data:
87
+ category_name = category.get('category', 'NA') # Use 'NA' if category is missing
88
+ for item in category['items']:
89
+ item['category'] = category_name
90
+ all_items.append(item)
91
+
92
+ except Exception as e:
93
+ st.error(f"Error processing {uploaded_file.name}: {str(e)}")
94
+ continue
95
+
96
+ if all_items:
97
+ df = pd.DataFrame(all_items)
98
+ st.subheader("Extracted Menu Items")
99
+ st.dataframe(df)
100
+
101
+ csv = df.to_csv(index=False).encode('utf-8')
102
+ st.download_button("Download CSV", csv, "consolidated_menu.csv", "text/csv")
103
+ else:
104
+ st.warning("No menu items found in the uploaded images")
105
+
106
+ if __name__ == "__main__":
107
+ main()