import streamlit as st
import pytesseract
from PIL import Image
import PyPDF2

import requests
import streamlit as st

# Hugging Face API token (replace with your own)
HF_TOKEN = "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"
headers = {"Authorization": f"Bearer {HF_TOKEN}"}

API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-mnli"  

def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

st.title("AI Medical Prescription Verifier")

user_input = st.text_area("Paste prescription text here:")

if st.button("Verify"):
    if user_input.strip():
        result = query({"inputs": user_input})
        st.write(result)
    else:
        st.warning("Please enter prescription text.")

)

st.write(response.json())




headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}

st.set_page_config(page_title="AI Prescription Verifier", page_icon="🩺", layout="wide")

st.markdown(
    """
    <style>
    body {
        background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
        color: white;
        font-family: 'Segoe UI', sans-serif;
    }
    .main-title {
        font-size: 36px;
        font-weight: bold;
        text-align: center;
        color: #00e6e6;
        padding: 20px;
    }
    .sub-title {
        font-size: 20px;
        text-align: center;
        color: #b3f0ff;
        margin-bottom: 20px;
    }
    .upload-card {
        background: rgba(255,255,255,0.05);
        padding: 20px;
        border-radius: 15px;
        box-shadow: 0px 4px 15px rgba(0,0,0,0.3);
        text-align: center;
    }
    .bot-response {
        background: rgba(0, 230, 230, 0.1);
        padding: 15px;
        border-radius: 10px;
        margin-top: 15px;
        border-left: 5px solid #00e6e6;
    }
    </style>
    """,
    unsafe_allow_html=True
)
# ===========================
# Animated Heading
# ===========================
st.markdown('<div class="main-title">🤖 AI Medical Prescription Verifier</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-title">Upload your prescription and let AI validate & extract important details!</div>', unsafe_allow_html=True)

# ===========================
# File Uploader
# ===========================
st.markdown('<div class="upload-card">', unsafe_allow_html=True)
uploaded_file = st.file_uploader(
    "📤 Upload Prescription", 
    type=["jpg", "png", "jpeg", "pdf", "txt"]
)
st.markdown('</div>', unsafe_allow_html=True)

# ===========================
# Processing
# ===========================
if uploaded_file:
    file_details = {
        "Filename": uploaded_file.name,
        "FileType": uploaded_file.type,
        "FileSize": f"{uploaded_file.size/1024:.2f} KB"
    }
    st.json(file_details)

    extracted_text = ""

    if uploaded_file.type == "application/pdf":
        pdf_reader = PyPDF2.PdfReader(uploaded_file)
        for page in pdf_reader.pages:
            extracted_text += page.extract_text() or ""

    elif uploaded_file.type.startswith("image/"):
        image = Image.open(uploaded_file)
        st.image(image, caption="Uploaded Prescription", use_column_width=True)
        extracted_text = pytesseract.image_to_string(image)

    elif uploaded_file.type == "text/plain":
        extracted_text = uploaded_file.read().decode("utf-8")

    # Show output like a bot response
    if extracted_text.strip():
        st.markdown(f'<div class="bot-response">🤖 <b>AI Extracted Content:</b><br>{extracted_text}</div>', unsafe_allow_html=True)
    else:
        st.warning("⚠️ No readable text found in the file.")
import streamlit as st
import pytesseract
from PIL import Image
import PyPDF2

# Page Config
st.set_page_config(page_title="AI Medical Prescription Verifier", page_icon="🩺", layout="wide")

# Sidebar
with st.sidebar:
    st.title("🩺 AI Prescription Bot")
    st.markdown("**Project:** Medical Prescription Verification")
    st.markdown("This tool verifies prescriptions using OCR & AI to ensure patient safety.")
    st.markdown("---")
    st.info("Upload an image, PDF, or TXT file of a prescription and let the AI assistant verify it.")

# Main Title
st.markdown("<h1 style='text-align: center; color: #2E86C1;'>🤖 AI Medical Prescription Assistant</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center;'>Your smart healthcare buddy to verify prescriptions 📑</p>", unsafe_allow_html=True)
st.write("")

# Chatbot Style Message Boxes
def bot_message(message):
    st.markdown(f"""
    <div style="background-color:#EAF2F8; padding:10px; border-radius:10px; margin:5px 0;">
        🤖 <b>Bot:</b> {message}
    </div>
    """, unsafe_allow_html=True)

def user_message(message):
    st.markdown(f"""
    <div style="background-color:#FDEDEC; padding:10px; border-radius:10px; margin:5px 0; text-align:right;">
        👤 <b>You:</b> {message}
    </div>
    """, unsafe_allow_html=True)

# Bot Greeting
bot_message("Hello! Please upload your prescription (PDF, Image, or TXT) for verification.")

# File Uploader
uploaded_file = st.file_uploader(
    "📤 Upload Prescription", 
    type=["jpg", "png", "jpeg", "pdf", "txt"], 
    key="prescription_upload"
)


if uploaded_file:
    # Show File Details
    file_details = {
        "Filename": uploaded_file.name,
        "FileType": uploaded_file.type,
        "FileSize": uploaded_file.size
    }
    st.json(file_details)

    user_message(f"I uploaded a file: **{uploaded_file.name}**")
    text = ""

    # Handle PDF
    if uploaded_file.type == "application/pdf":
        bot_message("Processing PDF file... 📄")
        pdf_reader = PyPDF2.PdfReader(uploaded_file)
        for page in pdf_reader.pages:
            text += page.extract_text() or ""

    # Handle Image
    elif uploaded_file.type.startswith("image/"):
        bot_message("Processing image file... 🖼️ Running OCR...")
        image = Image.open(uploaded_file)
        st.image(image, caption="Uploaded Prescription", use_column_width=True)
        text = pytesseract.image_to_string(image)

    # Handle TXT
    elif uploaded_file.type == "text/plain":
        bot_message("Reading text file... 📝")
        text = uploaded_file.read().decode("utf-8")

    else:
        st.error("❌ Unsupported file format. Please upload PDF, Image, or TXT.")
        bot_message("Sorry, I don’t recognize this file format.")
    
    # Display Extracted Text
    if text.strip():
        st.success("✅ Extracted Text")
        st.text_area("📝 Prescription Content", text, height=200)
        bot_message("Here’s what I found in your prescription. Do you want me to verify medicines?")
    else:
        st.error("⚠️ Could not extract text. Please try again with a clearer file.")
        bot_message("Hmm... I couldn't read the prescription clearly.")
