|
import streamlit as st |
|
from PIL import Image |
|
import cv2 |
|
import os |
|
import base64 |
|
import io |
|
import pandas as pd |
|
from dotenv import load_dotenv |
|
from groq import Groq |
|
from reportlab.lib.pagesizes import letter |
|
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer |
|
from reportlab.lib.styles import getSampleStyleSheet |
|
|
|
|
|
|
|
|
|
PAGE_CONFIG = { |
|
"page_title": "Rice Quality Analyzer", |
|
"page_icon": "πΎ", |
|
"layout": "wide", |
|
"initial_sidebar_state": "expanded" |
|
} |
|
|
|
ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg'] |
|
ALLOWED_VIDEO_TYPES = ['mp4', 'avi', 'mov'] |
|
|
|
CSS_STYLES = """ |
|
<style> |
|
.main { background-color: #f4f9f9; color: #000000; } |
|
.sidebar .sidebar-content { background-color: #d1e7dd; } |
|
.stTextInput textarea { color: #000000 !important; } |
|
.stButton>button { |
|
background-color: #21eeef; |
|
color: white; |
|
font-size: 16px; |
|
border-radius: 5px; |
|
} |
|
.report-container { |
|
background-color: #ffffff; |
|
border-radius: 15px; |
|
padding: 20px; |
|
margin-top: 20px; |
|
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); |
|
border-left: 5px solid #21eeef; |
|
} |
|
.report-text { |
|
font-family: 'Arial', sans-serif; |
|
font-size: 14px; |
|
line-height: 1.6; |
|
color: #2c3e50; |
|
} |
|
</style> |
|
""" |
|
|
|
|
|
|
|
|
|
def configure_application(): |
|
"""Initialize application settings and styling""" |
|
st.set_page_config(**PAGE_CONFIG) |
|
st.markdown(CSS_STYLES, unsafe_allow_html=True) |
|
|
|
def initialize_api_client(): |
|
"""Create and validate Groq API client""" |
|
load_dotenv() |
|
api_key = os.getenv("GROQ_API_KEY") |
|
|
|
if not api_key: |
|
st.error("API key not found. Please verify .env configuration.") |
|
st.stop() |
|
|
|
return Groq(api_key=api_key) |
|
|
|
def process_image_data(uploaded_file): |
|
"""Convert image to base64 encoded string""" |
|
try: |
|
image = Image.open(uploaded_file) |
|
buffer = io.BytesIO() |
|
image.save(buffer, format=image.format) |
|
return base64.b64encode(buffer.getvalue()).decode('utf-8'), image.format |
|
except Exception as e: |
|
st.error(f"Image processing error: {str(e)}") |
|
return None, None |
|
|
|
def generate_rice_report(image_data, img_format, client): |
|
"""Generate AI-powered rice quality analysis""" |
|
if not image_data: |
|
return None |
|
|
|
image_url = f"data:image/{img_format.lower()};base64,{image_data}" |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model="llama-3.2-11b-vision-preview", |
|
messages=[{ |
|
"role": "user", |
|
"content": [ |
|
{"type": "text", "text": ( |
|
"Analyze the rice grain image and provide a detailed report including:", |
|
"Rice type classification", |
|
"Quality assessment (broken grains %, discoloration %, impurities %)", |
|
"Foreign object detection", |
|
"Size and shape consistency", |
|
"Recommendations for processing or improvement" |
|
)}, |
|
{"type": "image_url", "image_url": {"url": image_url}}, |
|
] |
|
}], |
|
temperature=0.2, |
|
max_tokens=400, |
|
top_p=0.5 |
|
) |
|
return response.choices[0].message.content |
|
except Exception as e: |
|
st.error(f"API communication error: {str(e)}") |
|
return None |
|
|
|
def format_report_as_table(report_text): |
|
"""Convert report text into structured table format""" |
|
rows = [row.split(': ') for row in report_text.split('\n') if ': ' in row] |
|
df = pd.DataFrame(rows, columns=["Category", "Details"]) |
|
return df |
|
|
|
def display_main_interface(): |
|
"""Render primary application interface""" |
|
st.title("πΎ Rice Quality Analyzer") |
|
st.subheader("AI-Powered Rice Grain Inspection") |
|
st.markdown("---") |
|
|
|
def render_sidebar(client): |
|
"""Create sidebar interface elements""" |
|
with st.sidebar: |
|
st.subheader("Upload Image") |
|
uploaded_file = st.file_uploader("Select an image", type=ALLOWED_FILE_TYPES) |
|
|
|
if uploaded_file: |
|
base64_image, img_format = process_image_data(uploaded_file) |
|
report = generate_rice_report(base64_image, img_format, client) |
|
|
|
if report: |
|
st.session_state.analysis_result = report |
|
st.rerun() |
|
|
|
if "analysis_result" in st.session_state: |
|
st.markdown("### π Analysis Report") |
|
report_df = format_report_as_table(st.session_state.analysis_result) |
|
st.table(report_df) |
|
|
|
def main(): |
|
configure_application() |
|
groq_client = initialize_api_client() |
|
display_main_interface() |
|
render_sidebar(groq_client) |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|