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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
iface.launch(share=True)
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
from transformers import VisionEncoderDecoderModel, TrOCRProcessor
|
| 5 |
+
import numpy as np
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
|
| 9 |
+
# Configuration
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class ModelConfig:
|
| 12 |
+
MODEL_TYPE: str = 'large' # small|base|large
|
| 13 |
+
MODEL_NAME: str = f'microsoft/trocr-{MODEL_TYPE}-printed'
|
| 14 |
+
MODEL_PATH: str = 'ocr_model_large_2024-07-25_15_32.pt'
|
| 15 |
+
YOLO_MODEL_PATH = "yolov_pbo1.pt"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Initialisation du dispositif
|
| 19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
+
|
| 21 |
+
# Chargement du modèle TrOCR
|
| 22 |
+
trained_model = VisionEncoderDecoderModel.from_pretrained(ModelConfig.MODEL_NAME)
|
| 23 |
+
trained_model.load_state_dict(torch.load(ModelConfig.MODEL_PATH, map_location=device))
|
| 24 |
+
trained_model.to(device)
|
| 25 |
+
trained_model.eval()
|
| 26 |
+
|
| 27 |
+
# Chargement du processeur TrOCR
|
| 28 |
+
processor = TrOCRProcessor.from_pretrained(ModelConfig.MODEL_NAME)
|
| 29 |
+
|
| 30 |
+
# Chargement du modèle YOLO
|
| 31 |
+
yolo_model = YOLO(ModelConfig.YOLO_MODEL_PATH)
|
| 32 |
+
|
| 33 |
+
def resize_image(image, max_size=1024):
|
| 34 |
+
image.thumbnail((max_size, max_size))
|
| 35 |
+
return image
|
| 36 |
+
|
| 37 |
+
# Fonction d'inférence avec visualisation
|
| 38 |
+
def ocr(image):
|
| 39 |
+
try:
|
| 40 |
+
image = resize_image(image)
|
| 41 |
+
image = Image.fromarray(np.array(image))
|
| 42 |
+
|
| 43 |
+
# Détection d'objets avec YOLO
|
| 44 |
+
results = yolo_model(image)
|
| 45 |
+
|
| 46 |
+
# Création d'un objet ImageDraw pour dessiner les boîtes
|
| 47 |
+
draw = ImageDraw.Draw(image)
|
| 48 |
+
|
| 49 |
+
# Initialisation d'une liste pour stocker le texte extrait
|
| 50 |
+
extracted_texts = []
|
| 51 |
+
|
| 52 |
+
# Extraction et visualisation des régions d'intérêt détectées par YOLO
|
| 53 |
+
for result in results:
|
| 54 |
+
for bbox in result.boxes:
|
| 55 |
+
x1, y1, x2, y2 = map(int, bbox.xyxy[0])
|
| 56 |
+
|
| 57 |
+
# Dessiner une boîte autour de chaque région détectée
|
| 58 |
+
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
|
| 59 |
+
|
| 60 |
+
# Passer la région d'intérêt au modèle OCR
|
| 61 |
+
roi = image.crop((x1, y1, x2, y2))
|
| 62 |
+
pixel_values = processor(roi, return_tensors='pt').pixel_values.to(device)
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
generated_ids = trained_model.generate(pixel_values)
|
| 65 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 66 |
+
|
| 67 |
+
# Stocker le texte extrait
|
| 68 |
+
extracted_texts.append(generated_text)
|
| 69 |
+
|
| 70 |
+
# Afficher les textes extraits
|
| 71 |
+
extracted_text = " | ".join(extracted_texts) if extracted_texts else "No text detected."
|
| 72 |
+
|
| 73 |
+
# Retourner l'image annotée et le texte extrait
|
| 74 |
+
return image, extracted_text
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return image, f"An error occurred during processing: {e}"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Interface Gradio améliorée
|
| 81 |
+
with gr.Blocks(css="""
|
| 82 |
+
body {
|
| 83 |
+
background-color: #f4f4f9;
|
| 84 |
+
font-family: 'Arial', sans-serif;
|
| 85 |
+
}
|
| 86 |
+
.output-image, .input-image {
|
| 87 |
+
border: 2px solid #ddd;
|
| 88 |
+
border-radius: 10px;
|
| 89 |
+
}
|
| 90 |
+
.output-text {
|
| 91 |
+
background-color: #f4f4f9;
|
| 92 |
+
border-radius: 10px;
|
| 93 |
+
border: 1px solid #ddd;
|
| 94 |
+
}
|
| 95 |
+
.output-box {
|
| 96 |
+
margin-top: 20px;
|
| 97 |
+
}
|
| 98 |
+
""") as iface:
|
| 99 |
+
|
| 100 |
+
gr.Markdown("""
|
| 101 |
+
<div style='text-align: center; font-size: 18px;'>
|
| 102 |
+
<p>Upload an image to extract text using the TrOCR model with YOLO object detection.</p>
|
| 103 |
+
<p>Detected regions are highlighted in <span style='color: red; font-weight: bold;'>red</span>.</p>
|
| 104 |
+
</div>
|
| 105 |
+
""")
|
| 106 |
+
|
| 107 |
+
with gr.Row():
|
| 108 |
+
image_input = gr.Image(type="pil", label="Upload Image", height=300)
|
| 109 |
+
image_output = gr.Image(label="Detected Image", height=300, width=300)
|
| 110 |
+
|
| 111 |
+
text_output = gr.Textbox(label="Extracted Text", lines=3, max_lines=3, placeholder="Text will appear here...")
|
| 112 |
+
|
| 113 |
+
image_input.change(fn=ocr, inputs=image_input, outputs=[image_output, text_output])
|
| 114 |
+
|
| 115 |
+
iface.launch(share=True)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# Initialisation du device et du modèle
|
| 119 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 120 |
+
processor = TrOCRProcessor.from_pretrained(ModelConfig.MODEL_NAME)
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
trained_model = VisionEncoderDecoderModel.from_pretrained(ModelConfig.MODEL_NAME)
|
| 124 |
+
trained_model.load_state_dict(torch.load(ModelConfig.MODEL_PATH, map_location=device))
|
| 125 |
+
trained_model.to(device)
|
| 126 |
+
trained_model.eval()
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Erreur lors du chargement du modèle : {e}")
|
| 129 |
+
exit(1)
|
| 130 |
+
|
| 131 |
+
# Fonction d'inférence
|
| 132 |
+
def ocr(image):
|
| 133 |
+
try:
|
| 134 |
+
image = Image.fromarray(np.array(image))
|
| 135 |
+
pixel_values = processor(image, return_tensors='pt').pixel_values.to(device)
|
| 136 |
+
generated_ids = trained_model.generate(pixel_values)
|
| 137 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 138 |
+
return generated_text
|
| 139 |
+
except Exception as e:
|
| 140 |
+
return f"Erreur lors du traitement de l'image : {e}"
|
| 141 |
+
|
| 142 |
+
# Interface Gradio
|
| 143 |
+
iface = gr.Interface(
|
| 144 |
+
fn=ocr,
|
| 145 |
+
inputs=gr.Image(type="pil", label="Télécharger une image", image_mode="fit"),
|
| 146 |
+
outputs=gr.Textbox(label="Texte extrait"),
|
| 147 |
+
title="Extraction de texte OCR",
|
| 148 |
+
description="Téléchargez une image pour extraire le texte en utilisant le modèle TrOCR.",
|
| 149 |
+
allow_flagging="never"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
iface.launch(share=True)
|