Update app.py
Browse files
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 |
-
#
|
14 |
-
#
|
15 |
-
|
16 |
-
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
.
|
28 |
-
.
|
29 |
-
.
|
30 |
-
|
31 |
-
color:
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
font-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
# ======================
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
story
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
st.
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|