SURESHBEEKHANI commited on
Commit
54f826c
Β·
verified Β·
1 Parent(s): 6f65288

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -199
app.py CHANGED
@@ -1,199 +1,160 @@
1
- import streamlit as st
2
- from PIL import Image
3
- import os
4
- import base64
5
- import io
6
- from dotenv import load_dotenv
7
- from groq import Groq
8
- from reportlab.lib.pagesizes import letter
9
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
10
- from reportlab.lib.styles import getSampleStyleSheet
11
-
12
- # ======================
13
- # CONFIGURATION SETTINGS
14
- # ======================
15
- PAGE_CONFIG = {
16
- "page_title": "Rice Quality Analyzer",
17
- "page_icon": "🌾",
18
- "layout": "wide",
19
- "initial_sidebar_state": "expanded"
20
- }
21
-
22
- ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
23
-
24
- CSS_STYLES = """
25
- <style>
26
- .main { background-color: #f4f9f9; color: #000000; }
27
- .sidebar .sidebar-content { background-color: #d1e7dd; }
28
- .stTextInput textarea { color: #000000 !important; }
29
- .stButton>button {
30
- background-color: #21eeef;
31
- color: white;
32
- font-size: 16px;
33
- border-radius: 5px;
34
- }
35
- .report-container {
36
- background-color: #ffffff;
37
- border-radius: 15px;
38
- padding: 20px;
39
- margin-top: 20px;
40
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
41
- border-left: 5px solid #21eeef;
42
- }
43
- .report-text {
44
- font-family: 'Arial', sans-serif;
45
- font-size: 14px;
46
- line-height: 1.6;
47
- color: #2c3e50;
48
- }
49
- </style>
50
- """
51
-
52
- # ======================
53
- # CORE FUNCTIONS
54
- # ======================
55
- def configure_application():
56
- """Initialize application settings and styling"""
57
- st.set_page_config(**PAGE_CONFIG)
58
- st.markdown(CSS_STYLES, unsafe_allow_html=True)
59
-
60
- def initialize_api_client():
61
- """Create and validate Groq API client"""
62
- load_dotenv()
63
- api_key = os.getenv("GROQ_API_KEY")
64
-
65
- if not api_key:
66
- st.error("API key not found. Please verify .env configuration.")
67
- st.stop()
68
-
69
- return Groq(api_key=api_key)
70
-
71
- def process_image_data(uploaded_file):
72
- """Convert image to base64 encoded string"""
73
- try:
74
- image = Image.open(uploaded_file)
75
- buffer = io.BytesIO()
76
- image.save(buffer, format=image.format)
77
- return base64.b64encode(buffer.getvalue()).decode('utf-8'), image.format
78
- except Exception as e:
79
- st.error(f"Image processing error: {str(e)}")
80
- return None, None
81
-
82
- def generate_pdf_report(report_text):
83
- """Generate PDF document from report text"""
84
- buffer = io.BytesIO()
85
- doc = SimpleDocTemplate(buffer, pagesize=letter)
86
- styles = getSampleStyleSheet()
87
- story = []
88
-
89
- title = Paragraph("<b>Rice Quality Report</b>", styles['Title'])
90
- story.append(title)
91
- story.append(Spacer(1, 12))
92
-
93
- content = Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
94
- story.append(content)
95
-
96
- doc.build(story)
97
- buffer.seek(0)
98
- return buffer
99
-
100
- def generate_rice_report(uploaded_file, client):
101
- """Generate AI-powered rice quality analysis"""
102
- base64_image, img_format = process_image_data(uploaded_file)
103
-
104
- if not base64_image:
105
- return None
106
-
107
- image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
108
-
109
- try:
110
- response = client.chat.completions.create(
111
- model="llama-3.2-11b-vision-preview",
112
- messages=[{
113
- "role": "user",
114
- "content": [
115
- {"type": "text", "text": (
116
- "Analyze the rice grain image and provide a detailed report including:\n"
117
- "1. Rice type classification\n2. Quality assessment (broken grains %, discoloration %, impurities %)\n"
118
- "3. Foreign object detection\n4. Size and shape consistency\n5. Recommendations for processing or improvement"
119
- )},
120
- {"type": "image_url", "image_url": {"url": image_url}},
121
- ]
122
- }],
123
- temperature=0.2,
124
- max_tokens=400,
125
- top_p=0.5
126
- )
127
- return response.choices[0].message.content
128
- except Exception as e:
129
- st.error(f"API communication error: {str(e)}")
130
- return None
131
-
132
- # ======================
133
- # UI COMPONENTS
134
- # ======================
135
- def display_main_interface():
136
- """Render primary application interface"""
137
- st.title("🌾 Rice Quality Analyzer")
138
- st.subheader("AI-Powered Rice Grain Inspection")
139
- st.markdown("---")
140
-
141
- # Display analysis results
142
- if st.session_state.get('analysis_result'):
143
- st.markdown("### πŸ“‹ Analysis Report")
144
- st.markdown(
145
- f'<div class="report-container"><div class="report-text">{st.session_state.analysis_result}</div></div>',
146
- unsafe_allow_html=True
147
- )
148
- pdf_report = generate_pdf_report(st.session_state.analysis_result)
149
- st.download_button(
150
- label="πŸ“„ Download PDF Report",
151
- data=pdf_report,
152
- file_name="rice_quality_report.pdf",
153
- mime="application/pdf"
154
- )
155
-
156
- if st.button("Clear Analysis πŸ—‘οΈ"):
157
- st.session_state.pop('analysis_result', None)
158
- st.rerun()
159
-
160
- def render_sidebar(client):
161
- """Create sidebar interface elements"""
162
- with st.sidebar:
163
- st.markdown("### Features")
164
- st.markdown("""
165
- - **Rice Type Classification** (e.g., Basmati, Jasmine, Indica)
166
- - **Quality Check** (Broken grains %, impurities %, discoloration %)
167
- - **Foreign Object Detection** (Husks, stones, debris)
168
- - **Grain Size & Shape Analysis**
169
- - **Processing Recommendations**
170
- """)
171
- st.markdown("---")
172
-
173
- st.subheader("Upload Rice Image")
174
- uploaded_file = st.file_uploader(
175
- "Select an image of rice grains",
176
- type=ALLOWED_FILE_TYPES
177
- )
178
-
179
- if uploaded_file:
180
- st.image(Image.open(uploaded_file), caption="Uploaded Image", use_column_width=True)
181
- if st.button("Analyze Rice Quality πŸ”"):
182
- with st.spinner("Processing image... This may take a few seconds."):
183
- report = generate_rice_report(uploaded_file, client)
184
- st.session_state.analysis_result = report
185
- st.rerun()
186
-
187
- # ======================
188
- # APPLICATION ENTRYPOINT
189
- # ======================
190
- def main():
191
- """Primary application controller"""
192
- configure_application()
193
- groq_client = initialize_api_client()
194
-
195
- display_main_interface()
196
- render_sidebar(groq_client)
197
-
198
- if __name__ == "__main__":
199
- main()
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import os
4
+ import base64
5
+ import io
6
+ from dotenv import load_dotenv
7
+ from groq import Groq
8
+ from reportlab.lib.pagesizes import letter
9
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
10
+ from reportlab.lib.styles import getSampleStyleSheet
11
+ import pandas as pd
12
+
13
+ # ======================
14
+ # CONFIGURATION SETTINGS
15
+ # ======================
16
+ st.set_page_config(
17
+ page_title="Rice Quality Analyzer",
18
+ page_icon="🌾",
19
+ layout="wide",
20
+ initial_sidebar_state="expanded"
21
+ )
22
+
23
+ ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
24
+
25
+ CSS_STYLES = """
26
+ <style>
27
+ .main { background-color: #f4f9f9; color: #000000; }
28
+ .sidebar .sidebar-content { background-color: #d1e7dd; }
29
+ .stTextInput textarea { color: #000000 !important; }
30
+ .stButton>button {
31
+ background-color: #21eeef;
32
+ color: white;
33
+ font-size: 16px;
34
+ border-radius: 5px;
35
+ }
36
+ .report-container {
37
+ background-color: #ffffff;
38
+ border-radius: 15px;
39
+ padding: 20px;
40
+ margin-top: 20px;
41
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
42
+ border-left: 5px solid #21eeef;
43
+ }
44
+ .report-text {
45
+ font-family: 'Arial', sans-serif;
46
+ font-size: 14px;
47
+ line-height: 1.6;
48
+ color: #2c3e50;
49
+ }
50
+ </style>
51
+ """
52
+ st.markdown(CSS_STYLES, unsafe_allow_html=True)
53
+
54
+ # ======================
55
+ # CORE FUNCTIONS
56
+ # ======================
57
+ def initialize_api_client():
58
+ """Initialize and validate the Groq API client."""
59
+ load_dotenv()
60
+ api_key = os.getenv("GROQ_API_KEY")
61
+ if not api_key:
62
+ st.error("API key not found. Please check .env configuration.")
63
+ st.stop()
64
+ return Groq(api_key=api_key)
65
+
66
+ def process_image_data(uploaded_file):
67
+ """Convert image to base64 encoded string."""
68
+ try:
69
+ image = Image.open(uploaded_file)
70
+ buffer = io.BytesIO()
71
+ image.save(buffer, format=image.format)
72
+ return base64.b64encode(buffer.getvalue()).decode('utf-8'), image.format
73
+ except Exception as e:
74
+ st.error(f"Image processing error: {str(e)}")
75
+ return None, None
76
+
77
+ def generate_pdf_report(report_text):
78
+ """Generate a PDF report from the analysis text."""
79
+ buffer = io.BytesIO()
80
+ doc = SimpleDocTemplate(buffer, pagesize=letter)
81
+ styles = getSampleStyleSheet()
82
+ story = [
83
+ Paragraph("<b>Rice Quality Report</b>", styles['Title']),
84
+ Spacer(1, 12),
85
+ Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
86
+ ]
87
+ doc.build(story)
88
+ buffer.seek(0)
89
+ return buffer
90
+
91
+ def generate_rice_report(uploaded_file, client):
92
+ """Generate AI-powered rice quality analysis."""
93
+ base64_image, img_format = process_image_data(uploaded_file)
94
+ if not base64_image:
95
+ return None
96
+
97
+ image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
98
+
99
+ try:
100
+ response = client.chat.completions.create(
101
+ model="llama-3.2-11b-vision-preview",
102
+ messages=[
103
+ {"role": "user", "content": [
104
+ {"type": "text", "text": (
105
+ "Analyze the rice grain image and provide a structured report including:"
106
+ )},
107
+ {"type": "image_url", "image_url": {"url": image_url}},
108
+ ]}
109
+ ],
110
+ temperature=0.2,
111
+ max_tokens=400,
112
+ top_p=0.5
113
+ )
114
+ return response.choices[0].message.content
115
+ except Exception as e:
116
+ st.error(f"API communication error: {str(e)}")
117
+ return None
118
+
119
+ # ======================
120
+ # UI COMPONENTS
121
+ # ======================
122
+ def display_main_interface():
123
+ """Render primary application interface."""
124
+ st.title("🌾 Rice Quality Analyzer")
125
+ st.subheader("AI-Powered Rice Grain Inspection")
126
+ st.markdown("---")
127
+
128
+ st.markdown("### Key Benefits:")
129
+ st.markdown("- Reduces inspection time by a factor of 10")
130
+ st.markdown("- Simple 3-step process: Load sample β†’ Click start β†’ Get results")
131
+ st.markdown("- Results stored in a database for traceability and further analysis")
132
+ st.markdown("- Integration with 3rd party instruments for higher-level data analysis")
133
+ st.markdown("- No minimum sample size required")
134
+ st.markdown("- No complicated sample preparation needed")
135
+
136
+ if 'analysis_result' in st.session_state:
137
+ st.markdown("### πŸ“‹ Analysis Report")
138
+ report_data = st.session_state.analysis_result
139
+ df = pd.DataFrame(report_data.items(), columns=["Metric", "Value"])
140
+ st.table(df)
141
+
142
+ pdf_report = generate_pdf_report(str(report_data))
143
+ st.download_button(
144
+ label="πŸ“„ Download PDF Report",
145
+ data=pdf_report,
146
+ file_name="rice_quality_report.pdf",
147
+ mime="application/pdf"
148
+ )
149
+
150
+ if st.button("Clear Analysis πŸ—‘οΈ"):
151
+ st.session_state.pop('analysis_result', None)
152
+ st.rerun()
153
+
154
+ def main():
155
+ """Primary application controller."""
156
+ groq_client = initialize_api_client()
157
+ display_main_interface()
158
+
159
+ if __name__ == "__main__":
160
+ main()