SURESHBEEKHANI commited on
Commit
a4600c1
Β·
verified Β·
1 Parent(s): d44ba7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -34
app.py CHANGED
@@ -1,10 +1,8 @@
1
  import streamlit as st
2
  from PIL import Image
3
- import cv2
4
  import os
5
  import base64
6
  import io
7
- import pandas as pd
8
  from dotenv import load_dotenv
9
  from groq import Groq
10
  from reportlab.lib.pagesizes import letter
@@ -22,7 +20,6 @@ PAGE_CONFIG = {
22
  }
23
 
24
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
25
- ALLOWED_VIDEO_TYPES = ['mp4', 'avi', 'mov']
26
 
27
  CSS_STYLES = """
28
  <style>
@@ -82,13 +79,33 @@ def process_image_data(uploaded_file):
82
  st.error(f"Image processing error: {str(e)}")
83
  return None, None
84
 
85
- def generate_rice_report(image_data, img_format, client):
86
- """Generate AI-powered rice quality analysis"""
87
- if not image_data:
88
- return None
 
 
 
 
 
 
89
 
90
- image_url = f"data:image/{img_format.lower()};base64,{image_data}"
 
 
 
 
 
 
 
 
 
91
 
 
 
 
 
 
92
  try:
93
  response = client.chat.completions.create(
94
  model="llama-3.2-11b-vision-preview",
@@ -96,12 +113,9 @@ def generate_rice_report(image_data, img_format, client):
96
  "role": "user",
97
  "content": [
98
  {"type": "text", "text": (
99
- "Analyze the rice grain image and provide a detailed report including:",
100
- "Rice type classification",
101
- "Quality assessment (broken grains %, discoloration %, impurities %)",
102
- "Foreign object detection",
103
- "Size and shape consistency",
104
- "Recommendations for processing or improvement"
105
  )},
106
  {"type": "image_url", "image_url": {"url": image_url}},
107
  ]
@@ -115,42 +129,71 @@ def generate_rice_report(image_data, img_format, client):
115
  st.error(f"API communication error: {str(e)}")
116
  return None
117
 
118
- def format_report_as_table(report_text):
119
- """Convert report text into structured table format"""
120
- rows = [row.split(': ') for row in report_text.split('\n') if ': ' in row]
121
- df = pd.DataFrame(rows, columns=["Category", "Details"])
122
- return df
123
-
124
  def display_main_interface():
125
  """Render primary application interface"""
126
  st.title("🌾 Rice Quality Analyzer")
127
  st.subheader("AI-Powered Rice Grain Inspection")
128
  st.markdown("---")
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def render_sidebar(client):
131
  """Create sidebar interface elements"""
132
  with st.sidebar:
133
- st.subheader("Upload Image")
134
- uploaded_file = st.file_uploader("Select an image", type=ALLOWED_FILE_TYPES)
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  if uploaded_file:
137
- base64_image, img_format = process_image_data(uploaded_file)
138
- report = generate_rice_report(base64_image, img_format, client)
139
-
140
- if report:
141
- st.session_state.analysis_result = report
142
- st.rerun()
143
-
144
- if "analysis_result" in st.session_state:
145
- st.markdown("### πŸ“‹ Analysis Report")
146
- report_df = format_report_as_table(st.session_state.analysis_result)
147
- st.table(report_df)
148
 
 
 
 
149
  def main():
 
150
  configure_application()
151
  groq_client = initialize_api_client()
 
152
  display_main_interface()
153
  render_sidebar(groq_client)
154
 
155
  if __name__ == "__main__":
156
- 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
 
20
  }
21
 
22
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
 
23
 
24
  CSS_STYLES = """
25
  <style>
 
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",
 
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
  ]
 
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()