Coklu kaynak sozlesmesi: sources listesi, OLE okuma, atlama durumları
Browse files at this commit02e5c99a88d64df26decba3fcd205cefcf873a7bParent: b71953f13 changed files +752 -271
- CLAUDE.md +22 -14
- Containerfile +2 -0
- README.md +51 -36
- src/api_engine.py +73 -58
- src/backend.py +1 -0
- src/capabilities.py +44 -23
- src/extract.py +61 -15
- src/jobs.py +45 -8
- tests/unit/test_api_engine.py +74 -2
- tests/unit/test_capabilities.py +138 -0
- tests/unit/test_extract.py +23 -6
- tests/unit/test_extract_formats.py +22 -2
- tests/unit/test_multi_source.py +196 -107
CLAUDE.mdmodified+22 -14
| @@ -102,9 +102,11 @@ bunu tekrarlar; `tools/mutation_test.py` slayt operatorleriyle mutasyon skoru ol | ||
| 102 | 102 | gönderir; dosya diskte uzantısız durur, anahtar bir kimliktir. `extract.sniff()` |
| 103 | 103 | sihirli baytlara ve zip üye adlarına bakar. Uzantıya güvenen bir kısayol |
| 104 | 104 | eklenirse `ders.pdf` adlı bir docx yanlış ayrıştırıcıya gider. |
| 105 | -- **Yeni belge biçimi için bağımlılık eklenmez.** docx/pptx/odt/odp hepsi | |
| 106 | - zip + XML'dir; `zipfile` ve `xml.etree` yeter. `requirements.txt` iki satırdır | |
| 107 | - (`aioquic`, `pymupdf`) ve öyle kalmalı — imaj bağımlılık kapısından geçiyor. | |
| 105 | +- **Yeni pip bağımlılığı eklenmez; sistem aracı apt'tan gelir.** docx/pptx/ | |
| 106 | + odt/odp zip + XML'dir; `zipfile` ve `xml.etree` yeter. `requirements.txt` | |
| 107 | + iki satırdır (`aioquic`, `pymupdf`) ve öyle kalmalı. Eski ikili `.doc/.ppt` | |
| 108 | + stdlib ile OKUNMAZ: `antiword` + `catdoc` apt paketleriyle girer (60 sn | |
| 109 | + zaman aşımı, utf-8 -> cp1254 sırası), LibreOffice kasıtlı istenmez. | |
| 108 | 110 | - **Zip üyesi okunmadan ÖNCE boyutu denetlenir.** `_guard_size()` üye başına |
| 109 | 111 | 16 MiB, toplam 64 MiB tavanı uygular. Sınırsız `archive.read()` sıkıştırma |
| 110 | 112 | bombasına açık kapıdır. |
| @@ -113,26 +115,32 @@ bunu tekrarlar; `tools/mutation_test.py` slayt operatorleriyle mutasyon skoru ol | ||
| 113 | 115 | 1, 10, 11, 2 sırasıyla akar. |
| 114 | 116 | - **Okunamayan biçim sebebini ve çıkış yolunu söyler.** `unsupported_source` |
| 115 | 117 | kodu döner ve mesaj ne yapılacağını yazar (".docx olarak kaydedin" gibi). |
| 116 | - Eski ikili `.doc/.ppt` için yarım ayrıştırıcı YAZILMAZ: yanlış metin | |
| 117 | - üretmektense açık hata verilir. | |
| 118 | + OLE yolunda iki araç da yoksa `extractor_unavailable`, ikisi de okumazsa | |
| 119 | + `source_unreadable`, çıktı boşsa `no_text_layer` döner. | |
| 118 | 120 | - **Görüntü-only sunumda OCR yoktur.** PDF yolunda OCR yedeği var, PPTX/ODP |
| 119 | 121 | yolunda yok; iş `no_text_layer` ile açıkça düşer, boş üretmez. Konuşmacı |
| 120 | 122 | notları okunmaz — ölçüldü, çoğu yalnızca slayt numarası taşıyor ve anlatıma |
| 121 | 123 | çöp sokardı. |
| 122 | 124 | - **Çoklu kaynakta alan EKLENDİ, yeniden adlandırılmadı.** `source_key` tekil |
| 123 | - kaldı (ilk belge), `source_keys` eklendi (en fazla 20). Alan gelmezse | |
| 124 | - `[source_key]`'e düşülür; böylece servis backend'den ÖNCE dağıtılabilir. | |
| 125 | - `source_keys` `REQUIRED_FIELDS`'a **eklenmez** — eklenirse alan eklenmeden | |
| 126 | - önce yazılmış kayıtlar açılışta topluca atılır. | |
| 127 | -- **Çoklu kaynakta bir belge okunamazsa iş DÜŞER**, sessizce atlanmaz. Beş | |
| 128 | - belgeden biri atlanırsa kullanıcı eksik içerikli bir podcast alır ve bunu | |
| 129 | - fark edemez; "sessiz sahte üretim yasak" ilkesi burada da geçerlidir. Hata | |
| 130 | - kaçıncı kaynağın sorunlu olduğunu adıyla söyler. | |
| 125 | + kaldı (ilk belge, bir sürüm uyumluluğu), `sources` eklendi: | |
| 126 | + `[{key, name, content_type}]`, en fazla 10. Servis `sources`'ı tercih eder, | |
| 127 | + gelmezse tekilden türetir. `sources` `REQUIRED_FIELDS`'a **eklenmez** — | |
| 128 | + eklenirse alan eklenmeden önce yazılmış kayıtlar açılışta topluca atılır. | |
| 129 | +- **Çoklu kaynakta okunamayan belge işi DÜŞÜRMEZ, ATLANIR.** Atlama kodu | |
| 130 | + `skipped:<kod>` olarak iş kaydındaki `sources` listesine yazılır ve | |
| 131 | + `podcast.report` yüküyle backend'e gider (`{key, name, status}`). Tümü | |
| 132 | + atlanırsa iş ilk kaynağın atlama koduyla; birleşik metin | |
| 133 | + `PODCAST_MIN_TEXT_CHARS` altındaysa `no_text_layer` ile düşer. Bu donmuş | |
| 134 | + sözleşme kararıdır; "sessiz sahte üretim" sayılmaz çünkü eksik belge | |
| 135 | + raporda adıyla görünür. | |
| 136 | +- **Belgeler `\n\n=== <name> ===\n\n` başlığıyla birleşir.** Başlık yalnızca | |
| 137 | + belgeler ARASINDA gelir; tek kaynaklı iş başlıksızdır ve `extract_text` | |
| 138 | + ile birebir aynı sonucu üretir. | |
| 131 | 139 | |
| 132 | 140 | ## Dosyalar ve komutlar |
| 133 | 141 | `config.py` ortam+log · `protocol.py` çerçeveleme+mesajlar · `jobs.py` iş deposu+ |
| 134 | 142 | durum makinesi+sahte hat · `pipeline.py` gerçek `router.hat.Hat` runner'ı (tembel |
| 135 | -import) · `extract.py` belge bicimi tanima + docx/pptx/odt/odp/metin okuma · `capabilities.py` yetenek defteri · `bridge.py` QUIC istemcisi · | |
| 143 | +import) · `extract.py` belge bicimi tanima + docx/pptx/odt/odp/ole/metin okuma · `capabilities.py` yetenek defteri · `bridge.py` QUIC istemcisi · | |
| 136 | 144 | `main.py` `--validate` + `--health` · `tools/smoke_test.py` elle koşulan duman testi · |
| 137 | 145 | `tools/mutation_test.py` slayt operatörleriyle mutasyon skoru · `tools/fuzz_test.py` |
| 138 | 146 | altı slayt kategorisi + şablon/gramer/kapsam-geri-besleme fuzzing · |
Containerfilemodified+2 -0
| @@ -21,6 +21,8 @@ RUN apt-get update \ | ||
| 21 | 21 | libgl1 \ |
| 22 | 22 | libglib2.0-0 \ |
| 23 | 23 | tesseract-ocr \ |
| 24 | + antiword \ | |
| 25 | + catdoc \ | |
| 24 | 26 | tesseract-ocr-tur \ |
| 25 | 27 | && rm -rf /var/lib/apt/lists/* |
| 26 | 28 |
README.mdmodified+51 -36
| @@ -435,7 +435,7 @@ bir kimlik, dosya adı değil. Bu yüzden `sniff()` sihirli baytlara bakar: | ||
| 435 | 435 | | `PK\x03\x04` + `mimetype` = OpenDocument text/presentation | `odt` / `odp` | |
| 436 | 436 | | `PK\x03\x04` + `xl/workbook.xml` veya OpenDocument spreadsheet | `sheet` (reddedilir) | |
| 437 | 437 | | `{\rtf` | `rtf` (reddedilir) | |
| 438 | -| `\xd0\xcf\x11\xe0...` | `ole` — eski ikili `.doc/.ppt/.xls` (reddedilir) | | |
| 438 | +| `\xd0\xcf\x11\xe0...` | `ole` — eski ikili `.doc/.ppt`; `antiword`/`catppt` ile okunur | | |
| 439 | 439 | | NUL içermeyen, çözülebilen metin | `text` | |
| 440 | 440 | |
| 441 | 441 | Bunun ölçülmüş sonucu: `ders.pdf` adlı ama içeriği docx olan bir dosya **docx** |
| @@ -459,21 +459,27 @@ Sessizce "bilinmeyen" demek yerine her red ne yapılacağını yazar: | ||
| 459 | 459 | |
| 460 | 460 | | Biçim | Mesaj | |
| 461 | 461 | | --- | --- | |
| 462 | -| `.doc/.ppt/.xls` | "eski ikili Office bicimi; dosyayi .docx veya .pptx olarak kaydedip yeniden yukleyin" | | |
| 463 | 462 | | `.xlsx/.ods` | "hesap tablosu anlatima uygun degil; ders metnini belge olarak yukleyin" | |
| 464 | 463 | | `.rtf` | "rtf desteklenmiyor; .docx veya .odt olarak kaydedin" | |
| 465 | 464 | |
| 466 | 465 | Hata kodu `unsupported_source`'tur (18 karakter; backend `error_code` için 64 |
| 467 | 466 | karakter sınırı koyar, test bunu da doğrular). |
| 468 | 467 | |
| 469 | -Eski ikili biçimler için yarım yamalak bir ayrıştırıcı **bilerek yazılmadı**: | |
| 470 | -OLE2 stdlib ile okunamaz, gerçek destek `antiword` ya da LibreOffice headless | |
| 471 | -ister. Yanlış metin üretmektense açık hata verilir. | |
| 468 | +### Eski ikili .doc/.ppt: antiword + catppt | |
| 472 | 469 | |
| 473 | -### Yeni bağımlılık YOK | |
| 470 | +OLE imzası gören yol `antiword`'ü (.doc), o olmazsa `catppt'i (.ppt)` | |
| 471 | +çalıştırır; 60 saniye zaman aşımıyla. Çıktı baytları sırayla utf-8 ve | |
| 472 | +cp1254 çözülür (Türkçe eski belgeler için). İki araç da kurulu değilse | |
| 473 | +`extractor_unavailable`, ikisi de okumazsa `source_unreadable`, çıktı boşsa | |
| 474 | +`no_text_layer` döner — çok kaynaklı işte bu bir **atlama**dır (aşağıda). | |
| 475 | +Araçlar Containerfile'a `antiword` + `catdoc` paketleriyle girer; ikisi de | |
| 476 | +küçüktür ve LibreOffice gibi ağır bir bağımlılık istemez. | |
| 477 | + | |
| 478 | +### Yeni pip bağımlılığı YOK | |
| 474 | 479 | |
| 475 | 480 | DOCX, PPTX, ODT ve ODP hepsi zip + XML'dir; `zipfile` ve `xml.etree` stdlib'de |
| 476 | -vardır. `requirements.txt` değişmedi (`aioquic`, `pymupdf`). | |
| 481 | +vardır. `requirements.txt` değişmedi (`aioquic`, `pymupdf`). Tek bağımlılık | |
| 482 | +değişimi apt tarafındadır: `antiword`, `catdoc`. | |
| 477 | 483 | |
| 478 | 484 | ### Zip bombası koruması |
| 479 | 485 | |
| @@ -508,65 +514,74 @@ Gövde dışı metin (üstbilgi, altbilgi, dipnot) alınmaz. 90 gerçek docx'te | ||
| 508 | 514 | | --- | --- | --- | --- | |
| 509 | 515 | | `.docx` | 283 | 257 | 0 | |
| 510 | 516 | | `.pptx` | 58 | 56 | 0 | |
| 511 | -| `.doc` | 28 | 23 (reddedildi) | 0 | | |
| 517 | +| `.doc` | 28 | 23 | 0 | | |
| 512 | 518 | | `.txt` | 400 örnek | 400 | 0 | |
| 513 | 519 | | `.md` | 144 | 142 | 0 | |
| 514 | 520 | |
| 515 | 521 | Tanınmayanların tamamı 0–165 baytlık artık dosyalardı, gerçek belge değil. |
| 522 | +Ölçüm `.doc` henüz reddedilirken yapıldı; bugün 23 tanınan dosya | |
| 523 | +`antiword` yoluna girer. | |
| 516 | 524 | |
| 517 | 525 | ## Çoklu kaynak: N belge, tek podcast |
| 518 | 526 | |
| 519 | 527 | Bir iş birden çok belgeyi birleştirip **tek** podcast üretebilir. Belgeler |
| 520 | 528 | farklı biçimlerde olabilir — bir docx, bir pptx ve bir odt aynı işte toplanabilir. |
| 521 | 529 | |
| 522 | -### Sözleşme kırılmadı, alan EKLENDİ | |
| 530 | +### Sözleşme: sources listesi, tekil alan geriye dönük uyumluluk içindir | |
| 523 | 531 | |
| 524 | 532 | `audio_id`/`audio_ids` çiftinde olduğu gibi tekil alan yerinde kaldı: |
| 525 | 533 | |
| 526 | 534 | ``` |
| 527 | -source_key TEKIL kaldi, ilk belgeyi gosterir | |
| 528 | -source_keys EKLENDI, tum belgeler (en fazla MAX_SOURCES = 20) | |
| 535 | +source_key TEKIL kaldi, ilk belgeyi gosterir (bir surum uyumlulugu) | |
| 536 | +sources EKLENDI, tum belgeler: [{key, name, content_type}] (en fazla 10) | |
| 529 | 537 | ``` |
| 530 | 538 | |
| 531 | -`source_keys` gelmezse `[source_key]`'e düşülür, yani **eski yük eski davranışı | |
| 532 | -üretir**. Bu kasıtlıdır: servis backend'den önce dağıtılabilsin, iki repo aynı | |
| 533 | -anda deploy edilmek zorunda kalmasın diye. | |
| 539 | +Servis `sources`'ı tercih eder; gelmezse `source_key`'ten tek girdili bir | |
| 540 | +liste türetir — yani **eski yük eski davranışı üretir**. `sources`'un ilk | |
| 541 | +öğesi verildiyse `source_key` ile aynı olmak zorundadır. | |
| 534 | 542 | |
| 535 | -`source_keys` `REQUIRED_FIELDS`'a **eklenmedi**. Eklenseydi, alan eklenmeden önce | |
| 536 | -diske yazılmış işler açılışta topluca atılırdı; `JobContext` cogul alanı yoksa | |
| 543 | +`sources` `REQUIRED_FIELDS`'a **eklenmedi**. Eklenseydi, alan eklenmeden önce | |
| 544 | +diske yazılmış işler açılışta topluca atılırdı; `JobContext` alanı yoksa | |
| 537 | 545 | tekilden türetir. |
| 538 | 546 | |
| 539 | 547 | ### Doğrulama |
| 540 | 548 | |
| 541 | -`podcast.submit` şu durumlarda `bad_request` döner: liste değilse, boşsa, boş | |
| 542 | -metin içeriyorsa, aynı kaynağı tekrar ediyorsa, ilk öğesi `source_key` ile | |
| 543 | -uyuşmuyorsa, ya da 20'yi aşıyorsa. | |
| 549 | +`podcast.submit` şu durumlarda `bad_request` döner: `sources` liste değilse, | |
| 550 | +boşsa, bir üye nesne değilse, `key` `source_key` güvenlik desenini | |
| 551 | +(`^[A-Za-z0-9._-]{1,128}$`) geçmiyorsa, aynı kaynağı tekrar ediyorsa, ilk | |
| 552 | +öğesi `source_key` ile uyuşmuyorsa, 10'u aşıyorsa — ya da `sources` da | |
| 553 | +`source_key` da yoksa. `name` boşsa anahtara düşer; `content_type` yalnızca | |
| 554 | +kayıt amaçlıdır, tür her zaman içerikten gelir. | |
| 544 | 555 | |
| 545 | 556 | ### Birleştirme |
| 546 | 557 | |
| 547 | -Belgeler **gönderildikleri sırayla** okunur ve metinleri boş satırla ayrılarak | |
| 548 | -birleştirilir; sonra mevcut bölümleme ve seslendirme aynen çalışır. Tek kaynaklı | |
| 549 | -bir iş `extract_text` ile birebir aynı sonucu üretir — test bunu kilitler. | |
| 558 | +Belgeler **gönderildikleri sırayla** okunur ve metinleri belge başına | |
| 559 | +`\n\n=== <name> ===\n\n` başlığıyla ayrılarak birleştirilir; sonra mevcut | |
| 560 | +bölümleme ve seslendirme aynen çalışır. Tek kaynaklı bir iş başlıksız, | |
| 561 | +`extract_text` ile birebir aynı sonucu üretir — test bunu kilitler. | |
| 550 | 562 | |
| 551 | -### Bir belge okunamazsa iş DÜŞER | |
| 563 | +### Bir belge okunamazsa İŞ DEĞİL, o belge ATLANIR | |
| 552 | 564 | |
| 553 | -Sessizce atlanmaz. Gerekçe: beş belgeden biri sessizce atlanırsa kullanıcı eksik | |
| 554 | -içerikli bir podcast alır ve bunu fark edemez — deponun "sessiz sahte üretim | |
| 555 | -yasak" ilkesine aykırıdır. Hata kaçıncı kaynağın sorunlu olduğunu söyler: | |
| 556 | -`"2. kaynak (ders.pptx) okunamadi: ..."`. | |
| 565 | +Kaynağın çıkarımı başarısızsa iş düşmez; o belge atlanır ve iş kalanlarla | |
| 566 | +sürer. Durum `podcast.report` yüküne eklenen `sources` alanında taşınır: | |
| 567 | +her girdi `{key, name, status}`; `status` ya `ok` ya `skipped:<kod>` | |
| 568 | +(`extractor_unavailable` / `source_unreadable` / `no_text_layer` | |
| 569 | +/ `unsupported_source`). Tümü atlanırsa ya da birleşik metin | |
| 570 | +`PODCAST_MIN_TEXT_CHARS`'ın altında kalırsa iş mevcut kodlarla düşer | |
| 571 | +(sırayla: ilk kaynağın atlama kodu, `no_text_layer`). Bu, donmuş sözleşme | |
| 572 | +kararıdır: on belgeden biri bozuksa kullanıcı dokuz belgelik bölümu ve | |
| 573 | +hangi belgenin eksildiğini rapordan görür. | |
| 557 | 574 | |
| 558 | -İptal belgeler arasında denetlenir; 20 belgelik bir iş iptal edildiğinde | |
| 575 | +İptal belgeler arasında denetlenir; 10 belgelik bir iş iptal edildiğinde | |
| 559 | 576 | hepsinin bitmesi beklenmez. |
| 560 | 577 | |
| 561 | -### Backend tarafı henüz hazır değil | |
| 562 | - | |
| 563 | -Bugünkü backend her iki yeteneği de kullanmıyor: | |
| 564 | - | |
| 565 | -1. `newest_pdf()` sorgusu `content_type = 'application/pdf'` ile sabit filtreler; | |
| 566 | - PDF eki olmayan notta iş **hiç oluşturulmaz**. | |
| 567 | -2. `PodcastSubmitPayload` tek bir `source_key: String` taşır. | |
| 578 | +### Backend tarafı | |
| 568 | 579 | |
| 569 | -Servis ikisine de hazırdır ve alanlar gelmediği sürece eski davranışı sürdürür. | |
| 580 | +Backend şeridi aynı sözleşmeyi uyguluyor: kapı (`POST /podcast/jobs`) yalnızca | |
| 581 | +notun eki hiç yoksa ya da blob'ları diskte yoksa 409 `source_missing` | |
| 582 | +der; yük `sources` + tekil `source_key` (ilk kaynağın anahtarı) taşır ve | |
| 583 | +`podcast.report` artık `sources` alanını içerir. Servis bu sözleşmeye hazırdır | |
| 584 | +ve alanlar eski haliyle gelirse legacy yolla çalışmayı sürdürür. | |
| 570 | 585 | |
| 571 | 586 | |
| 572 | 587 | ## İki motor (`PODCAST_ENGINE`) |
src/api_engine.pymodified+73 -58
| @@ -130,20 +130,6 @@ def _page_texts(doc: Any, settings: Any, check: Callable[[], None]) -> tuple[lis | ||
| 130 | 130 | return texts, ocr_pages, bool(tesseract) |
| 131 | 131 | |
| 132 | 132 | |
| 133 | -def _finish_text( | |
| 134 | - blocks: list[str], settings: Any, kind: str, path: str | |
| 135 | -) -> tuple[str, int, int]: | |
| 136 | - text = _clean_text("\n".join(blocks)) | |
| 137 | - if len(text) < int(settings.min_text_chars): | |
| 138 | - raise EngineError( | |
| 139 | - NO_TEXT, | |
| 140 | - f"{kind} belgesinden metin cikmadi; cikan metin {len(text)} " | |
| 141 | - f"karakter, gereken en az {settings.min_text_chars}", | |
| 142 | - ) | |
| 143 | - config.log("info", f"{kind} metni cikarildi: {len(blocks)} blok, {path}") | |
| 144 | - return text, len(blocks), 0 | |
| 145 | - | |
| 146 | - | |
| 147 | 133 | def extract_text( |
| 148 | 134 | path: str, settings: Any, check: Callable[[], None] |
| 149 | 135 | ) -> tuple[str, int, int]: |
| @@ -151,24 +137,29 @@ def extract_text( | ||
| 151 | 137 | kind = extract.sniff(path) |
| 152 | 138 | except extract.ExtractError as exc: |
| 153 | 139 | raise EngineError(SOURCE_UNREADABLE, str(exc)) from exc |
| 140 | + if kind == extract.KIND_PDF: | |
| 141 | + return _extract_pdf(path, settings, check) | |
| 154 | 142 | readers = { |
| 155 | 143 | extract.KIND_DOCX: extract.docx_blocks, |
| 156 | 144 | extract.KIND_PPTX: extract.pptx_slides, |
| 157 | 145 | extract.KIND_ODT: extract.odt_blocks, |
| 158 | 146 | extract.KIND_ODP: extract.odp_slides, |
| 159 | 147 | extract.KIND_TEXT: extract.text_blocks, |
| 148 | + extract.KIND_OLE: extract.ole_blocks, | |
| 160 | 149 | } |
| 161 | 150 | reader = readers.get(kind) |
| 162 | - if reader is not None: | |
| 163 | - check() | |
| 164 | - try: | |
| 165 | - blocks = reader(path) | |
| 166 | - except extract.ExtractError as exc: | |
| 167 | - raise EngineError(exc.code, str(exc)) from exc | |
| 168 | - return _finish_text(blocks, settings, kind, path) | |
| 169 | - if kind != extract.KIND_PDF: | |
| 151 | + if reader is None: | |
| 170 | 152 | raise EngineError(UNSUPPORTED_SOURCE, extract.unsupported_message(kind)) |
| 171 | - return _extract_pdf(path, settings, check) | |
| 153 | + check() | |
| 154 | + try: | |
| 155 | + blocks = reader(path) | |
| 156 | + except extract.ExtractError as exc: | |
| 157 | + raise EngineError(exc.code, str(exc)) from exc | |
| 158 | + text = _clean_text("\n".join(blocks)) | |
| 159 | + if not text: | |
| 160 | + raise EngineError(NO_TEXT, f"{kind} belgesinden metin cikmadi") | |
| 161 | + config.log("info", f"{kind} metni cikarildi: {len(blocks)} blok, {path}") | |
| 162 | + return text, len(blocks), 0 | |
| 172 | 163 | |
| 173 | 164 | |
| 174 | 165 | def _extract_pdf( |
| @@ -191,49 +182,51 @@ def _extract_pdf( | ||
| 191 | 182 | finally: |
| 192 | 183 | doc.close() |
| 193 | 184 | text = _clean_text("\n".join(pages)) |
| 194 | - if len(text) < int(settings.min_text_chars): | |
| 185 | + if not text: | |
| 195 | 186 | reason = ( |
| 196 | 187 | "sayfalarda metin katmani yok" |
| 197 | 188 | if tesseract |
| 198 | 189 | else "sayfalarda metin katmani yok ve tesseract kurulu degil " |
| 199 | 190 | "(tesseract-ocr + tesseract-ocr-tur gerekir)" |
| 200 | 191 | ) |
| 201 | - raise EngineError( | |
| 202 | - NO_TEXT, | |
| 203 | - f"{reason}; cikan metin {len(text)} karakter, " | |
| 204 | - f"gereken en az {settings.min_text_chars}", | |
| 205 | - ) | |
| 192 | + raise EngineError(NO_TEXT, reason) | |
| 206 | 193 | if ocr_pages: |
| 207 | 194 | config.log("info", f"OCR {ocr_pages} sayfada kullanildi: {path}") |
| 208 | 195 | return text, len(pages), ocr_pages |
| 209 | 196 | |
| 210 | 197 | |
| 211 | -SOURCE_SEPARATOR = "\n\n" | |
| 198 | +SOURCE_HEADER = "\n\n=== {name} ===\n\n" | |
| 212 | 199 | |
| 213 | 200 | |
| 214 | 201 | def extract_sources( |
| 215 | - paths: list[Path], settings: Any, check: Callable[[], None] | |
| 202 | + sources: list[dict[str, Any]], settings: Any, check: Callable[[], None] | |
| 216 | 203 | ) -> tuple[str, int, int]: |
| 217 | - if not paths: | |
| 204 | + if not sources: | |
| 218 | 205 | raise EngineError(SOURCE_NOT_FOUND, "is icin hic kaynak verilmedi") |
| 219 | - if len(paths) == 1: | |
| 220 | - return extract_text(str(paths[0]), settings, check) | |
| 221 | 206 | parts: list[str] = [] |
| 222 | 207 | pages = 0 |
| 223 | 208 | ocr_pages = 0 |
| 224 | - for index, path in enumerate(paths, 1): | |
| 209 | + for source in sources: | |
| 225 | 210 | check() |
| 211 | + path = source.get("path") | |
| 212 | + if path is None: | |
| 213 | + continue | |
| 226 | 214 | try: |
| 227 | 215 | text, page_count, ocr = extract_text(str(path), settings, check) |
| 228 | 216 | except EngineError as exc: |
| 229 | - raise EngineError( | |
| 230 | - exc.code, | |
| 231 | - f"{index}. kaynak ({path.name}) okunamadi: {exc}", | |
| 232 | - ) from exc | |
| 217 | + source["status"] = f"skipped:{exc.code}" | |
| 218 | + config.log( | |
| 219 | + "info", | |
| 220 | + f"kaynak atlandi ({exc.code}): {source['name']}: {exc}", | |
| 221 | + ) | |
| 222 | + continue | |
| 223 | + source["status"] = "ok" | |
| 224 | + if parts: | |
| 225 | + parts.append(SOURCE_HEADER.format(name=source["name"])) | |
| 233 | 226 | parts.append(text) |
| 234 | 227 | pages += page_count |
| 235 | 228 | ocr_pages += ocr |
| 236 | - return SOURCE_SEPARATOR.join(parts), pages, ocr_pages | |
| 229 | + return "".join(parts), pages, ocr_pages | |
| 237 | 230 | |
| 238 | 231 | |
| 239 | 232 | def _write_bytes(path: Path, data: bytes) -> None: |
| @@ -352,16 +345,18 @@ def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: | ||
| 352 | 345 | total = len(STAGES) |
| 353 | 346 | |
| 354 | 347 | def runner(ctx: jobs.JobContext) -> None: |
| 355 | - try: | |
| 356 | - sources = [ | |
| 357 | - _source_path(settings.media_root, ctx.school, key) | |
| 358 | - for key in ctx.source_keys | |
| 359 | - ] | |
| 360 | - except (ValueError, FileNotFoundError, OSError) as exc: | |
| 361 | - config.log("error", f"is {ctx.job_id} kaynagi cozulemedi: {exc}") | |
| 362 | - ctx.store.fail(ctx.job_id, SOURCE_NOT_FOUND) | |
| 363 | - return | |
| 364 | - pdf = sources[0] | |
| 348 | + for spec in ctx.sources: | |
| 349 | + try: | |
| 350 | + spec["path"] = _source_path( | |
| 351 | + settings.media_root, ctx.school, spec["key"] | |
| 352 | + ) | |
| 353 | + except (ValueError, FileNotFoundError, OSError) as exc: | |
| 354 | + spec["status"] = f"skipped:{SOURCE_UNREADABLE}" | |
| 355 | + config.log( | |
| 356 | + "error", | |
| 357 | + f"is {ctx.job_id} kaynagi cozulemedi: " | |
| 358 | + f"{spec['name']}: {exc}", | |
| 359 | + ) | |
| 365 | 360 | ctx.check() |
| 366 | 361 | ctx.progress(STAGES[0], 0.0) |
| 367 | 362 | try: |
| @@ -377,17 +372,37 @@ def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: | ||
| 377 | 372 | succeeded = False |
| 378 | 373 | try: |
| 379 | 374 | ctx.progress(STAGES[1], 1.0 / total) |
| 380 | - text, pages, ocr_pages = extract_sources(sources, settings, ctx.check) | |
| 375 | + text, pages, ocr_pages = extract_sources( | |
| 376 | + ctx.sources, settings, ctx.check | |
| 377 | + ) | |
| 378 | + ctx.store.update_sources(ctx.job_id, ctx.sources) | |
| 379 | + if all(spec["status"] != "ok" for spec in ctx.sources): | |
| 380 | + if all("path" not in spec for spec in ctx.sources): | |
| 381 | + raise EngineError( | |
| 382 | + SOURCE_NOT_FOUND, "hicbir kaynak diskte yok" | |
| 383 | + ) | |
| 384 | + first = ctx.sources[0]["status"] | |
| 385 | + code = first.split(":", 1)[1] if ":" in first else SOURCE_UNREADABLE | |
| 386 | + raise EngineError(code, "hicbir kaynak okunamadi") | |
| 387 | + if len(text) < int(settings.min_text_chars): | |
| 388 | + raise EngineError( | |
| 389 | + NO_TEXT, | |
| 390 | + f"birlestirilen metin {len(text)} karakter, " | |
| 391 | + f"gereken en az {settings.min_text_chars}", | |
| 392 | + ) | |
| 393 | + base = Path( | |
| 394 | + next(spec["path"] for spec in ctx.sources if spec.get("path")) | |
| 395 | + ) | |
| 381 | 396 | config.log( |
| 382 | 397 | "info", |
| 383 | - f"is {ctx.job_id} metin cikarildi: {len(sources)} kaynak, " | |
| 398 | + f"is {ctx.job_id} metin cikarildi: {len(ctx.sources)} kaynak, " | |
| 384 | 399 | f"{pages} sayfa, {len(text)} karakter, ocr={ocr_pages}", |
| 385 | 400 | ) |
| 386 | 401 | |
| 387 | 402 | chapters = split_chapters(text, int(settings.chapter_chars), limit) |
| 388 | 403 | if not chapters: |
| 389 | 404 | raise EngineError(SCRIPT_EMPTY, "metinden bolum uretilemedi") |
| 390 | - script_dir = output_root / pdf.stem / DIR_SCRIPT / ctx.format | |
| 405 | + script_dir = output_root / base.stem / DIR_SCRIPT / ctx.format | |
| 391 | 406 | script_paths: list[Path] = [] |
| 392 | 407 | bodies: list[str] = [] |
| 393 | 408 | ctx.progress(STAGES[2], 2.0 / total) |
| @@ -395,11 +410,11 @@ def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: | ||
| 395 | 410 | ctx.check() |
| 396 | 411 | body = _script_body(chapter, ctx.format, settings, ctx.check) |
| 397 | 412 | bodies.append(body) |
| 398 | - script_path = script_dir / f"{pdf.stem}-b{index + 1:02d}.script.json" | |
| 413 | + script_path = script_dir / f"{base.stem}-b{index + 1:02d}.script.json" | |
| 399 | 414 | _write_json( |
| 400 | 415 | script_path, |
| 401 | 416 | { |
| 402 | - "kaynak": pdf.name, | |
| 417 | + "kaynak": base.name, | |
| 403 | 418 | "format": ctx.format, |
| 404 | 419 | "bolum": index + 1, |
| 405 | 420 | "baslik": _chapter_title(body), |
| @@ -412,13 +427,13 @@ def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: | ||
| 412 | 427 | STAGES[2], (2 + (index + 1) / len(chapters)) / total |
| 413 | 428 | ) |
| 414 | 429 | |
| 415 | - audio_dir = output_root / pdf.stem / DIR_AUDIO / ctx.format | |
| 430 | + audio_dir = output_root / base.stem / DIR_AUDIO / ctx.format | |
| 416 | 431 | parts: list[Path] = [] |
| 417 | 432 | ctx.progress(STAGES[3], 3.0 / total) |
| 418 | 433 | for index, body in enumerate(bodies): |
| 419 | 434 | ctx.check() |
| 420 | 435 | audio = tts.synthesize(body, settings) |
| 421 | - part = work / f"{pdf.stem}-b{index + 1:02d}.mp3" | |
| 436 | + part = work / f"{base.stem}-b{index + 1:02d}.mp3" | |
| 422 | 437 | _write_bytes(part, audio) |
| 423 | 438 | parts.append(part) |
| 424 | 439 | ctx.progress( |
| @@ -426,7 +441,7 @@ def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: | ||
| 426 | 441 | ) |
| 427 | 442 | |
| 428 | 443 | ctx.progress(STAGES[4], 4.0 / total) |
| 429 | - final = audio_dir / f"{pdf.stem}.mp3" | |
| 444 | + final = audio_dir / f"{base.stem}.mp3" | |
| 430 | 445 | _mux(parts, final, work) |
| 431 | 446 | created.append(final) |
| 432 | 447 |
src/backend.pymodified+1 -0
| @@ -51,6 +51,7 @@ class BackendClient: | ||
| 51 | 51 | "progress": record["progress"], |
| 52 | 52 | "error_code": record["error_code"], |
| 53 | 53 | "transcript": record.get("transcript") or "", |
| 54 | + "sources": record.get("sources") or [], | |
| 54 | 55 | } |
| 55 | 56 | return self._call( |
| 56 | 57 | self._protocol.call_capability(school, protocol.PODCAST_REPORT_CAPABILITY, payload), |
src/capabilities.pymodified+44 -23
| @@ -62,45 +62,66 @@ def _optional_choice(payload: dict, key: str, choices: tuple, default: str) -> s | ||
| 62 | 62 | return normalized |
| 63 | 63 | |
| 64 | 64 | |
| 65 | -MAX_SOURCES = 20 | |
| 65 | +MAX_SOURCES = 10 | |
| 66 | 66 | |
| 67 | 67 | |
| 68 | -def _source_keys(payload: dict, first: str) -> list[str]: | |
| 69 | - raw = payload.get("source_keys") | |
| 68 | +def _sources(payload: dict) -> tuple[str, list[dict[str, str]]]: | |
| 69 | + first_raw = payload.get("source_key") | |
| 70 | + first = first_raw.strip() if isinstance(first_raw, str) else "" | |
| 71 | + raw = payload.get("sources") | |
| 70 | 72 | if raw is None: |
| 71 | - return [first] | |
| 72 | - if not isinstance(raw, list): | |
| 73 | - raise CapabilityError("bad_request", "'source_keys' bir liste olmali") | |
| 74 | - keys: list[str] = [] | |
| 75 | - for item in raw: | |
| 76 | - if not isinstance(item, str) or not item.strip(): | |
| 73 | + if not first: | |
| 77 | 74 | raise CapabilityError( |
| 78 | - "bad_request", "'source_keys' bos olmayan metinlerden olusmali" | |
| 75 | + "bad_request", "'source_key' veya 'sources' gerekli" | |
| 79 | 76 | ) |
| 80 | - keys.append(item.strip()) | |
| 81 | - if not keys: | |
| 82 | - raise CapabilityError("bad_request", "'source_keys' bos olamaz") | |
| 83 | - if len(keys) > MAX_SOURCES: | |
| 77 | + return first, [{"key": first, "name": first, "content_type": ""}] | |
| 78 | + if not isinstance(raw, list): | |
| 79 | + raise CapabilityError("bad_request", "'sources' bir liste olmali") | |
| 80 | + if not raw: | |
| 81 | + raise CapabilityError("bad_request", "'sources' bos olamaz") | |
| 82 | + if len(raw) > MAX_SOURCES: | |
| 84 | 83 | raise CapabilityError( |
| 85 | 84 | "bad_request", |
| 86 | 85 | f"tek iste en fazla {MAX_SOURCES} kaynak birlestirilebilir; " |
| 87 | - f"{len(keys)} geldi", | |
| 86 | + f"{len(raw)} geldi", | |
| 87 | + ) | |
| 88 | + sources: list[dict[str, str]] = [] | |
| 89 | + for item in raw: | |
| 90 | + if not isinstance(item, dict): | |
| 91 | + raise CapabilityError( | |
| 92 | + "bad_request", "'sources' ogeleri anahtar-deger nesnesi olmali" | |
| 93 | + ) | |
| 94 | + key = item.get("key") | |
| 95 | + if ( | |
| 96 | + not isinstance(key, str) | |
| 97 | + or jobs.SAFE_SOURCE_ID.match(key.strip() or "") is None | |
| 98 | + ): | |
| 99 | + raise CapabilityError( | |
| 100 | + "bad_request", | |
| 101 | + "'sources' anahtarlari 'source_key' guvenlik kurallarina uymali", | |
| 102 | + ) | |
| 103 | + key = key.strip() | |
| 104 | + name = item.get("name") | |
| 105 | + name = name.strip() if isinstance(name, str) and name.strip() else key | |
| 106 | + content_type = item.get("content_type") | |
| 107 | + content_type = ( | |
| 108 | + content_type.strip() if isinstance(content_type, str) else "" | |
| 88 | 109 | ) |
| 89 | - if keys[0] != first: | |
| 110 | + sources.append({"key": key, "name": name, "content_type": content_type}) | |
| 111 | + if sources[0]["key"] != first and first: | |
| 90 | 112 | raise CapabilityError( |
| 91 | 113 | "bad_request", |
| 92 | - "'source_keys' ilk ogesi 'source_key' ile ayni olmali", | |
| 114 | + "'sources' ilk ogesi 'source_key' ile ayni olmali", | |
| 93 | 115 | ) |
| 94 | - if len(set(keys)) != len(keys): | |
| 95 | - raise CapabilityError("bad_request", "'source_keys' ayni kaynagi tekrar ediyor") | |
| 96 | - return keys | |
| 116 | + if len({item["key"] for item in sources}) != len(sources): | |
| 117 | + raise CapabilityError("bad_request", "'sources' ayni kaynagi tekrar ediyor") | |
| 118 | + return sources[0]["key"], sources | |
| 97 | 119 | |
| 98 | 120 | |
| 99 | 121 | def submit(school: str, payload: dict) -> dict: |
| 100 | 122 | job_id = _require_text(payload, "job_id") |
| 101 | 123 | source_id = _require_text(payload, "source_id") |
| 102 | - source_key = _require_text(payload, "source_key") | |
| 103 | - source_keys = _source_keys(payload, source_key) | |
| 124 | + source_key, sources = _sources(payload) | |
| 104 | 125 | user_id = _require_text(payload, "user_id") |
| 105 | 126 | job_format = _optional_choice(payload, "format", FORMATS, DEFAULT_FORMAT) |
| 106 | 127 | if job_format in LLM_FORMATS and not _llm_ready: |
| @@ -113,7 +134,7 @@ def submit(school: str, payload: dict) -> dict: | ||
| 113 | 134 | try: |
| 114 | 135 | record, eta = store.submit( |
| 115 | 136 | job_id, source_id, job_format, user_id=user_id, school=school, |
| 116 | - source_key=source_key, source_keys=source_keys, | |
| 137 | + source_key=source_key, sources=sources, | |
| 117 | 138 | ) |
| 118 | 139 | except jobs.JobExists as exc: |
| 119 | 140 | raise CapabilityError("conflict", str(exc)) from exc |
src/extract.pymodified+61 -15
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | from __future__ import annotations |
| 2 | 2 | |
| 3 | 3 | import re |
| 4 | +import shutil | |
| 5 | +import subprocess | |
| 4 | 6 | import zipfile |
| 5 | 7 | from pathlib import Path |
| 6 | 8 | from xml.etree import ElementTree |
| @@ -19,6 +21,8 @@ KIND_UNKNOWN = "unknown" | ||
| 19 | 21 | |
| 20 | 22 | UNSUPPORTED_SOURCE = "unsupported_source" |
| 21 | 23 | SOURCE_UNREADABLE = "source_unreadable" |
| 24 | +EXTRACTOR_UNAVAILABLE = "extractor_unavailable" | |
| 25 | +NO_TEXT_LAYER = "no_text_layer" | |
| 22 | 26 | |
| 23 | 27 | PDF_MAGIC = b"%PDF-" |
| 24 | 28 | ZIP_MAGIC = b"PK\x03\x04" |
| @@ -52,13 +56,14 @@ MAX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024 | ||
| 52 | 56 | MAX_MEMBER_BYTES = 16 * 1024 * 1024 |
| 53 | 57 | MAX_TEXT_BYTES = 16 * 1024 * 1024 |
| 54 | 58 | |
| 55 | -READABLE_KINDS = (KIND_PDF, KIND_DOCX, KIND_PPTX, KIND_ODT, KIND_ODP, KIND_TEXT) | |
| 56 | -SUPPORTED_NOTE = "desteklenen bicimler: pdf, docx, pptx, odt, odp, duz metin" | |
| 57 | - | |
| 58 | -OLE_HINT = ( | |
| 59 | - "eski ikili Office bicimi (.doc/.ppt/.xls) desteklenmiyor; " | |
| 60 | - "dosyayi .docx veya .pptx olarak kaydedip yeniden yukleyin" | |
| 59 | +READABLE_KINDS = (KIND_PDF, KIND_DOCX, KIND_PPTX, KIND_ODT, KIND_ODP, KIND_TEXT, KIND_OLE) | |
| 60 | +SUPPORTED_NOTE = ( | |
| 61 | + "desteklenen bicimler: pdf, docx, pptx, doc, ppt, odt, odp, duz metin" | |
| 61 | 62 | ) |
| 63 | + | |
| 64 | +OLE_TOOLS = ("antiword", "catppt") | |
| 65 | +OLE_TIMEOUT_SECS = 60 | |
| 66 | + | |
| 62 | 67 | SHEET_HINT = ( |
| 63 | 68 | "hesap tablosu (.xlsx/.ods) anlatima uygun degil; ders metnini " |
| 64 | 69 | "belge olarak yukleyin" |
| @@ -283,13 +288,7 @@ def odp_slides(path: str | Path) -> list[str]: | ||
| 283 | 288 | return slides |
| 284 | 289 | |
| 285 | 290 | |
| 286 | -def text_blocks(path: str | Path) -> list[str]: | |
| 287 | - raw = _head(path, MAX_TEXT_BYTES + 1) | |
| 288 | - if len(raw) > MAX_TEXT_BYTES: | |
| 289 | - raise ExtractError( | |
| 290 | - SOURCE_UNREADABLE, | |
| 291 | - f"duz metin {MAX_TEXT_BYTES} bayt sinirini asiyor", | |
| 292 | - ) | |
| 291 | +def _decoded_blocks(raw: bytes) -> list[str]: | |
| 293 | 292 | for encoding in TEXT_ENCODINGS: |
| 294 | 293 | try: |
| 295 | 294 | decoded = raw.decode(encoding) |
| @@ -303,9 +302,56 @@ def text_blocks(path: str | Path) -> list[str]: | ||
| 303 | 302 | raise ExtractError(SOURCE_UNREADABLE, "duz metin cozulemedi") |
| 304 | 303 | |
| 305 | 304 | |
| 305 | +def text_blocks(path: str | Path) -> list[str]: | |
| 306 | + raw = _head(path, MAX_TEXT_BYTES + 1) | |
| 307 | + if len(raw) > MAX_TEXT_BYTES: | |
| 308 | + raise ExtractError( | |
| 309 | + SOURCE_UNREADABLE, | |
| 310 | + f"duz metin {MAX_TEXT_BYTES} bayt sinirini asiyor", | |
| 311 | + ) | |
| 312 | + return _decoded_blocks(raw) | |
| 313 | + | |
| 314 | + | |
| 315 | +def ole_blocks(path: str | Path) -> list[str]: | |
| 316 | + outputs: list[bytes] = [] | |
| 317 | + available = False | |
| 318 | + for tool in OLE_TOOLS: | |
| 319 | + binary = shutil.which(tool) | |
| 320 | + if binary is None: | |
| 321 | + continue | |
| 322 | + available = True | |
| 323 | + try: | |
| 324 | + result = subprocess.run( | |
| 325 | + [binary, str(path)], | |
| 326 | + capture_output=True, | |
| 327 | + timeout=OLE_TIMEOUT_SECS, | |
| 328 | + ) | |
| 329 | + except subprocess.TimeoutExpired as exc: | |
| 330 | + raise ExtractError( | |
| 331 | + SOURCE_UNREADABLE, | |
| 332 | + f"{tool} {OLE_TIMEOUT_SECS} sn icinde bitmedi", | |
| 333 | + ) from exc | |
| 334 | + except OSError as exc: | |
| 335 | + raise ExtractError( | |
| 336 | + SOURCE_UNREADABLE, f"{tool} calistirilamadi: {exc}" | |
| 337 | + ) from exc | |
| 338 | + if result.returncode == 0 and result.stdout.strip(): | |
| 339 | + outputs.append(result.stdout) | |
| 340 | + break | |
| 341 | + if not outputs: | |
| 342 | + if not available: | |
| 343 | + raise ExtractError( | |
| 344 | + EXTRACTOR_UNAVAILABLE, | |
| 345 | + "antiword/catppt kurulu degil; eski doc/ppt metni " | |
| 346 | + "cikarilamaz", | |
| 347 | + ) | |
| 348 | + raise ExtractError( | |
| 349 | + SOURCE_UNREADABLE, "eski doc/ppt belgesi okunamadi" | |
| 350 | + ) | |
| 351 | + return _decoded_blocks(outputs[0]) | |
| 352 | + | |
| 353 | + | |
| 306 | 354 | def unsupported_message(kind: str) -> str: |
| 307 | - if kind == KIND_OLE: | |
| 308 | - return OLE_HINT | |
| 309 | 355 | if kind == KIND_SHEET: |
| 310 | 356 | return SHEET_HINT |
| 311 | 357 | if kind == KIND_RTF: |
src/jobs.pymodified+45 -8
| @@ -35,10 +35,29 @@ TRANSITIONS: dict[str, tuple[str, ...]] = { | ||
| 35 | 35 | SIMULATED_STAGES = ("ocr", "plan", "script", "tts", "mux") |
| 36 | 36 | INTERRUPTED_CODE = "interrupted" |
| 37 | 37 | |
| 38 | -def _key_list(keys: list[str] | None, first: str) -> list[str]: | |
| 39 | - if keys: | |
| 40 | - return [str(item) for item in keys] | |
| 41 | - return [str(first)] if first else [] | |
| 38 | +def _sources_list( | |
| 39 | + sources: list[dict[str, Any]] | None, first: str | |
| 40 | +) -> list[dict[str, str]]: | |
| 41 | + if sources: | |
| 42 | + return [ | |
| 43 | + { | |
| 44 | + "key": str(item.get("key", "")), | |
| 45 | + "name": str(item.get("name", "")) or str(item.get("key", "")), | |
| 46 | + "content_type": str(item.get("content_type", "")), | |
| 47 | + "status": str(item.get("status", "pending")), | |
| 48 | + } | |
| 49 | + for item in sources | |
| 50 | + ] | |
| 51 | + if first: | |
| 52 | + return [ | |
| 53 | + { | |
| 54 | + "key": str(first), | |
| 55 | + "name": str(first), | |
| 56 | + "content_type": "", | |
| 57 | + "status": "pending", | |
| 58 | + } | |
| 59 | + ] | |
| 60 | + return [] | |
| 42 | 61 | |
| 43 | 62 | |
| 44 | 63 | REQUIRED_FIELDS = ( |
| @@ -192,8 +211,8 @@ class JobContext: | ||
| 192 | 211 | self.source_id = record["source_id"] |
| 193 | 212 | self.school = record["school"] |
| 194 | 213 | self.source_key = record["source_key"] |
| 195 | - self.source_keys = _key_list( | |
| 196 | - record.get("source_keys"), record["source_key"] | |
| 214 | + self.sources = _sources_list( | |
| 215 | + record.get("sources"), str(record.get("source_key") or "") | |
| 197 | 216 | ) |
| 198 | 217 | self.format = record["format"] |
| 199 | 218 | self.stages = store.stages |
| @@ -634,7 +653,7 @@ class JobStore: | ||
| 634 | 653 | user_id: str = "", |
| 635 | 654 | school: str = "", |
| 636 | 655 | source_key: str = "", |
| 637 | - source_keys: list[str] | None = None, | |
| 656 | + sources: list[dict[str, Any]] | None = None, | |
| 638 | 657 | ) -> tuple[dict[str, Any], int]: |
| 639 | 658 | if not isinstance(job_id, str) or SAFE_JOB_ID.match(job_id) is None: |
| 640 | 659 | raise ValueError(f"gecersiz job_id: {job_id!r}") |
| @@ -649,7 +668,7 @@ class JobStore: | ||
| 649 | 668 | "job_id": job_id, |
| 650 | 669 | "source_id": source_id, |
| 651 | 670 | "source_key": str(source_key), |
| 652 | - "source_keys": _key_list(source_keys, source_key), | |
| 671 | + "sources": _sources_list(sources, str(source_key)), | |
| 653 | 672 | "format": job_format, |
| 654 | 673 | "state": STATE_QUEUED, |
| 655 | 674 | "stage": "", |
| @@ -705,6 +724,24 @@ class JobStore: | ||
| 705 | 724 | self._report_record(snapshot) |
| 706 | 725 | return snapshot |
| 707 | 726 | |
| 727 | + def update_sources( | |
| 728 | + self, job_id: str, sources: list[dict[str, Any]] | |
| 729 | + ) -> dict[str, Any] | None: | |
| 730 | + with self._lock: | |
| 731 | + record = self._jobs.get(job_id) | |
| 732 | + if record is None: | |
| 733 | + raise JobNotFound(job_id) | |
| 734 | + if record["state"] != STATE_RUNNING: | |
| 735 | + return None | |
| 736 | + candidate = dict(record) | |
| 737 | + candidate["sources"] = [ | |
| 738 | + {key: value for key, value in item.items() if key != "path"} | |
| 739 | + for item in sources | |
| 740 | + ] | |
| 741 | + candidate["updated_at"] = _now_ms() | |
| 742 | + self._commit(record, candidate) | |
| 743 | + return dict(candidate) | |
| 744 | + | |
| 708 | 745 | def update_progress( |
| 709 | 746 | self, job_id: str, stage: str, progress: float |
| 710 | 747 | ) -> dict[str, Any] | None: |
tests/unit/test_api_engine.pymodified+74 -2
| @@ -464,7 +464,7 @@ class EngineEndToEndTests(EnvIsolatedTestCase): | ||
| 464 | 464 | self._counter += 1 |
| 465 | 465 | return f"aaaaaaaa-aaaa-7aaa-8aaa-{self._counter:012x}" |
| 466 | 466 | |
| 467 | - def run_job(self, source_id: str, job_format: str): | |
| 467 | + def run_job(self, source_id: str, job_format: str, sources=None): | |
| 468 | 468 | store = jobs.JobStore( |
| 469 | 469 | root=self.job_root, |
| 470 | 470 | workers=1, |
| @@ -485,7 +485,8 @@ class EngineEndToEndTests(EnvIsolatedTestCase): | ||
| 485 | 485 | store.start() |
| 486 | 486 | try: |
| 487 | 487 | job_id = store.submit( |
| 488 | - self.job_id(), source_id, job_format, school="okul-a", source_key=source_id | |
| 488 | + self.job_id(), source_id, job_format, school="okul-a", | |
| 489 | + source_key=source_id, sources=sources, | |
| 489 | 490 | )[0]["job_id"] |
| 490 | 491 | deadline = time.monotonic() + 20.0 |
| 491 | 492 | while time.monotonic() < deadline: |
| @@ -535,6 +536,77 @@ class EngineEndToEndTests(EnvIsolatedTestCase): | ||
| 535 | 536 | self.assertEqual(record["state"], jobs.STATE_DONE) |
| 536 | 537 | self.assertEqual(self.stub.llm_calls(), []) |
| 537 | 538 | |
| 539 | + def test_a_corrupt_middle_source_is_skipped_and_the_job_finishes(self) -> None: | |
| 540 | + from tests.unit.test_extract_formats import docx_bytes | |
| 541 | + | |
| 542 | + (self.media_root / "okul-a" / "not.docx").write_bytes( | |
| 543 | + docx_bytes(["Hucre canliligin temel birimidir. " * 8]) | |
| 544 | + ) | |
| 545 | + (self.media_root / "okul-a" / "bozuk").write_bytes(b"\x00bozuk veri") | |
| 546 | + sources = [ | |
| 547 | + {"key": "not.docx", "name": "Hucre Notu", "content_type": "application/octet-stream"}, | |
| 548 | + {"key": "bozuk", "name": "Bozuk", "content_type": "application/octet-stream"}, | |
| 549 | + {"key": "ders.pdf", "name": "Ders", "content_type": "application/pdf"}, | |
| 550 | + ] | |
| 551 | + record, _ = self.run_job("not.docx", "duz_okuma", sources=sources) | |
| 552 | + self.assertEqual(record["state"], jobs.STATE_DONE, record["error_code"]) | |
| 553 | + self.assertEqual( | |
| 554 | + [item["status"] for item in record["sources"]], | |
| 555 | + ["ok", "skipped:unsupported_source", "ok"], | |
| 556 | + ) | |
| 557 | + | |
| 558 | + def test_a_missing_blob_is_skipped_and_reported(self) -> None: | |
| 559 | + sources = [ | |
| 560 | + {"key": "yok.pdf", "name": "Yok", "content_type": "application/pdf"}, | |
| 561 | + {"key": "ders.pdf", "name": "Ders", "content_type": "application/pdf"}, | |
| 562 | + ] | |
| 563 | + record, _ = self.run_job("yok.pdf", "duz_okuma", sources=sources) | |
| 564 | + self.assertEqual(record["state"], jobs.STATE_DONE, record["error_code"]) | |
| 565 | + self.assertEqual( | |
| 566 | + [item["status"] for item in record["sources"]], | |
| 567 | + ["skipped:source_unreadable", "ok"], | |
| 568 | + ) | |
| 569 | + | |
| 570 | + def test_all_blobs_missing_fails_as_source_not_found(self) -> None: | |
| 571 | + sources = [ | |
| 572 | + {"key": "yok1.pdf", "name": "Yok Bir", "content_type": "application/pdf"}, | |
| 573 | + {"key": "yok2.pdf", "name": "Yok Iki", "content_type": "application/pdf"}, | |
| 574 | + ] | |
| 575 | + record, _ = self.run_job("yok1.pdf", "duz_okuma", sources=sources) | |
| 576 | + self.assertEqual(record["state"], jobs.STATE_FAILED) | |
| 577 | + self.assertEqual(record["error_code"], api_engine.SOURCE_NOT_FOUND) | |
| 578 | + self.assertEqual( | |
| 579 | + [item["status"] for item in record["sources"]], | |
| 580 | + ["skipped:source_unreadable", "skipped:source_unreadable"], | |
| 581 | + ) | |
| 582 | + | |
| 583 | + def test_all_sources_failing_fails_with_the_first_code(self) -> None: | |
| 584 | + (self.media_root / "okul-a" / "bozuk1").write_bytes(b"\x00bozuk bir") | |
| 585 | + (self.media_root / "okul-a" / "bozuk2").write_bytes(b"\x00bozuk iki") | |
| 586 | + sources = [ | |
| 587 | + {"key": "bozuk1", "name": "Bir", "content_type": ""}, | |
| 588 | + {"key": "bozuk2", "name": "Iki", "content_type": ""}, | |
| 589 | + ] | |
| 590 | + record, _ = self.run_job("bozuk1", "duz_okuma", sources=sources) | |
| 591 | + self.assertEqual(record["state"], jobs.STATE_FAILED) | |
| 592 | + self.assertEqual(record["error_code"], api_engine.UNSUPPORTED_SOURCE) | |
| 593 | + self.assertEqual( | |
| 594 | + [item["status"] for item in record["sources"]], | |
| 595 | + ["skipped:unsupported_source", "skipped:unsupported_source"], | |
| 596 | + ) | |
| 597 | + | |
| 598 | + def test_text_below_the_floor_fails_as_no_text_layer(self) -> None: | |
| 599 | + (self.media_root / "okul-a" / "kisa.txt").write_bytes("kisa".encode("utf-8")) | |
| 600 | + sources = [ | |
| 601 | + {"key": "kisa.txt", "name": "Kisa", "content_type": "text/plain"} | |
| 602 | + ] | |
| 603 | + record, _ = self.run_job("kisa.txt", "duz_okuma", sources=sources) | |
| 604 | + self.assertEqual(record["state"], jobs.STATE_FAILED) | |
| 605 | + self.assertEqual(record["error_code"], api_engine.NO_TEXT) | |
| 606 | + self.assertEqual( | |
| 607 | + [item["status"] for item in record["sources"]], ["ok"] | |
| 608 | + ) | |
| 609 | + | |
| 538 | 610 | def test_multiple_chapters_are_muxed_into_one_deliverable(self) -> None: |
| 539 | 611 | self.settings.chapter_chars = 120 |
| 540 | 612 | self.settings.chapter_limit = -1 |
tests/unit/test_capabilities.pymodified+138 -0
| @@ -249,6 +249,144 @@ class SubmitTests(CapabilityTestCase): | ||
| 249 | 249 | }), "internal") |
| 250 | 250 | |
| 251 | 251 | |
| 252 | +class SourcesPayloadTests(CapabilityTestCase): | |
| 253 | + def base_payload(self, **extra: object) -> dict: | |
| 254 | + payload = { | |
| 255 | + "job_id": JOB_ONE, | |
| 256 | + "source_id": "not-1", | |
| 257 | + "user_id": USER_ID, | |
| 258 | + } | |
| 259 | + payload.update(extra) | |
| 260 | + return payload | |
| 261 | + | |
| 262 | + def submit_payload(self, **extra: object) -> dict: | |
| 263 | + return capabilities.dispatch("podcast.submit", "okul-a", self.base_payload(**extra)) | |
| 264 | + | |
| 265 | + def test_missing_key_and_sources_is_bad_request(self) -> None: | |
| 266 | + self.assertEqual( | |
| 267 | + self.error_code("podcast.submit", self.base_payload()), | |
| 268 | + "bad_request", | |
| 269 | + ) | |
| 270 | + | |
| 271 | + def test_a_legacy_key_alone_queues_and_fills_the_sources_list(self) -> None: | |
| 272 | + result = self.submit_payload(source_key="ders.pdf") | |
| 273 | + record = self.store.get(result["job_id"]) | |
| 274 | + self.assertEqual(record["source_key"], "ders.pdf") | |
| 275 | + self.assertEqual( | |
| 276 | + record["sources"], | |
| 277 | + [ | |
| 278 | + { | |
| 279 | + "key": "ders.pdf", | |
| 280 | + "name": "ders.pdf", | |
| 281 | + "content_type": "", | |
| 282 | + "status": "pending", | |
| 283 | + } | |
| 284 | + ], | |
| 285 | + ) | |
| 286 | + | |
| 287 | + def test_sources_alone_queue_and_rekey_the_singular_field(self) -> None: | |
| 288 | + sources = [ | |
| 289 | + {"key": "a.pdf", "name": "Ders Notu", "content_type": "application/pdf"}, | |
| 290 | + {"key": "b.txt", "name": "Ikinci", "content_type": "text/plain"}, | |
| 291 | + ] | |
| 292 | + result = self.submit_payload(sources=sources) | |
| 293 | + record = self.store.get(result["job_id"]) | |
| 294 | + self.assertEqual(record["source_key"], "a.pdf") | |
| 295 | + self.assertEqual( | |
| 296 | + [(item["key"], item["name"], item["content_type"]) for item in record["sources"]], | |
| 297 | + [("a.pdf", "Ders Notu", "application/pdf"), ("b.txt", "Ikinci", "text/plain")], | |
| 298 | + ) | |
| 299 | + self.assertEqual( | |
| 300 | + [item["status"] for item in record["sources"]], ["pending", "pending"] | |
| 301 | + ) | |
| 302 | + | |
| 303 | + def test_a_first_key_mismatch_with_the_singular_field_is_bad_request(self) -> None: | |
| 304 | + sources = [{"key": "b.pdf", "name": "B", "content_type": ""}] | |
| 305 | + self.assertEqual( | |
| 306 | + self.error_code( | |
| 307 | + "podcast.submit", self.base_payload(source_key="a.pdf", sources=sources) | |
| 308 | + ), | |
| 309 | + "bad_request", | |
| 310 | + ) | |
| 311 | + | |
| 312 | + def test_a_non_list_sources_is_bad_request(self) -> None: | |
| 313 | + self.assertEqual( | |
| 314 | + self.error_code( | |
| 315 | + "podcast.submit", self.base_payload(source_key="a.pdf", sources="a.pdf") | |
| 316 | + ), | |
| 317 | + "bad_request", | |
| 318 | + ) | |
| 319 | + | |
| 320 | + def test_an_empty_sources_list_is_bad_request(self) -> None: | |
| 321 | + self.assertEqual( | |
| 322 | + self.error_code( | |
| 323 | + "podcast.submit", self.base_payload(source_key="a.pdf", sources=[]) | |
| 324 | + ), | |
| 325 | + "bad_request", | |
| 326 | + ) | |
| 327 | + | |
| 328 | + def test_a_non_object_member_is_bad_request(self) -> None: | |
| 329 | + self.assertEqual( | |
| 330 | + self.error_code( | |
| 331 | + "podcast.submit", | |
| 332 | + self.base_payload(source_key="a.pdf", sources=["a.pdf"]), | |
| 333 | + ), | |
| 334 | + "bad_request", | |
| 335 | + ) | |
| 336 | + | |
| 337 | + def test_a_key_breaking_the_source_key_rules_is_bad_request(self) -> None: | |
| 338 | + for bad_key in ("", " ", 7, None, "../gizli", "a/b", "a b"): | |
| 339 | + with self.subTest(key=bad_key): | |
| 340 | + sources = [{"key": bad_key, "name": "X", "content_type": ""}] | |
| 341 | + self.assertEqual( | |
| 342 | + self.error_code( | |
| 343 | + "podcast.submit", | |
| 344 | + self.base_payload(source_key="a.pdf", sources=sources), | |
| 345 | + ), | |
| 346 | + "bad_request", | |
| 347 | + ) | |
| 348 | + | |
| 349 | + def test_a_repeated_key_is_bad_request(self) -> None: | |
| 350 | + sources = [ | |
| 351 | + {"key": "a.pdf", "name": "A", "content_type": ""}, | |
| 352 | + {"key": "a.pdf", "name": "A2", "content_type": ""}, | |
| 353 | + ] | |
| 354 | + self.assertEqual( | |
| 355 | + self.error_code( | |
| 356 | + "podcast.submit", self.base_payload(source_key="a.pdf", sources=sources) | |
| 357 | + ), | |
| 358 | + "bad_request", | |
| 359 | + ) | |
| 360 | + | |
| 361 | + def test_more_than_the_ceiling_is_bad_request(self) -> None: | |
| 362 | + sources = [ | |
| 363 | + {"key": f"k{index}.pdf", "name": f"K{index}", "content_type": ""} | |
| 364 | + for index in range(capabilities.MAX_SOURCES + 1) | |
| 365 | + ] | |
| 366 | + self.assertEqual( | |
| 367 | + self.error_code( | |
| 368 | + "podcast.submit", | |
| 369 | + self.base_payload(source_key="k0.pdf", sources=sources), | |
| 370 | + ), | |
| 371 | + "bad_request", | |
| 372 | + ) | |
| 373 | + | |
| 374 | + def test_the_ceiling_itself_is_accepted(self) -> None: | |
| 375 | + sources = [ | |
| 376 | + {"key": f"k{index}.pdf", "name": f"K{index}", "content_type": ""} | |
| 377 | + for index in range(capabilities.MAX_SOURCES) | |
| 378 | + ] | |
| 379 | + result = self.submit_payload(source_key="k0.pdf", sources=sources) | |
| 380 | + record = self.store.get(result["job_id"]) | |
| 381 | + self.assertEqual(len(record["sources"]), capabilities.MAX_SOURCES) | |
| 382 | + | |
| 383 | + def test_a_blank_name_falls_back_to_the_key(self) -> None: | |
| 384 | + sources = [{"key": "a.pdf", "name": " ", "content_type": " "}] | |
| 385 | + result = self.submit_payload(sources=sources) | |
| 386 | + record = self.store.get(result["job_id"]) | |
| 387 | + self.assertEqual(record["sources"][0]["name"], "a.pdf") | |
| 388 | + | |
| 389 | + | |
| 252 | 390 | class StatusResultCancelTests(CapabilityTestCase): |
| 253 | 391 | def test_submitted_job_reports_queued_without_error_code(self) -> None: |
| 254 | 392 | self.submit(JOB_ONE, "x") |
tests/unit/test_extract.pymodified+23 -6
| @@ -85,7 +85,7 @@ class SniffIdentifiesTheFormat(ExtractTestCase): | ||
| 85 | 85 | def test_a_legacy_ole_document_is_named_not_guessed(self) -> None: |
| 86 | 86 | path = self.write("kaynak", extract.OLE_MAGIC + b"\x00" * 32) |
| 87 | 87 | self.assertEqual(extract.sniff(path), extract.KIND_OLE) |
| 88 | - self.assertIn(".docx", extract.unsupported_message(extract.KIND_OLE)) | |
| 88 | + self.assertIn(extract.KIND_OLE, extract.READABLE_KINDS) | |
| 89 | 89 | |
| 90 | 90 | def test_a_plain_zip_is_not_mistaken_for_a_document(self) -> None: |
| 91 | 91 | path = self.write("kaynak", _zip({"okuma.txt": "merhaba"})) |
| @@ -198,14 +198,22 @@ class EngineDispatchesByFormat(ExtractTestCase): | ||
| 198 | 198 | self.assertEqual(blocks, 2) |
| 199 | 199 | self.assertEqual(ocr_pages, 0) |
| 200 | 200 | |
| 201 | - def test_a_legacy_doc_is_refused_with_unsupported_source(self) -> None: | |
| 201 | + def test_a_legacy_doc_dispatches_to_the_ole_extractor(self) -> None: | |
| 202 | + import shutil | |
| 203 | + | |
| 202 | 204 | from src import api_engine |
| 203 | 205 | |
| 204 | 206 | path = self.write("kaynak", extract.OLE_MAGIC + b"\x00" * 64) |
| 205 | 207 | with self.assertRaises(api_engine.EngineError) as raised: |
| 206 | 208 | self._extract(path) |
| 207 | - self.assertEqual(raised.exception.code, api_engine.UNSUPPORTED_SOURCE) | |
| 208 | - self.assertIn(".docx", str(raised.exception)) | |
| 209 | + if shutil.which("antiword") or shutil.which("catppt"): | |
| 210 | + self.assertEqual( | |
| 211 | + raised.exception.code, api_engine.SOURCE_UNREADABLE | |
| 212 | + ) | |
| 213 | + else: | |
| 214 | + self.assertEqual( | |
| 215 | + raised.exception.code, api_engine.EXTRACTOR_UNAVAILABLE | |
| 216 | + ) | |
| 209 | 217 | |
| 210 | 218 | def test_an_unknown_blob_is_refused_with_unsupported_source(self) -> None: |
| 211 | 219 | from src import api_engine |
| @@ -215,14 +223,23 @@ class EngineDispatchesByFormat(ExtractTestCase): | ||
| 215 | 223 | self._extract(path) |
| 216 | 224 | self.assertEqual(raised.exception.code, api_engine.UNSUPPORTED_SOURCE) |
| 217 | 225 | |
| 218 | - def test_a_docx_with_too_little_text_fails_as_no_text_not_as_success(self) -> None: | |
| 226 | + def test_a_docx_with_no_text_at_all_fails_as_no_text_layer(self) -> None: | |
| 219 | 227 | from src import api_engine |
| 220 | 228 | |
| 221 | - path = self.write("kaynak", docx_bytes(["kisa"])) | |
| 229 | + path = self.write("kaynak", docx_bytes(["", " "])) | |
| 222 | 230 | with self.assertRaises(api_engine.EngineError) as raised: |
| 223 | 231 | self._extract(path) |
| 224 | 232 | self.assertEqual(raised.exception.code, api_engine.NO_TEXT) |
| 225 | 233 | |
| 234 | + def test_a_docx_with_a_little_text_still_extracts(self) -> None: | |
| 235 | + from src import api_engine | |
| 236 | + | |
| 237 | + path = self.write("kaynak", docx_bytes(["kisa"])) | |
| 238 | + text, blocks, ocr_pages = self._extract(path) | |
| 239 | + self.assertEqual(text, "kisa") | |
| 240 | + self.assertEqual(blocks, 1) | |
| 241 | + self.assertEqual(ocr_pages, 0) | |
| 242 | + | |
| 226 | 243 | def test_the_error_code_fits_the_backend_limit(self) -> None: |
| 227 | 244 | from src import api_engine |
| 228 | 245 |
tests/unit/test_extract_formats.pymodified+22 -2
| @@ -196,6 +196,28 @@ class RelatedExtensionsNeedNoExtraCode(FormatTestCase): | ||
| 196 | 196 | ) |
| 197 | 197 | |
| 198 | 198 | |
| 199 | +class LegacyOfficeIsRead(FormatTestCase): | |
| 200 | + def test_an_ole_blob_sniffs_as_a_readable_kind(self) -> None: | |
| 201 | + path = self.write("kaynak", extract.OLE_MAGIC + b"\x00" * 32) | |
| 202 | + self.assertEqual(extract.sniff(path), extract.KIND_OLE) | |
| 203 | + self.assertIn(extract.KIND_OLE, extract.READABLE_KINDS) | |
| 204 | + | |
| 205 | + def test_ole_extraction_needs_antiword_or_catppt(self) -> None: | |
| 206 | + import shutil | |
| 207 | + | |
| 208 | + path = self.write("kaynak", extract.OLE_MAGIC + b"\x00" * 32) | |
| 209 | + with self.assertRaises(extract.ExtractError) as raised: | |
| 210 | + extract.ole_blocks(path) | |
| 211 | + if shutil.which("antiword") or shutil.which("catppt"): | |
| 212 | + self.assertEqual( | |
| 213 | + raised.exception.code, extract.SOURCE_UNREADABLE | |
| 214 | + ) | |
| 215 | + else: | |
| 216 | + self.assertEqual( | |
| 217 | + raised.exception.code, extract.EXTRACTOR_UNAVAILABLE | |
| 218 | + ) | |
| 219 | + | |
| 220 | + | |
| 199 | 221 | class RefusedFormatsSayWhyAndWhatToDo(FormatTestCase): |
| 200 | 222 | def test_an_ooxml_spreadsheet_is_named_and_refused(self) -> None: |
| 201 | 223 | path = self.write("kaynak", zip_bytes({"xl/workbook.xml": "<workbook/>"})) |
| @@ -222,7 +244,6 @@ class RefusedFormatsSayWhyAndWhatToDo(FormatTestCase): | ||
| 222 | 244 | for kind in ( |
| 223 | 245 | extract.KIND_ZIP, |
| 224 | 246 | extract.KIND_UNKNOWN, |
| 225 | - extract.KIND_OLE, | |
| 226 | 247 | extract.KIND_SHEET, |
| 227 | 248 | extract.KIND_RTF, |
| 228 | 249 | ): |
| @@ -232,7 +253,6 @@ class RefusedFormatsSayWhyAndWhatToDo(FormatTestCase): | ||
| 232 | 253 | |
| 233 | 254 | def test_a_refused_kind_is_never_in_the_readable_set(self) -> None: |
| 234 | 255 | for kind in ( |
| 235 | - extract.KIND_OLE, | |
| 236 | 256 | extract.KIND_SHEET, |
| 237 | 257 | extract.KIND_RTF, |
| 238 | 258 | extract.KIND_ZIP, |
tests/unit/test_multi_source.pymodified+196 -107
| @@ -2,15 +2,17 @@ from __future__ import annotations | ||
| 2 | 2 | |
| 3 | 3 | import sys |
| 4 | 4 | import tempfile |
| 5 | +import time | |
| 5 | 6 | import unittest |
| 6 | 7 | from pathlib import Path |
| 7 | 8 | |
| 8 | 9 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) |
| 9 | 10 | |
| 10 | -from src import api_engine, capabilities, config, jobs | |
| 11 | +from src import api_engine, config, jobs | |
| 11 | 12 | from tests.unit.test_extract_formats import docx_bytes, odt_bytes, pptx_bytes |
| 12 | 13 | |
| 13 | 14 | LONG = "Hucre canliligin temel birimidir. " * 8 |
| 15 | +SCHOOL = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d" | |
| 14 | 16 | |
| 15 | 17 | |
| 16 | 18 | class MultiSourceTestCase(unittest.TestCase): |
| @@ -20,16 +22,16 @@ class MultiSourceTestCase(unittest.TestCase): | ||
| 20 | 22 | self._tmp = tempfile.TemporaryDirectory(prefix="coklu-") |
| 21 | 23 | self.root = Path(self._tmp.name) |
| 22 | 24 | self.media = self.root / "medya" |
| 23 | - self.school = "okul-a" | |
| 24 | - (self.media / self.school).mkdir(parents=True) | |
| 25 | + (self.media / SCHOOL).mkdir(parents=True) | |
| 25 | 26 | |
| 26 | 27 | def tearDown(self) -> None: |
| 27 | 28 | self._tmp.cleanup() |
| 28 | 29 | config._active_level = self._log_level |
| 29 | 30 | |
| 30 | - def source(self, key: str, data: bytes) -> str: | |
| 31 | - (self.media / self.school / key).write_bytes(data) | |
| 32 | - return key | |
| 31 | + def source(self, key: str, data: bytes) -> Path: | |
| 32 | + path = self.media / SCHOOL / key | |
| 33 | + path.write_bytes(data) | |
| 34 | + return path | |
| 33 | 35 | |
| 34 | 36 | def settings(self): |
| 35 | 37 | settings = config.Config(require_token=False) |
| @@ -37,156 +39,243 @@ class MultiSourceTestCase(unittest.TestCase): | ||
| 37 | 39 | return settings |
| 38 | 40 | |
| 39 | 41 | |
| 40 | -class SourceKeysAreValidated(unittest.TestCase): | |
| 41 | - def _payload(self, **extra): | |
| 42 | - payload = { | |
| 43 | - "job_id": "aaaaaaaa-aaaa-7aaa-8aaa-000000000001", | |
| 44 | - "source_id": "not-1", | |
| 45 | - "source_key": "a", | |
| 46 | - "user_id": "kullanici-1", | |
| 47 | - } | |
| 48 | - payload.update(extra) | |
| 49 | - return payload | |
| 50 | - | |
| 51 | - def test_a_missing_list_falls_back_to_the_single_key(self) -> None: | |
| 52 | - self.assertEqual( | |
| 53 | - capabilities._source_keys(self._payload(), "a"), ["a"] | |
| 54 | - ) | |
| 55 | - | |
| 56 | - def test_a_non_list_is_a_bad_request(self) -> None: | |
| 57 | - with self.assertRaises(capabilities.CapabilityError) as raised: | |
| 58 | - capabilities._source_keys(self._payload(source_keys="a"), "a") | |
| 59 | - self.assertEqual(raised.exception.code, "bad_request") | |
| 60 | - | |
| 61 | - def test_an_empty_list_is_a_bad_request(self) -> None: | |
| 62 | - with self.assertRaises(capabilities.CapabilityError): | |
| 63 | - capabilities._source_keys(self._payload(source_keys=[]), "a") | |
| 64 | - | |
| 65 | - def test_a_blank_member_is_a_bad_request(self) -> None: | |
| 66 | - with self.assertRaises(capabilities.CapabilityError): | |
| 67 | - capabilities._source_keys(self._payload(source_keys=["a", " "]), "a") | |
| 68 | - | |
| 69 | - def test_a_repeated_source_is_a_bad_request(self) -> None: | |
| 70 | - with self.assertRaises(capabilities.CapabilityError) as raised: | |
| 71 | - capabilities._source_keys(self._payload(source_keys=["a", "b", "a"]), "a") | |
| 72 | - self.assertIn("tekrar", str(raised.exception)) | |
| 73 | - | |
| 74 | - def test_the_first_key_must_match_the_singular_field(self) -> None: | |
| 75 | - with self.assertRaises(capabilities.CapabilityError) as raised: | |
| 76 | - capabilities._source_keys(self._payload(source_keys=["b", "a"]), "a") | |
| 77 | - self.assertIn("ilk ogesi", str(raised.exception)) | |
| 78 | - | |
| 79 | - def test_more_than_the_ceiling_is_refused(self) -> None: | |
| 80 | - keys = ["a"] + [f"k{index}" for index in range(capabilities.MAX_SOURCES)] | |
| 81 | - with self.assertRaises(capabilities.CapabilityError) as raised: | |
| 82 | - capabilities._source_keys(self._payload(source_keys=keys), "a") | |
| 83 | - self.assertEqual(raised.exception.code, "bad_request") | |
| 84 | - | |
| 85 | - def test_the_ceiling_itself_is_accepted(self) -> None: | |
| 86 | - keys = ["a"] + [f"k{index}" for index in range(capabilities.MAX_SOURCES - 1)] | |
| 87 | - self.assertEqual( | |
| 88 | - len(capabilities._source_keys(self._payload(source_keys=keys), "a")), | |
| 89 | - capabilities.MAX_SOURCES, | |
| 90 | - ) | |
| 91 | - | |
| 92 | - | |
| 93 | -class TheRecordKeepsBothShapes(MultiSourceTestCase): | |
| 42 | +class TheRecordCarriesSources(MultiSourceTestCase): | |
| 94 | 43 | def make_store(self) -> jobs.JobStore: |
| 95 | - store = jobs.JobStore(root=self.root / "isler", workers=1, max_jobs=64, | |
| 96 | - stage_secs=0.0) | |
| 44 | + store = jobs.JobStore( | |
| 45 | + root=self.root / "isler", workers=1, max_jobs=64, stage_secs=0.0 | |
| 46 | + ) | |
| 97 | 47 | self.addCleanup(store.shutdown, 1.0) |
| 98 | 48 | return store |
| 99 | 49 | |
| 100 | 50 | def test_the_singular_field_stays_the_first_source(self) -> None: |
| 101 | 51 | store = self.make_store() |
| 52 | + sources = [ | |
| 53 | + {"key": "bir", "name": "Birinci", "content_type": "application/pdf"}, | |
| 54 | + {"key": "iki", "name": "Ikinci", "content_type": "text/plain"}, | |
| 55 | + ] | |
| 102 | 56 | record, _ = store.submit( |
| 103 | - "aaaaaaaa-aaaa-7aaa-8aaa-000000000001", "not-1", "duz_okuma", | |
| 104 | - source_key="bir", source_keys=["bir", "iki", "uc"], | |
| 57 | + "aaaaaaaa-aaaa-7aaa-8aaa-000000000001", | |
| 58 | + "not-1", | |
| 59 | + "duz_okuma", | |
| 60 | + source_key="bir", | |
| 61 | + sources=sources, | |
| 105 | 62 | ) |
| 106 | 63 | self.assertEqual(record["source_key"], "bir") |
| 107 | - self.assertEqual(record["source_keys"], ["bir", "iki", "uc"]) | |
| 64 | + self.assertEqual( | |
| 65 | + record["sources"], | |
| 66 | + [ | |
| 67 | + { | |
| 68 | + "key": "bir", | |
| 69 | + "name": "Birinci", | |
| 70 | + "content_type": "application/pdf", | |
| 71 | + "status": "pending", | |
| 72 | + }, | |
| 73 | + { | |
| 74 | + "key": "iki", | |
| 75 | + "name": "Ikinci", | |
| 76 | + "content_type": "text/plain", | |
| 77 | + "status": "pending", | |
| 78 | + }, | |
| 79 | + ], | |
| 80 | + ) | |
| 108 | 81 | |
| 109 | - def test_a_single_source_job_still_fills_the_plural_field(self) -> None: | |
| 82 | + def test_a_legacy_single_key_submit_fills_the_sources_list(self) -> None: | |
| 110 | 83 | store = self.make_store() |
| 111 | 84 | record, _ = store.submit( |
| 112 | - "aaaaaaaa-aaaa-7aaa-8aaa-000000000002", "not-1", "duz_okuma", | |
| 85 | + "aaaaaaaa-aaaa-7aaa-8aaa-000000000002", | |
| 86 | + "not-1", | |
| 87 | + "duz_okuma", | |
| 113 | 88 | source_key="tek", |
| 114 | 89 | ) |
| 115 | - self.assertEqual(record["source_keys"], ["tek"]) | |
| 90 | + self.assertEqual( | |
| 91 | + record["sources"], | |
| 92 | + [ | |
| 93 | + { | |
| 94 | + "key": "tek", | |
| 95 | + "name": "tek", | |
| 96 | + "content_type": "", | |
| 97 | + "status": "pending", | |
| 98 | + } | |
| 99 | + ], | |
| 100 | + ) | |
| 116 | 101 | |
| 117 | - def test_source_keys_is_not_a_required_field(self) -> None: | |
| 102 | + def test_sources_is_not_a_required_field(self) -> None: | |
| 118 | 103 | self.assertNotIn( |
| 119 | - "source_keys", | |
| 104 | + "sources", | |
| 120 | 105 | jobs.REQUIRED_FIELDS, |
| 121 | 106 | "REQUIRED_FIELDS'a eklenirse alan eklenmeden once yazilmis eski " |
| 122 | 107 | "kayitlar acilista topluca atilir", |
| 123 | 108 | ) |
| 124 | 109 | |
| 125 | - def test_an_old_record_without_the_plural_field_still_loads(self) -> None: | |
| 110 | + def test_an_old_record_without_sources_still_loads(self) -> None: | |
| 126 | 111 | store = self.make_store() |
| 127 | 112 | job_id = "aaaaaaaa-aaaa-7aaa-8aaa-000000000003" |
| 128 | - record, _ = store.submit(job_id, "not-1", "duz_okuma", source_key="eski") | |
| 113 | + store.submit(job_id, "not-1", "duz_okuma", source_key="eski") | |
| 129 | 114 | path = Path(store.root) / f"{job_id}.json" |
| 130 | 115 | import json |
| 131 | 116 | |
| 132 | 117 | data = json.loads(path.read_text(encoding="utf-8")) |
| 133 | - data.pop("source_keys", None) | |
| 118 | + data.pop("sources", None) | |
| 134 | 119 | path.write_text(json.dumps(data), encoding="utf-8") |
| 135 | - reopened = jobs.JobStore(root=store.root, workers=1, max_jobs=64, | |
| 136 | - stage_secs=0.0) | |
| 120 | + reopened = jobs.JobStore( | |
| 121 | + root=store.root, workers=1, max_jobs=64, stage_secs=0.0 | |
| 122 | + ) | |
| 137 | 123 | self.addCleanup(reopened.shutdown, 1.0) |
| 138 | 124 | loaded = reopened.get(job_id) |
| 139 | 125 | self.assertEqual(loaded["source_key"], "eski") |
| 140 | 126 | context = jobs.JobContext(reopened, job_id) |
| 141 | 127 | self.assertEqual( |
| 142 | - context.source_keys, | |
| 128 | + [item["key"] for item in context.sources], | |
| 143 | 129 | ["eski"], |
| 144 | - "cogul alani olmayan eski kayit tekil alandan turetilmeli", | |
| 130 | + "sources alani olmayan eski kayit tekil alandan turetilmeli", | |
| 131 | + ) | |
| 132 | + | |
| 133 | + def test_sources_survive_a_full_job_lifecycle(self) -> None: | |
| 134 | + store = self.make_store() | |
| 135 | + store.start() | |
| 136 | + job_id = "aaaaaaaa-aaaa-7aaa-8aaa-000000000004" | |
| 137 | + store.submit( | |
| 138 | + job_id, | |
| 139 | + "not-1", | |
| 140 | + "duz_okuma", | |
| 141 | + school=SCHOOL, | |
| 142 | + source_key="tek", | |
| 143 | + sources=[ | |
| 144 | + {"key": "tek", "name": "Tek", "content_type": "text/plain"} | |
| 145 | + ], | |
| 146 | + ) | |
| 147 | + deadline = time.monotonic() + 10.0 | |
| 148 | + record = store.get(job_id) | |
| 149 | + while record["state"] not in jobs.TERMINAL_STATES: | |
| 150 | + if time.monotonic() > deadline: | |
| 151 | + self.fail("sahte is zaman asiminda bitmedi") | |
| 152 | + time.sleep(0.02) | |
| 153 | + record = store.get(job_id) | |
| 154 | + self.assertEqual( | |
| 155 | + record["sources"], | |
| 156 | + [ | |
| 157 | + { | |
| 158 | + "key": "tek", | |
| 159 | + "name": "Tek", | |
| 160 | + "content_type": "text/plain", | |
| 161 | + "status": "pending", | |
| 162 | + } | |
| 163 | + ], | |
| 164 | + ) | |
| 165 | + | |
| 166 | + def test_update_sources_needs_a_running_job(self) -> None: | |
| 167 | + store = self.make_store() | |
| 168 | + record, _ = store.submit( | |
| 169 | + "aaaaaaaa-aaaa-7aaa-8aaa-000000000005", | |
| 170 | + "not-1", | |
| 171 | + "duz_okuma", | |
| 172 | + source_key="tek", | |
| 145 | 173 | ) |
| 174 | + self.assertIsNone( | |
| 175 | + store.update_sources(record["job_id"], record["sources"]), | |
| 176 | + "kuyruktaki bir isin kaynak durumu guncellenmemeli", | |
| 177 | + ) | |
| 178 | + with self.assertRaises(jobs.JobNotFound): | |
| 179 | + store.update_sources("aaaaaaaa-aaaa-7aaa-8aaa-999999999999", []) | |
| 146 | 180 | |
| 147 | 181 | |
| 148 | 182 | class SourcesAreCombinedIntoOneText(MultiSourceTestCase): |
| 149 | - def test_three_documents_of_different_formats_become_one_text(self) -> None: | |
| 150 | - paths = [ | |
| 151 | - self.media / self.school / self.source("a", docx_bytes([LONG + "birinci"])), | |
| 152 | - self.media / self.school / self.source("b", pptx_bytes([[LONG + "ikinci"]])), | |
| 153 | - self.media / self.school / self.source("c", odt_bytes([LONG + "ucuncu"])), | |
| 154 | - ] | |
| 183 | + def documents(self, *pairs: tuple[str, Path]) -> list[dict]: | |
| 184 | + return [{"name": name, "path": path} for name, path in pairs] | |
| 185 | + | |
| 186 | + def test_three_documents_are_merged_with_per_document_headers(self) -> None: | |
| 187 | + docs = self.documents( | |
| 188 | + ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), | |
| 189 | + ("Ikinci", self.source("b", pptx_bytes([[LONG + "ikinci"]]))), | |
| 190 | + ("Ucuncu", self.source("c", odt_bytes([LONG + "ucuncu"]))), | |
| 191 | + ) | |
| 155 | 192 | text, blocks, ocr = api_engine.extract_sources( |
| 156 | - paths, self.settings(), lambda: None | |
| 193 | + docs, self.settings(), lambda: None | |
| 157 | 194 | ) |
| 158 | 195 | self.assertIn("birinci", text) |
| 159 | 196 | self.assertIn("ikinci", text) |
| 160 | 197 | self.assertIn("ucuncu", text) |
| 198 | + self.assertIn("\n\n=== Ikinci ===\n\n", text) | |
| 199 | + self.assertIn("\n\n=== Ucuncu ===\n\n", text) | |
| 200 | + self.assertLess(text.index("birinci"), text.index("=== Ikinci ===")) | |
| 201 | + self.assertLess(text.index("=== Ikinci ==="), text.index("ikinci")) | |
| 202 | + self.assertLess(text.index("ikinci"), text.index("=== Ucuncu ===")) | |
| 161 | 203 | self.assertEqual(blocks, 3) |
| 162 | 204 | self.assertEqual(ocr, 0) |
| 205 | + self.assertEqual( | |
| 206 | + [item["status"] for item in docs], ["ok", "ok", "ok"] | |
| 207 | + ) | |
| 163 | 208 | |
| 164 | 209 | def test_the_submitted_order_is_preserved(self) -> None: |
| 165 | - paths = [ | |
| 166 | - self.media / self.school / self.source("a", docx_bytes([LONG + "ALFA"])), | |
| 167 | - self.media / self.school / self.source("b", docx_bytes([LONG + "BETA"])), | |
| 168 | - ] | |
| 169 | - text, _, _ = api_engine.extract_sources(paths, self.settings(), lambda: None) | |
| 210 | + docs = self.documents( | |
| 211 | + ("Alfa", self.source("a", docx_bytes([LONG + "ALFA"]))), | |
| 212 | + ("Beta", self.source("b", docx_bytes([LONG + "BETA"]))), | |
| 213 | + ) | |
| 214 | + text, _, _ = api_engine.extract_sources( | |
| 215 | + docs, self.settings(), lambda: None | |
| 216 | + ) | |
| 170 | 217 | self.assertLess( |
| 171 | - text.index("ALFA"), text.index("BETA"), | |
| 218 | + text.index("ALFA"), | |
| 219 | + text.index("BETA"), | |
| 172 | 220 | "kaynaklar gonderildikleri sirayla birlestirilmeli", |
| 173 | 221 | ) |
| 174 | 222 | |
| 175 | - def test_a_single_source_behaves_exactly_as_before(self) -> None: | |
| 176 | - path = self.media / self.school / self.source("a", docx_bytes([LONG])) | |
| 177 | - birlesik = api_engine.extract_sources([path], self.settings(), lambda: None) | |
| 223 | + def test_a_single_source_has_no_header(self) -> None: | |
| 224 | + path = self.source("a", docx_bytes([LONG])) | |
| 225 | + docs = self.documents(("Tek", path)) | |
| 226 | + birlesik = api_engine.extract_sources( | |
| 227 | + docs, self.settings(), lambda: None | |
| 228 | + ) | |
| 178 | 229 | tekil = api_engine.extract_text(str(path), self.settings(), lambda: None) |
| 179 | 230 | self.assertEqual(birlesik, tekil) |
| 231 | + self.assertNotIn("===", birlesik[0]) | |
| 180 | 232 | |
| 181 | - def test_an_unreadable_source_fails_the_job_and_names_which_one(self) -> None: | |
| 182 | - paths = [ | |
| 183 | - self.media / self.school / self.source("a", docx_bytes([LONG])), | |
| 184 | - self.media / self.school / self.source("b", b"\x00bozuk veri"), | |
| 185 | - ] | |
| 186 | - with self.assertRaises(api_engine.EngineError) as raised: | |
| 187 | - api_engine.extract_sources(paths, self.settings(), lambda: None) | |
| 188 | - self.assertEqual(raised.exception.code, api_engine.UNSUPPORTED_SOURCE) | |
| 189 | - self.assertIn("2. kaynak", str(raised.exception)) | |
| 233 | + def test_a_corrupt_source_is_skipped_and_the_rest_continue(self) -> None: | |
| 234 | + docs = self.documents( | |
| 235 | + ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), | |
| 236 | + ("Bozuk", self.source("b", b"\x00bozuk veri")), | |
| 237 | + ("Ucuncu", self.source("c", odt_bytes([LONG + "ucuncu"]))), | |
| 238 | + ) | |
| 239 | + text, _, _ = api_engine.extract_sources( | |
| 240 | + docs, self.settings(), lambda: None | |
| 241 | + ) | |
| 242 | + self.assertIn("birinci", text) | |
| 243 | + self.assertIn("ucuncu", text) | |
| 244 | + self.assertNotIn("bozuk veri", text) | |
| 245 | + self.assertEqual( | |
| 246 | + [item["status"] for item in docs], | |
| 247 | + ["ok", "skipped:unsupported_source", "ok"], | |
| 248 | + ) | |
| 249 | + | |
| 250 | + def test_a_textless_source_is_skipped_as_no_text_layer(self) -> None: | |
| 251 | + docs = self.documents( | |
| 252 | + ("Birinci", self.source("a", docx_bytes([LONG + "birinci"]))), | |
| 253 | + ("Bos", self.source("b", docx_bytes(["", " "]))), | |
| 254 | + ) | |
| 255 | + text, _, _ = api_engine.extract_sources( | |
| 256 | + docs, self.settings(), lambda: None | |
| 257 | + ) | |
| 258 | + self.assertIn("birinci", text) | |
| 259 | + self.assertEqual( | |
| 260 | + [item["status"] for item in docs], | |
| 261 | + ["ok", "skipped:no_text_layer"], | |
| 262 | + ) | |
| 263 | + | |
| 264 | + def test_all_sources_failing_yields_an_empty_merge_with_statuses(self) -> None: | |
| 265 | + docs = self.documents( | |
| 266 | + ("Birinci", self.source("a", b"\x00bozuk veri")), | |
| 267 | + ("Ikinci", self.source("b", docx_bytes(["", ""]))), | |
| 268 | + ) | |
| 269 | + text, blocks, ocr = api_engine.extract_sources( | |
| 270 | + docs, self.settings(), lambda: None | |
| 271 | + ) | |
| 272 | + self.assertEqual(text, "") | |
| 273 | + self.assertEqual(blocks, 0) | |
| 274 | + self.assertEqual(ocr, 0) | |
| 275 | + self.assertEqual( | |
| 276 | + [item["status"] for item in docs], | |
| 277 | + ["skipped:unsupported_source", "skipped:no_text_layer"], | |
| 278 | + ) | |
| 190 | 279 | |
| 191 | 280 | def test_no_source_at_all_is_refused(self) -> None: |
| 192 | 281 | with self.assertRaises(api_engine.EngineError) as raised: |
| @@ -194,10 +283,10 @@ class SourcesAreCombinedIntoOneText(MultiSourceTestCase): | ||
| 194 | 283 | self.assertEqual(raised.exception.code, api_engine.SOURCE_NOT_FOUND) |
| 195 | 284 | |
| 196 | 285 | def test_cancellation_is_checked_between_sources(self) -> None: |
| 197 | - paths = [ | |
| 198 | - self.media / self.school / self.source("a", docx_bytes([LONG])), | |
| 199 | - self.media / self.school / self.source("b", docx_bytes([LONG])), | |
| 200 | - ] | |
| 286 | + docs = self.documents( | |
| 287 | + ("Birinci", self.source("a", docx_bytes([LONG]))), | |
| 288 | + ("Ikinci", self.source("b", docx_bytes([LONG]))), | |
| 289 | + ) | |
| 201 | 290 | cagrilar = [] |
| 202 | 291 | |
| 203 | 292 | def check(): |
| @@ -206,7 +295,7 @@ class SourcesAreCombinedIntoOneText(MultiSourceTestCase): | ||
| 206 | 295 | raise jobs.JobCancelled("iptal") |
| 207 | 296 | |
| 208 | 297 | with self.assertRaises(jobs.JobCancelled): |
| 209 | - api_engine.extract_sources(paths, self.settings(), check) | |
| 298 | + api_engine.extract_sources(docs, self.settings(), check) | |
| 210 | 299 | |
| 211 | 300 | |
| 212 | 301 | if __name__ == "__main__": |