Update app.py
Browse files
app.py
CHANGED
@@ -5,7 +5,7 @@ import torch
|
|
5 |
from transformers import NougatProcessor, VisionEncoderDecoderModel
|
6 |
from PIL import Image
|
7 |
import fitz # PyMuPDF
|
8 |
-
from typing import List
|
9 |
import os
|
10 |
import requests
|
11 |
from io import BytesIO
|
@@ -37,57 +37,68 @@ def process_single_image(image: Image.Image) -> str:
|
|
37 |
return "Model yüklenemedi veya geçersiz görüntü."
|
38 |
|
39 |
try:
|
40 |
-
# Görüntüyü modelin beklediği formata dönüştürme
|
41 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
42 |
|
43 |
-
# Metin üretimi
|
44 |
outputs = model.generate(
|
45 |
pixel_values.to(device),
|
46 |
min_length=1,
|
47 |
-
max_new_tokens=4096,
|
48 |
bad_words_ids=[[processor.tokenizer.unk_token_id]],
|
49 |
)
|
50 |
|
51 |
-
# Çıktıyı okunabilir metne dönüştürme ve son işleme
|
52 |
sequence = processor.batch_decode(outputs, skip_special_tokens=True)
|
53 |
sequence = processor.post_process_generation(sequence[0], fix_markdown=False)
|
54 |
|
55 |
return sequence
|
56 |
except Exception as e:
|
|
|
|
|
57 |
return f"Görüntü işlenirken bir hata oluştu: {e}"
|
58 |
|
59 |
-
def process_pdf_file(pdf_file) -> str:
|
60 |
-
"""Yüklenen bir PDF dosyasını işler, her
|
61 |
-
if not MODEL_LOADED
|
62 |
-
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
doc = None # doc değişkenini try bloğundan önce tanımla
|
66 |
try:
|
67 |
-
|
68 |
-
# Bu nesnenin .name özelliği dosya yolunu içerir.
|
69 |
-
# PyMuPDF'in open fonksiyonuna doğrudan bu dosya yolunu veriyoruz.
|
70 |
doc = fitz.open(pdf_file.name)
|
|
|
71 |
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
76 |
pix = page.get_pixmap(dpi=150)
|
77 |
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples).convert("RGB")
|
78 |
|
79 |
-
# Her sayfayı tekil görüntü olarak işleme
|
80 |
page_markdown = process_single_image(image)
|
81 |
full_markdown_content.append(f"## Sayfa {page_num + 1}\n\n{page_markdown}")
|
82 |
|
83 |
-
|
|
|
|
|
|
|
84 |
except Exception as e:
|
85 |
-
|
|
|
|
|
86 |
finally:
|
87 |
if doc:
|
88 |
doc.close()
|
89 |
|
90 |
-
|
91 |
# --- Gradio Arayüzü ---
|
92 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
93 |
gr.Markdown(
|
@@ -103,6 +114,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
103 |
with gr.TabItem("PDF Dosyasını İşle"):
|
104 |
pdf_input = gr.File(label="PDF Dosyası Yükle", file_types=[".pdf"])
|
105 |
pdf_process_button = gr.Button("PDF'i Dönüştür", variant="primary")
|
|
|
|
|
106 |
pdf_output = gr.Markdown(label="Dönüştürülen Metin (Markdown)")
|
107 |
|
108 |
# Tek Görüntü İşleme Sekmesi
|
@@ -111,11 +124,12 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
111 |
image_process_button = gr.Button("Görüntüyü Dönüştür", variant="primary")
|
112 |
image_output = gr.Markdown(label="Dönüştürülen Metin (Markdown)")
|
113 |
|
114 |
-
# Buton tıklama
|
115 |
pdf_process_button.click(
|
116 |
fn=process_pdf_file,
|
117 |
inputs=[pdf_input],
|
118 |
-
|
|
|
119 |
api_name="process_pdf"
|
120 |
)
|
121 |
|
@@ -127,8 +141,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
127 |
)
|
128 |
|
129 |
gr.Markdown("### Örnek Kullanım")
|
130 |
-
# Örnek bir resim dosyası oluşturun veya yükleyin ve adını buraya yazın.
|
131 |
-
# Örneğin, projenizin kök dizininde 'nougat_paper_example.png' adında bir dosya olmalı.
|
132 |
example_image_path = "nougat_paper_example.png"
|
133 |
if os.path.exists(example_image_path):
|
134 |
gr.Examples(
|
@@ -141,7 +153,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
141 |
)
|
142 |
|
143 |
if __name__ == "__main__":
|
144 |
-
# Örnek resim dosyasını indirme (eğer yoksa)
|
145 |
if not os.path.exists("nougat_paper_example.png"):
|
146 |
try:
|
147 |
url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_docvqa/resolve/main/nougat_paper.png"
|
@@ -152,4 +163,4 @@ if __name__ == "__main__":
|
|
152 |
except Exception as e:
|
153 |
print(f"Örnek resim indirilemedi: {e}")
|
154 |
|
155 |
-
demo.launch(debug=True)
|
|
|
5 |
from transformers import NougatProcessor, VisionEncoderDecoderModel
|
6 |
from PIL import Image
|
7 |
import fitz # PyMuPDF
|
8 |
+
from typing import List, Iterator, Tuple
|
9 |
import os
|
10 |
import requests
|
11 |
from io import BytesIO
|
|
|
37 |
return "Model yüklenemedi veya geçersiz görüntü."
|
38 |
|
39 |
try:
|
|
|
40 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
41 |
|
|
|
42 |
outputs = model.generate(
|
43 |
pixel_values.to(device),
|
44 |
min_length=1,
|
45 |
+
max_new_tokens=4096,
|
46 |
bad_words_ids=[[processor.tokenizer.unk_token_id]],
|
47 |
)
|
48 |
|
|
|
49 |
sequence = processor.batch_decode(outputs, skip_special_tokens=True)
|
50 |
sequence = processor.post_process_generation(sequence[0], fix_markdown=False)
|
51 |
|
52 |
return sequence
|
53 |
except Exception as e:
|
54 |
+
# Hatanın konsola yazdırılması
|
55 |
+
print(f"Görüntü işleme hatası: {e}")
|
56 |
return f"Görüntü işlenirken bir hata oluştu: {e}"
|
57 |
|
58 |
+
def process_pdf_file(pdf_file) -> Iterator[Tuple[str, str]]:
|
59 |
+
"""Yüklenen bir PDF dosyasını işler, her sayfa için durum güncellemesi yapar."""
|
60 |
+
if not MODEL_LOADED:
|
61 |
+
yield "Hata: Model yüklenemedi.", ""
|
62 |
+
return
|
63 |
+
if pdf_file is None:
|
64 |
+
yield "Hata: PDF dosyası yüklenmedi.", ""
|
65 |
+
return
|
66 |
|
67 |
+
doc = None
|
|
|
68 |
try:
|
69 |
+
yield "PDF dosyası açılıyor...", ""
|
|
|
|
|
70 |
doc = fitz.open(pdf_file.name)
|
71 |
+
total_pages = len(doc)
|
72 |
|
73 |
+
if total_pages == 0:
|
74 |
+
yield "Hata: PDF dosyasında işlenecek sayfa bulunamadı.", ""
|
75 |
+
return
|
76 |
+
|
77 |
+
full_markdown_content = []
|
78 |
+
for page_num in range(total_pages):
|
79 |
+
status_message = f"Sayfa {page_num + 1} / {total_pages} işleniyor..."
|
80 |
+
# Her sayfadan önce durum güncellemesi ve o ana kadarki içeriği gönder
|
81 |
+
yield status_message, "\n\n---\n\n".join(full_markdown_content)
|
82 |
|
83 |
+
page = doc.load_page(page_num)
|
84 |
pix = page.get_pixmap(dpi=150)
|
85 |
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples).convert("RGB")
|
86 |
|
|
|
87 |
page_markdown = process_single_image(image)
|
88 |
full_markdown_content.append(f"## Sayfa {page_num + 1}\n\n{page_markdown}")
|
89 |
|
90 |
+
# Sonuç
|
91 |
+
final_output = "\n\n---\n\n".join(full_markdown_content)
|
92 |
+
yield "İşlem tamamlandı!", final_output
|
93 |
+
|
94 |
except Exception as e:
|
95 |
+
error_msg = f"PDF işlenirken bir hata oluştu: {e}"
|
96 |
+
print(error_msg) # Hatanın sunucu loglarına yazdırılması
|
97 |
+
yield error_msg, "" # Hatanın arayüzde gösterilmesi
|
98 |
finally:
|
99 |
if doc:
|
100 |
doc.close()
|
101 |
|
|
|
102 |
# --- Gradio Arayüzü ---
|
103 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
104 |
gr.Markdown(
|
|
|
114 |
with gr.TabItem("PDF Dosyasını İşle"):
|
115 |
pdf_input = gr.File(label="PDF Dosyası Yükle", file_types=[".pdf"])
|
116 |
pdf_process_button = gr.Button("PDF'i Dönüştür", variant="primary")
|
117 |
+
# YENİ: Durum mesajları için bir metin kutusu eklendi
|
118 |
+
pdf_status = gr.Textbox(label="İşlem Durumu", value="İşlem bekleniyor...", interactive=False)
|
119 |
pdf_output = gr.Markdown(label="Dönüştürülen Metin (Markdown)")
|
120 |
|
121 |
# Tek Görüntü İşleme Sekmesi
|
|
|
124 |
image_process_button = gr.Button("Görüntüyü Dönüştür", variant="primary")
|
125 |
image_output = gr.Markdown(label="Dönüştürülen Metin (Markdown)")
|
126 |
|
127 |
+
# Buton tıklama olayı güncellendi
|
128 |
pdf_process_button.click(
|
129 |
fn=process_pdf_file,
|
130 |
inputs=[pdf_input],
|
131 |
+
# YENİ: Çıktılar hem durum kutusunu hem de sonuç kutusunu güncelliyor
|
132 |
+
outputs=[pdf_status, pdf_output],
|
133 |
api_name="process_pdf"
|
134 |
)
|
135 |
|
|
|
141 |
)
|
142 |
|
143 |
gr.Markdown("### Örnek Kullanım")
|
|
|
|
|
144 |
example_image_path = "nougat_paper_example.png"
|
145 |
if os.path.exists(example_image_path):
|
146 |
gr.Examples(
|
|
|
153 |
)
|
154 |
|
155 |
if __name__ == "__main__":
|
|
|
156 |
if not os.path.exists("nougat_paper_example.png"):
|
157 |
try:
|
158 |
url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_docvqa/resolve/main/nougat_paper.png"
|
|
|
163 |
except Exception as e:
|
164 |
print(f"Örnek resim indirilemedi: {e}")
|
165 |
|
166 |
+
demo.launch(debug=True)
|