import streamlit as st from transformers import AutoModel from PIL import Image import torch import numpy as np import urllib.request # Load the model without caching to avoid serialization issues def load_model(): model = AutoModel.from_pretrained("ragavsachdeva/magi", trust_remote_code=True) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) return model # Initialize the model once at the top level, outside any caching functions model = load_model() @st.cache_data def read_image_as_np_array(image_path): if "http" in image_path: image = Image.open(urllib.request.urlopen(image_path)).convert("L").convert("RGB") else: image = Image.open(image_path).convert("L").convert("RGB") image = np.array(image) return image @st.cache_data def predict_detections_and_associations( image_path, character_detection_threshold, panel_detection_threshold, text_detection_threshold, character_character_matching_threshold, text_character_matching_threshold, ): image = read_image_as_np_array(image_path) with torch.no_grad(): result = model.predict_detections_and_associations( [image], character_detection_threshold=character_detection_threshold, panel_detection_threshold=panel_detection_threshold, text_detection_threshold=text_detection_threshold, character_character_matching_threshold=character_character_matching_threshold, text_character_matching_threshold=text_character_matching_threshold, )[0] return result @st.cache_data def predict_ocr( image_path, character_detection_threshold, panel_detection_threshold, text_detection_threshold, character_character_matching_threshold, text_character_matching_threshold, ): if not generate_transcript: return image = read_image_as_np_array(image_path) result = predict_detections_and_associations( path_to_image, character_detection_threshold, panel_detection_threshold, text_detection_threshold, character_character_matching_threshold, text_character_matching_threshold, ) text_bboxes_for_all_images = [result["texts"]] with torch.no_grad(): ocr_results = model.predict_ocr([image], text_bboxes_for_all_images) return ocr_results # Streamlit UI elements st.markdown("""