SURESHBEEKHANI commited on
Commit
22abdaa
Β·
verified Β·
1 Parent(s): 22ea111

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -50
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import streamlit as st
2
  from PIL import Image
 
3
  import os
4
  import base64
5
  import io
@@ -20,6 +21,7 @@ PAGE_CONFIG = {
20
  }
21
 
22
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
 
23
 
24
  CSS_STYLES = """
25
  <style>
@@ -79,6 +81,32 @@ def process_image_data(uploaded_file):
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()
@@ -97,15 +125,13 @@ def generate_pdf_report(report_text):
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",
@@ -141,62 +167,40 @@ def display_main_interface():
141
  st.subheader("AI-Powered Rice Grain Inspection")
142
  st.markdown("---")
143
 
144
- # Display analysis results
145
- if st.session_state.get('analysis_result'):
146
- st.markdown("### πŸ“‹ Analysis Report")
147
- st.markdown(
148
- f'<div class="report-container"><div class="report-text">{st.session_state.analysis_result}</div></div>',
149
- unsafe_allow_html=True
150
- )
151
- pdf_report = generate_pdf_report(st.session_state.analysis_result)
152
- st.download_button(
153
- label="πŸ“„ Download PDF Report",
154
- data=pdf_report,
155
- file_name="rice_quality_report.pdf",
156
- mime="application/pdf"
157
- )
158
-
159
- if st.button("Clear Analysis πŸ—‘οΈ"):
160
- st.session_state.pop('analysis_result', None)
161
- st.rerun()
162
-
163
  def render_sidebar(client):
164
  """Create sidebar interface elements"""
165
  with st.sidebar:
166
- st.markdown("### Features")
167
- st.markdown("""
168
- - **Rice Type Classification** (e.g., Basmati, Jasmine, Indica)
169
- - **Quality Check** (Broken grains %, impurities %, discoloration %)
170
- - **Foreign Object Detection** (Husks, stones, debris)
171
- - **Grain Size & Shape Analysis**
172
- - **Processing Recommendations**
173
- """)
174
- st.markdown("---")
175
-
176
- st.subheader("Upload Rice Image")
177
- uploaded_file = st.file_uploader(
178
- "Select an image of rice grains",
179
- type=ALLOWED_FILE_TYPES
180
- )
181
 
182
  if uploaded_file:
183
- st.image(Image.open(uploaded_file), caption="Uploaded Image", use_column_width=True)
184
- if st.button("Analyze Rice Quality πŸ”"):
185
- with st.spinner("Processing image... This may take a few seconds."):
186
- report = generate_rice_report(uploaded_file, client)
187
- st.session_state.analysis_result = report
188
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  # ======================
191
  # APPLICATION ENTRYPOINT
192
  # ======================
193
  def main():
194
- """Primary application controller"""
195
  configure_application()
196
  groq_client = initialize_api_client()
197
-
198
  display_main_interface()
199
  render_sidebar(groq_client)
200
 
201
  if __name__ == "__main__":
202
- main()
 
1
  import streamlit as st
2
  from PIL import Image
3
+ import cv2
4
  import os
5
  import base64
6
  import io
 
21
  }
22
 
23
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
24
+ ALLOWED_VIDEO_TYPES = ['mp4', 'avi', 'mov']
25
 
26
  CSS_STYLES = """
27
  <style>
 
81
  st.error(f"Image processing error: {str(e)}")
82
  return None, None
83
 
84
+ def extract_video_frames(uploaded_video):
85
+ """Extract frames from uploaded video for analysis"""
86
+ try:
87
+ tfile = io.BytesIO(uploaded_video.read())
88
+ temp_filename = "temp_video.mp4"
89
+ with open(temp_filename, "wb") as f:
90
+ f.write(tfile.getvalue())
91
+
92
+ cap = cv2.VideoCapture(temp_filename)
93
+ frame_list = []
94
+ frame_count = 0
95
+
96
+ while cap.isOpened():
97
+ ret, frame = cap.read()
98
+ if not ret or frame_count > 10: # Process only up to 10 frames
99
+ break
100
+ frame_list.append(frame)
101
+ frame_count += 1
102
+
103
+ cap.release()
104
+ os.remove(temp_filename)
105
+ return frame_list
106
+ except Exception as e:
107
+ st.error(f"Video processing error: {str(e)}")
108
+ return []
109
+
110
  def generate_pdf_report(report_text):
111
  """Generate PDF document from report text"""
112
  buffer = io.BytesIO()
 
125
  buffer.seek(0)
126
  return buffer
127
 
128
+ def generate_rice_report(image_data, img_format, client):
129
  """Generate AI-powered rice quality analysis"""
130
+ if not image_data:
 
 
131
  return None
132
+
133
+ image_url = f"data:image/{img_format.lower()};base64,{image_data}"
134
+
135
  try:
136
  response = client.chat.completions.create(
137
  model="llama-3.2-11b-vision-preview",
 
167
  st.subheader("AI-Powered Rice Grain Inspection")
168
  st.markdown("---")
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  def render_sidebar(client):
171
  """Create sidebar interface elements"""
172
  with st.sidebar:
173
+ st.subheader("Upload Image or Video")
174
+ uploaded_file = st.file_uploader("Select an image or video", type=ALLOWED_FILE_TYPES + ALLOWED_VIDEO_TYPES)
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  if uploaded_file:
177
+ file_type = uploaded_file.type
178
+ if "video" in file_type:
179
+ frames = extract_video_frames(uploaded_file)
180
+ if frames:
181
+ st.image(frames[0], caption="Extracted Frame for Analysis", use_column_width=True)
182
+ frame_img = Image.fromarray(cv2.cvtColor(frames[0], cv2.COLOR_BGR2RGB))
183
+ buffer = io.BytesIO()
184
+ frame_img.save(buffer, format="JPEG")
185
+ base64_image = base64.b64encode(buffer.getvalue()).decode('utf-8')
186
+ report = generate_rice_report(base64_image, "jpeg", client)
187
+ else:
188
+ st.image(Image.open(uploaded_file), caption="Uploaded Image", use_column_width=True)
189
+ base64_image, img_format = process_image_data(uploaded_file)
190
+ report = generate_rice_report(base64_image, img_format, client)
191
+
192
+ if report:
193
+ st.markdown("### πŸ“‹ Analysis Report")
194
+ st.markdown(report)
195
 
196
  # ======================
197
  # APPLICATION ENTRYPOINT
198
  # ======================
199
  def main():
 
200
  configure_application()
201
  groq_client = initialize_api_client()
 
202
  display_main_interface()
203
  render_sidebar(groq_client)
204
 
205
  if __name__ == "__main__":
206
+ main()