Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,232 +1,194 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
from database import db
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 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 |
-
|
| 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 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
document.getElementById('stop-button').addEventListener('click', () => {{
|
| 196 |
-
responsiveVoice.cancel();
|
| 197 |
-
}});
|
| 198 |
-
|
| 199 |
-
// Text selection handler
|
| 200 |
-
document.addEventListener('mouseup', function() {{
|
| 201 |
-
const selection = window.getSelection().toString().trim();
|
| 202 |
-
if(selection) {{
|
| 203 |
-
responsiveVoice.cancel();
|
| 204 |
-
responsiveVoice.speak(selection, "{selected_voice}");
|
| 205 |
-
}}
|
| 206 |
-
}});
|
| 207 |
-
}});
|
| 208 |
-
</script>
|
| 209 |
-
|
| 210 |
-
<style>
|
| 211 |
-
#voice-controls button {{
|
| 212 |
-
margin: 2px;
|
| 213 |
-
padding: 6px 12px;
|
| 214 |
-
background-color: #4CAF50;
|
| 215 |
-
color: white;
|
| 216 |
-
border: none;
|
| 217 |
-
border-radius: 4px;
|
| 218 |
-
cursor: pointer;
|
| 219 |
-
}}
|
| 220 |
-
</style>
|
| 221 |
-
"""
|
| 222 |
-
|
| 223 |
-
# Use Streamlit component to inject the JavaScript
|
| 224 |
-
components.html(responsive_voice_js, height=70)
|
| 225 |
-
|
| 226 |
-
st.info("You can now click 'Read Aloud' to have the text read to you, or select specific text to have it read.")
|
| 227 |
-
else:
|
| 228 |
-
st.error("Text not found. Please check the ID.")
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
if __name__ == "__main__":
|
| 232 |
main()
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from database import db
|
| 3 |
+
from firebase_admin import firestore
|
| 4 |
+
from PyPDF2 import PdfReader
|
| 5 |
+
import easyocr
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
import random
|
| 9 |
+
import string
|
| 10 |
+
import base64
|
| 11 |
+
import os
|
| 12 |
+
import numpy as np
|
| 13 |
+
from mistralai import Mistral
|
| 14 |
+
|
| 15 |
+
def generate_readable_id(length=5):
|
| 16 |
+
"""Generate a random alphanumeric ID."""
|
| 17 |
+
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
|
| 18 |
+
return ''.join(random.choice(characters) for _ in range(length))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def encode_image(image_file):
|
| 22 |
+
"""Encode image to base64."""
|
| 23 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 24 |
+
|
| 25 |
+
def process_mistral_ocr(file, api_key):
|
| 26 |
+
"""Process OCR using Mistral API."""
|
| 27 |
+
client = Mistral(api_key=api_key)
|
| 28 |
+
|
| 29 |
+
if file.type == "application/pdf":
|
| 30 |
+
# Upload the PDF
|
| 31 |
+
uploaded_pdf = client.files.upload(
|
| 32 |
+
file={
|
| 33 |
+
"file_name": file.name,
|
| 34 |
+
"content": file.getvalue(),
|
| 35 |
+
},
|
| 36 |
+
purpose="ocr"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Get OCR results
|
| 40 |
+
ocr_response = client.ocr.process(
|
| 41 |
+
model="mistral-ocr-latest",
|
| 42 |
+
document={
|
| 43 |
+
"type": "document_url",
|
| 44 |
+
"document_url": client.files.get_signed_url(file_id=uploaded_pdf.id).url,
|
| 45 |
+
}
|
| 46 |
+
)
|
| 47 |
+
else:
|
| 48 |
+
# Process Image
|
| 49 |
+
base64_image = encode_image(file)
|
| 50 |
+
ocr_response = client.ocr.process(
|
| 51 |
+
model="mistral-ocr-latest",
|
| 52 |
+
document={
|
| 53 |
+
"type": "image_url",
|
| 54 |
+
"image_url": f"data:image/jpeg;base64,{base64_image}"
|
| 55 |
+
}
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
return ocr_response["text"]
|
| 59 |
+
|
| 60 |
+
def extract_text_from_pdf(file):
|
| 61 |
+
"""Extract text from a PDF file using PyPDF2."""
|
| 62 |
+
reader = PdfReader(file)
|
| 63 |
+
text = ""
|
| 64 |
+
for page in reader.pages:
|
| 65 |
+
text += page.extract_text() or ""
|
| 66 |
+
return text
|
| 67 |
+
|
| 68 |
+
def extract_text_from_image(image):
|
| 69 |
+
"""Extract text from an image using EasyOCR."""
|
| 70 |
+
# Convert PIL Image to numpy array for EasyOCR
|
| 71 |
+
img_array = np.array(image)
|
| 72 |
+
|
| 73 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 74 |
+
results = reader.readtext(img_array)
|
| 75 |
+
return " ".join([result[1] for result in results])
|
| 76 |
+
|
| 77 |
+
def save_text_to_firebase(text):
|
| 78 |
+
"""Save text to Firebase Firestore."""
|
| 79 |
+
try:
|
| 80 |
+
# Generate a readable ID for the text
|
| 81 |
+
text_id = generate_readable_id()
|
| 82 |
+
|
| 83 |
+
# Save the text to Firestore
|
| 84 |
+
db.collection("texts").document(text_id).set({
|
| 85 |
+
"content": text,
|
| 86 |
+
"created_at": firestore.SERVER_TIMESTAMP
|
| 87 |
+
})
|
| 88 |
+
return text_id
|
| 89 |
+
except Exception as e:
|
| 90 |
+
st.error(f"Error saving text to Firebase: {e}")
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
st.title("Text Upload App")
|
| 95 |
+
|
| 96 |
+
# Sidebar for API key configuration
|
| 97 |
+
with st.sidebar:
|
| 98 |
+
st.header("OCR Configuration")
|
| 99 |
+
# Mistral API key input
|
| 100 |
+
mistral_api_key = st.text_input("Enter Mistral API Key:", type="password")
|
| 101 |
+
# Save API key to session state
|
| 102 |
+
if mistral_api_key:
|
| 103 |
+
st.session_state['mistral_api_key'] = mistral_api_key
|
| 104 |
+
|
| 105 |
+
# Select OCR method
|
| 106 |
+
ocr_method = st.radio("Choose OCR method:", ("EasyOCR (Default)", "Mistral OCR (Requires API Key)"))
|
| 107 |
+
|
| 108 |
+
# Select input method
|
| 109 |
+
option = st.radio("Choose input method:", ("Upload Document", "Take Picture"))
|
| 110 |
+
|
| 111 |
+
if option == "Upload Document":
|
| 112 |
+
uploaded_file = st.file_uploader("Upload PDF or Image", type=["pdf", "png", "jpg", "jpeg"])
|
| 113 |
+
|
| 114 |
+
if uploaded_file:
|
| 115 |
+
with st.spinner("Processing document..."):
|
| 116 |
+
if ocr_method == "Mistral OCR (Requires API Key)":
|
| 117 |
+
# Check if API key is available
|
| 118 |
+
if 'mistral_api_key' not in st.session_state or not st.session_state['mistral_api_key']:
|
| 119 |
+
st.error("Please provide a Mistral API key in the sidebar to use Mistral OCR")
|
| 120 |
+
else:
|
| 121 |
+
try:
|
| 122 |
+
# Use Mistral OCR
|
| 123 |
+
text = process_mistral_ocr(uploaded_file, st.session_state['mistral_api_key'])
|
| 124 |
+
except Exception as e:
|
| 125 |
+
st.error(f"Error processing with Mistral OCR: {e}")
|
| 126 |
+
st.info("Falling back to default OCR method...")
|
| 127 |
+
# Fallback to traditional methods
|
| 128 |
+
if uploaded_file.type == "application/pdf":
|
| 129 |
+
text = extract_text_from_pdf(uploaded_file)
|
| 130 |
+
else:
|
| 131 |
+
# Reset file pointer to beginning
|
| 132 |
+
uploaded_file.seek(0)
|
| 133 |
+
image = Image.open(uploaded_file)
|
| 134 |
+
text = extract_text_from_image(image)
|
| 135 |
+
else:
|
| 136 |
+
# Use traditional methods
|
| 137 |
+
if uploaded_file.type == "application/pdf":
|
| 138 |
+
text = extract_text_from_pdf(uploaded_file)
|
| 139 |
+
else:
|
| 140 |
+
# Reset file pointer to beginning
|
| 141 |
+
uploaded_file.seek(0)
|
| 142 |
+
image = Image.open(uploaded_file)
|
| 143 |
+
text = extract_text_from_image(image)
|
| 144 |
+
|
| 145 |
+
if 'text' in locals() and text and text.strip():
|
| 146 |
+
# Show extracted text
|
| 147 |
+
with st.expander("View Extracted Text"):
|
| 148 |
+
st.write(text)
|
| 149 |
+
|
| 150 |
+
# Save text to Firebase
|
| 151 |
+
text_id = save_text_to_firebase(text)
|
| 152 |
+
if text_id:
|
| 153 |
+
st.success(f"Text extracted! Your Document ID: **{text_id}**")
|
| 154 |
+
else:
|
| 155 |
+
st.warning("No text could be extracted")
|
| 156 |
+
|
| 157 |
+
elif option == "Take Picture":
|
| 158 |
+
picture = st.camera_input("Take a picture")
|
| 159 |
+
|
| 160 |
+
if picture:
|
| 161 |
+
with st.spinner("Processing image..."):
|
| 162 |
+
if ocr_method == "Mistral OCR (Requires API Key)":
|
| 163 |
+
# Check if API key is available
|
| 164 |
+
if 'mistral_api_key' not in st.session_state or not st.session_state['mistral_api_key']:
|
| 165 |
+
st.error("Please provide a Mistral API key in the sidebar to use Mistral OCR")
|
| 166 |
+
else:
|
| 167 |
+
try:
|
| 168 |
+
# Use Mistral OCR
|
| 169 |
+
text = process_mistral_ocr(picture, st.session_state['mistral_api_key'])
|
| 170 |
+
except Exception as e:
|
| 171 |
+
st.error(f"Error processing with Mistral OCR: {e}")
|
| 172 |
+
st.info("Falling back to default OCR method...")
|
| 173 |
+
# Fallback to EasyOCR
|
| 174 |
+
image = Image.open(BytesIO(picture.getvalue()))
|
| 175 |
+
text = extract_text_from_image(image)
|
| 176 |
+
else:
|
| 177 |
+
# Use EasyOCR
|
| 178 |
+
image = Image.open(BytesIO(picture.getvalue()))
|
| 179 |
+
text = extract_text_from_image(image)
|
| 180 |
+
|
| 181 |
+
if 'text' in locals() and text and text.strip():
|
| 182 |
+
# Show extracted text
|
| 183 |
+
with st.expander("View Extracted Text"):
|
| 184 |
+
st.write(text)
|
| 185 |
+
|
| 186 |
+
# Save text to Firebase
|
| 187 |
+
text_id = save_text_to_firebase(text)
|
| 188 |
+
if text_id:
|
| 189 |
+
st.success(f"Text extracted! Your Document ID: **{text_id}**")
|
| 190 |
+
else:
|
| 191 |
+
st.warning("No text could be extracted")
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
main()
|