import streamlit as st from PIL import Image import tempfile from preprocessing.process import modify_image from model.loader import ImageProcessor from text_classifier.classifier import extract_medical_info, extract_and_save_medical_info from search.extractor import get_medication_details import os # ✅ Must be the first Streamlit command st.set_page_config(page_title="Medical Image Analyzer", page_icon="🔍", layout="wide") # Title st.title("Medical Image Text Analyzer") # Image upload widget uploaded_image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg", "gif", "webp"]) # If an image is uploaded if uploaded_image: # Show the uploaded image image = Image.open(uploaded_image) st.image(image, caption="Uploaded Image", use_column_width=True) # Process the image when the button is clicked if st.button("Analyze Image"): try: # Save the image temporarily to disk with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file: image.save(temp_file.name) # Image processing (preprocessing steps: grayscale, sharpen, enhance contrast) processed_image = modify_image(temp_file.name) if processed_image is not None: st.image(processed_image, caption="Processed Image", use_column_width=True) # Use the loader to analyze the image and get the markdown content processor = ImageProcessor() markdown_result = processor.analyze_image(image_path=temp_file.name) # Extract the text data from the markdown result medical_info = extract_medical_info(markdown_result) # Optional: Save to file extract_and_save_medical_info(markdown_result) # Display the extracted medical information st.subheader("Extracted Medical Information") if isinstance(medical_info, dict): st.json(medical_info) # Get medication details (with fuzzy matching) medications = medical_info.get("medications", []) medication_details_df = get_medication_details(medications) # Display the extracted medical information st.subheader("Extracted Medical Information") if isinstance(medical_info, dict): st.json(medical_info) # Get medication details (with fuzzy matching) medications = medical_info.get("medications", []) medication_details_df = get_medication_details(medications) # Display the medication details as a table st.subheader("Medication Details") # Loop over each medication and render it in a styled box for _, row in medication_details_df.iterrows(): st.markdown( f"""

🩺 {row['Name']}

Contains: {row['Contains']}

How to Use: {row['How to Use']}

Advice:
{row['Advice']}

🔗 More Info

""", unsafe_allow_html=True ) else: st.error("Failed to extract medical information.") # ✅ Cleanup if os.path.exists(temp_file.name): os.remove(temp_file.name) except Exception as e: st.error(f"Error analyzing image: {str(e)}")