File size: 4,156 Bytes
4ec8292
 
4eac348
 
ae870cd
4ec8292
 
ae870cd
4ec8292
4eac348
4ec8292
4eac348
 
4ec8292
4eac348
 
 
 
4ec8292
4eac348
ae870cd
4ec8292
ae870cd
4eac348
ae870cd
 
 
4eac348
 
4ec8292
 
 
 
ae870cd
4ec8292
 
ae870cd
 
 
 
ed6a8d8
 
ae870cd
ed6a8d8
 
 
 
 
ae870cd
ed6a8d8
 
 
 
ae870cd
ed6a8d8
 
 
 
 
 
 
 
 
 
 
 
ae870cd
ed6a8d8
 
 
ae870cd
ed6a8d8
 
 
 
 
 
 
 
 
 
 
 
ae870cd
ed6a8d8
 
 
 
 
 
ae870cd
ed6a8d8
 
 
 
ae870cd
ed6a8d8
 
 
 
 
 
ae870cd
ed6a8d8
 
 
1
2
3
4
5
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
import os
import gradio as gr
from transformers import VisionEncoderDecoderModel, NougatProcessor
import torch
import pypdfium2 as pdfium
from ebooklib import epub
import uuid
import markdown2

# --- Model ve İşlemci Yükleme ---
try:
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Kullanılan cihaz: {device}")

    model_name = "facebook/nougat-base" 
    processor = NougatProcessor.from_pretrained(model_name)
    model = VisionEncoderDecoderModel.from_pretrained(model_name).to(device)
    print("Nougat modeli ve işlemcisi başarıyla yüklendi.")
except Exception as e:
    print(f"Model yüklenirken bir hata oluştu: {e}")
    model, processor = None, None

# --- Ana Fonksiyon ---
def pdf_to_epub_nougat(pdf_file):
    # KODUN GÜNCELLENDİĞİNİ KONTROL ETMEK İÇİN KONTROL MESAJI
    print(">>> SÜRÜM 2: DÜZELTİLMİŞ KOD BAŞARIYLA ÇALIŞIYOR! <<<")

    if model is None or processor is None:
        raise gr.Error("Model yüklenemedi. Lütfen Space loglarını kontrol edin.")
    if pdf_file is None:
        raise gr.Error("Lütfen bir PDF dosyası yükleyin.")

    pdf_path = pdf_file.name

    try:
        print(f"'{os.path.basename(pdf_path)}' dosyası işleniyor...")

        # 1. PDF dosyasını PIL resim listesine çevir (DOĞRU FONKSİYON)
        images = pdfium.render_pdf_to_pil(pdf_path)

        total_pages = len(images)
        print(f"{total_pages} sayfa bulundu ve resimlere dönüştürüldü.")

        all_markdown_pages = []

        # 2. Her bir sayfa resmini Nougat ile işle
        for i, image in enumerate(images):
            print(f"Sayfa {i + 1}/{total_pages} Nougat tarafından işleniyor...")

            pixel_values = processor(images=image, return_tensors="pt").pixel_values
            outputs = model.generate(
                pixel_values.to(device),
                min_length=1,
                max_new_tokens=4096,
            )
            sequence = processor.batch_decode(outputs, skip_special_tokens=True)[0]
            sequence = processor.post_process_generation(sequence, fix_markdown=False)
            all_markdown_pages.append(sequence)

        print("Tüm sayfalardan metinler (Markdown) başarıyla çıkarıldı.")

        # 3. EPUB Dosyasını Oluştur
        print("EPUB dosyası oluşturuluyor...")
        full_markdown_content = "\n\n".join(all_markdown_pages)
        html_content = markdown2.markdown(full_markdown_content, extras=["tables", "fenced-code-blocks"])
        epub_filename = f"converted_{uuid.uuid4()}.epub"

        book = epub.EpubBook()
        book.set_identifier(f'urn:uuid:{uuid.uuid4()}')
        book.set_title(os.path.basename(pdf_path).replace('.pdf', ''))
        book.set_language('en')

        chapter = epub.EpubHtml(title='İçerik', file_name='chap_1.xhtml')
        chapter.content = html_content

        book.add_item(chapter)
        book.toc = [epub.Link('chap_1.xhtml', 'İçerik', 'content')]
        book.spine = ['nav', chapter]
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())

        epub.write_epub(epub_filename, book, {})
        print(f"EPUB dosyası başarıyla oluşturuldu: {epub_filename}")

        return epub_filename

    except Exception as e:
        print(f"Bir hata oluştu: {e}")
        raise gr.Error(f"İşlem sırasında bir hata meydana geldi: {e}")

# --- Gradio Arayüzü ---
with gr.Blocks() as iface:
    gr.Markdown(
        """
        # 📚 PDF'ten EPUB'a Dönüştürücü (Nougat Modeli ile)
        Bu araç, yüklediğiniz bir PDF dosyasının sayfalarını **Meta's Nougat** modelini kullanarak okur ve metinleri birleştirerek indirilebilir bir EPUB dosyası oluşturur.
        **Not:** Bu işlem, ücretsiz CPU donanımında yavaş olabilir. Lütfen sabırlı olun.
        """
    )
    pdf_input = gr.File(label="PDF Dosyasını Yükle", file_types=[".pdf"])
    epub_output = gr.File(label="İndirilebilir EPUB Dosyası")
    convert_button = gr.Button("Dönüştür", variant="primary")
    convert_button.click(fn=pdf_to_epub_nougat, inputs=pdf_input, outputs=epub_output)

if __name__ == "__main__":
    iface.launch()