| 1 | from __future__ import annotations |
| 2 | |
| 3 | import json |
| 4 | import os |
| 5 | import re |
| 6 | import shutil |
| 7 | import subprocess |
| 8 | import tempfile |
| 9 | from pathlib import Path |
| 10 | from typing import Any, Callable |
| 11 | |
| 12 | from . import capabilities, config, extract, jobs, llm, tts |
| 13 | |
| 14 | STAGES = ("kaynak", "metin", "script", "tts", "mux") |
| 15 | ETA_SECS = 300.0 |
| 16 | |
| 17 | SOURCE_NOT_FOUND = "source_not_found" |
| 18 | NO_TEXT = "no_text_layer" |
| 19 | SOURCE_UNREADABLE = "source_unreadable" |
| 20 | UNSUPPORTED_SOURCE = "unsupported_source" |
| 21 | EXTRACTOR_UNAVAILABLE = "extractor_unavailable" |
| 22 | SCRIPT_EMPTY = "script_empty" |
| 23 | MUX_ERROR = "mux_error" |
| 24 | OUTPUT_UNWRITABLE = "output_unwritable" |
| 25 | |
| 26 | OCR_DPI = 200 |
| 27 | TITLE_CHARS = 72 |
| 28 | WHITESPACE = re.compile(r"[ \t\r\f\v]+") |
| 29 | BLANK_LINES = re.compile(r"\n{3,}") |
| 30 | MARKUP = re.compile(r"[*_`#>]+") |
| 31 | |
| 32 | DIR_SCRIPT = "script" |
| 33 | DIR_AUDIO = "ses" |
| 34 | WORK_PREFIX = ".is-" |
| 35 | |
| 36 | SYSTEM_PROMPT = ( |
| 37 | "Sen bir Turkce egitim podcast'i icin metin hazirlayan bir yazarsin. " |
| 38 | "Yalnizca sesli okunacak duz metin dondurursun: baslik, madde imi, " |
| 39 | "yildiz, emoji ve bicimlendirme KULLANMAZSIN." |
| 40 | ) |
| 41 | TEACHER_PROMPT = ( |
| 42 | "Asagidaki ders metnini tek bir ogretmenin akici sesli anlatimina cevir. " |
| 43 | "Bilgileri koru, yeni bilgi ekleme, Turkce yaz. " |
| 44 | "Yalnizca anlatim metnini dondur.\n\n{metin}" |
| 45 | ) |
| 46 | DIALOGUE_PROMPT = ( |
| 47 | "Asagidaki ders metnini iki konusanli bir diyaloga cevir: ogrenci sorar, " |
| 48 | "hoca anlatir. Her satir 'Ogrenci: ' ya da 'Hoca: ' ile baslasin. " |
| 49 | "Yeni bilgi ekleme, Turkce yaz. Yalnizca diyalog metnini dondur.\n\n{metin}" |
| 50 | ) |
| 51 | PROMPTS = { |
| 52 | "tek_ogretici": TEACHER_PROMPT, |
| 53 | "ogrenci_hoca": DIALOGUE_PROMPT, |
| 54 | } |
| 55 | |
| 56 | |
| 57 | class EngineError(Exception): |
| 58 | def __init__(self, code: str, message: str) -> None: |
| 59 | super().__init__(message) |
| 60 | self.code = code |
| 61 | |
| 62 | |
| 63 | def _source_path(media_root: str, school: str, source_key: str) -> Path: |
| 64 | path = jobs.resolve_source(media_root, school, source_key) |
| 65 | if not path.is_file(): |
| 66 | raise FileNotFoundError(f"kaynak dosya yok: {path}") |
| 67 | return path |
| 68 | |
| 69 | |
| 70 | def _clean_text(text: str) -> str: |
| 71 | collapsed = WHITESPACE.sub(" ", text) |
| 72 | collapsed = BLANK_LINES.sub("\n\n", collapsed) |
| 73 | return collapsed.strip() |
| 74 | |
| 75 | |
| 76 | def _spoken_text(text: str) -> str: |
| 77 | lines = [] |
| 78 | for line in text.splitlines(): |
| 79 | stripped = MARKUP.sub("", line).strip().lstrip("-").strip() |
| 80 | if stripped: |
| 81 | lines.append(stripped) |
| 82 | return "\n".join(lines).strip() |
| 83 | |
| 84 | |
| 85 | def _chapter_title(text: str) -> str: |
| 86 | head = text[:TITLE_CHARS].strip() |
| 87 | return head if head else "bolum" |
| 88 | |
| 89 | |
| 90 | def split_chapters(text: str, limit_chars: int, limit: int | None) -> list[str]: |
| 91 | words = text.split() |
| 92 | chunks: list[str] = [] |
| 93 | current: list[str] = [] |
| 94 | size = 0 |
| 95 | for word in words: |
| 96 | if current and size + len(word) + 1 > limit_chars: |
| 97 | chunks.append(" ".join(current)) |
| 98 | current = [] |
| 99 | size = 0 |
| 100 | current.append(word) |
| 101 | size += len(word) + 1 |
| 102 | if current: |
| 103 | chunks.append(" ".join(current)) |
| 104 | if limit is not None: |
| 105 | return chunks[:limit] |
| 106 | return chunks |
| 107 | |
| 108 | |
| 109 | def _page_texts(doc: Any, settings: Any, check: Callable[[], None]) -> tuple[list[str], int, bool]: |
| 110 | tesseract = shutil.which("tesseract") |
| 111 | texts: list[str] = [] |
| 112 | ocr_pages = 0 |
| 113 | for page in doc: |
| 114 | check() |
| 115 | raw = page.get_text("text") |
| 116 | if len(raw.strip()) < int(settings.ocr_page_min_chars) and tesseract: |
| 117 | try: |
| 118 | layer = page.get_textpage_ocr( |
| 119 | language=settings.ocr_language, dpi=OCR_DPI |
| 120 | ) |
| 121 | candidate = page.get_text("text", textpage=layer) |
| 122 | except Exception as exc: |
| 123 | config.log("warn", f"sayfa OCR yapilamadi: {exc}") |
| 124 | candidate = "" |
| 125 | if len(candidate.strip()) > len(raw.strip()): |
| 126 | texts.append(candidate) |
| 127 | ocr_pages += 1 |
| 128 | continue |
| 129 | texts.append(raw) |
| 130 | return texts, ocr_pages, bool(tesseract) |
| 131 | |
| 132 | |
| 133 | def extract_text( |
| 134 | path: str, settings: Any, check: Callable[[], None] |
| 135 | ) -> tuple[str, int, int]: |
| 136 | try: |
| 137 | kind = extract.sniff(path) |
| 138 | except extract.ExtractError as exc: |
| 139 | raise EngineError(SOURCE_UNREADABLE, str(exc)) from exc |
| 140 | if kind == extract.KIND_PDF: |
| 141 | return _extract_pdf(path, settings, check) |
| 142 | readers = { |
| 143 | extract.KIND_DOCX: extract.docx_blocks, |
| 144 | extract.KIND_PPTX: extract.pptx_slides, |
| 145 | extract.KIND_ODT: extract.odt_blocks, |
| 146 | extract.KIND_ODP: extract.odp_slides, |
| 147 | extract.KIND_TEXT: extract.text_blocks, |
| 148 | extract.KIND_OLE: extract.ole_blocks, |
| 149 | } |
| 150 | reader = readers.get(kind) |
| 151 | if reader is None: |
| 152 | raise EngineError(UNSUPPORTED_SOURCE, extract.unsupported_message(kind)) |
| 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 |
| 163 | |
| 164 | |
| 165 | def _extract_pdf( |
| 166 | path: str, settings: Any, check: Callable[[], None] |
| 167 | ) -> tuple[str, int, int]: |
| 168 | try: |
| 169 | import pymupdf |
| 170 | except ImportError as exc: |
| 171 | raise EngineError( |
| 172 | EXTRACTOR_UNAVAILABLE, f"pymupdf kurulu degil; PDF metni cikarilamaz: {exc}" |
| 173 | ) from exc |
| 174 | try: |
| 175 | doc = pymupdf.open(path) |
| 176 | except Exception as exc: |
| 177 | raise EngineError( |
| 178 | SOURCE_UNREADABLE, f"PDF acilamadi ({type(exc).__name__}): {exc}" |
| 179 | ) from exc |
| 180 | try: |
| 181 | pages, ocr_pages, tesseract = _page_texts(doc, settings, check) |
| 182 | finally: |
| 183 | doc.close() |
| 184 | text = _clean_text("\n".join(pages)) |
| 185 | if not text: |
| 186 | reason = ( |
| 187 | "sayfalarda metin katmani yok" |
| 188 | if tesseract |
| 189 | else "sayfalarda metin katmani yok ve tesseract kurulu degil " |
| 190 | "(tesseract-ocr + tesseract-ocr-tur gerekir)" |
| 191 | ) |
| 192 | raise EngineError(NO_TEXT, reason) |
| 193 | if ocr_pages: |
| 194 | config.log("info", f"OCR {ocr_pages} sayfada kullanildi: {path}") |
| 195 | return text, len(pages), ocr_pages |
| 196 | |
| 197 | |
| 198 | SOURCE_HEADER = "\n\n=== {name} ===\n\n" |
| 199 | |
| 200 | |
| 201 | def extract_sources( |
| 202 | sources: list[dict[str, Any]], settings: Any, check: Callable[[], None] |
| 203 | ) -> tuple[str, int, int]: |
| 204 | if not sources: |
| 205 | raise EngineError(SOURCE_NOT_FOUND, "is icin hic kaynak verilmedi") |
| 206 | parts: list[str] = [] |
| 207 | pages = 0 |
| 208 | ocr_pages = 0 |
| 209 | for source in sources: |
| 210 | check() |
| 211 | path = source.get("path") |
| 212 | if path is None: |
| 213 | continue |
| 214 | try: |
| 215 | text, page_count, ocr = extract_text(str(path), settings, check) |
| 216 | except EngineError as 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"])) |
| 226 | parts.append(text) |
| 227 | pages += page_count |
| 228 | ocr_pages += ocr |
| 229 | return "".join(parts), pages, ocr_pages |
| 230 | |
| 231 | |
| 232 | def _write_bytes(path: Path, data: bytes) -> None: |
| 233 | path.parent.mkdir(parents=True, exist_ok=True) |
| 234 | tmp = path.parent / f"{path.name}.tmp{os.getpid()}" |
| 235 | with open(tmp, "wb") as handle: |
| 236 | handle.write(data) |
| 237 | handle.flush() |
| 238 | os.fsync(handle.fileno()) |
| 239 | os.replace(tmp, path) |
| 240 | |
| 241 | |
| 242 | def _write_json(path: Path, payload: Any) -> None: |
| 243 | _write_bytes(path, json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")) |
| 244 | |
| 245 | |
| 246 | def _script_body( |
| 247 | raw: str, job_format: str, settings: Any, check: Callable[[], None] |
| 248 | ) -> str: |
| 249 | prompt_template = PROMPTS.get(job_format) |
| 250 | if prompt_template is None: |
| 251 | return _spoken_text(raw) |
| 252 | reply = llm.chat( |
| 253 | prompt_template.format(metin=raw), |
| 254 | settings, |
| 255 | system=SYSTEM_PROMPT, |
| 256 | check=check, |
| 257 | ) |
| 258 | body = _spoken_text(_clean_text(reply)) |
| 259 | if not body: |
| 260 | raise EngineError(SCRIPT_EMPTY, "LLM metni bos dondu") |
| 261 | return body |
| 262 | |
| 263 | |
| 264 | def _run(command: list[str]) -> subprocess.CompletedProcess: |
| 265 | try: |
| 266 | return subprocess.run(command, capture_output=True, text=True, check=False) |
| 267 | except OSError as exc: |
| 268 | raise EngineError(MUX_ERROR, f"komut calistirilamadi: {exc}") from exc |
| 269 | |
| 270 | |
| 271 | def _mux(parts: list[Path], target: Path, work: Path) -> None: |
| 272 | listing = work / "concat.txt" |
| 273 | listing.write_text( |
| 274 | "".join(f"file '{part.as_posix()}'\n" for part in parts), encoding="utf-8" |
| 275 | ) |
| 276 | tmp = target.parent / f"{target.name}.tmp{os.getpid()}" |
| 277 | target.parent.mkdir(parents=True, exist_ok=True) |
| 278 | completed = _run( |
| 279 | [ |
| 280 | "ffmpeg", |
| 281 | "-y", |
| 282 | "-hide_banner", |
| 283 | "-loglevel", |
| 284 | "error", |
| 285 | "-f", |
| 286 | "concat", |
| 287 | "-safe", |
| 288 | "0", |
| 289 | "-i", |
| 290 | str(listing), |
| 291 | "-c", |
| 292 | "copy", |
| 293 | "-f", |
| 294 | "mp3", |
| 295 | str(tmp), |
| 296 | ] |
| 297 | ) |
| 298 | if completed.returncode != 0: |
| 299 | try: |
| 300 | tmp.unlink() |
| 301 | except OSError: |
| 302 | pass |
| 303 | detail = (completed.stderr or "").strip().splitlines() |
| 304 | raise EngineError( |
| 305 | MUX_ERROR, |
| 306 | "ffmpeg birlestirme basarisiz: " |
| 307 | + (detail[-1] if detail else f"cikis kodu {completed.returncode}"), |
| 308 | ) |
| 309 | os.replace(tmp, target) |
| 310 | |
| 311 | |
| 312 | def duration_secs(path: Path) -> float: |
| 313 | try: |
| 314 | completed = _run( |
| 315 | [ |
| 316 | "ffprobe", |
| 317 | "-v", |
| 318 | "error", |
| 319 | "-show_entries", |
| 320 | "format=duration", |
| 321 | "-of", |
| 322 | "default=nw=1:nk=1", |
| 323 | str(path), |
| 324 | ] |
| 325 | ) |
| 326 | except EngineError: |
| 327 | return 0.0 |
| 328 | try: |
| 329 | return max(0.0, float(completed.stdout.strip())) |
| 330 | except ValueError: |
| 331 | return 0.0 |
| 332 | |
| 333 | |
| 334 | def _relative(path: Path, root: Path) -> str: |
| 335 | try: |
| 336 | return path.resolve().relative_to(root.resolve()).as_posix() |
| 337 | except (ValueError, OSError): |
| 338 | return path.name |
| 339 | |
| 340 | |
| 341 | def make_runner(settings: Any) -> Callable[[jobs.JobContext], None]: |
| 342 | output_root = Path(settings.output_root) |
| 343 | limit = int(settings.chapter_limit) |
| 344 | limit = None if limit <= 0 else limit |
| 345 | total = len(STAGES) |
| 346 | |
| 347 | def runner(ctx: jobs.JobContext) -> None: |
| 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 | ) |
| 360 | ctx.check() |
| 361 | ctx.progress(STAGES[0], 0.0) |
| 362 | try: |
| 363 | output_root.mkdir(parents=True, exist_ok=True) |
| 364 | work = Path( |
| 365 | tempfile.mkdtemp(prefix=WORK_PREFIX + ctx.job_id[-8:] + "-", dir=str(output_root)) |
| 366 | ) |
| 367 | except OSError as exc: |
| 368 | config.log("error", f"is {ctx.job_id} calisma dizini acilamadi: {exc}") |
| 369 | ctx.store.fail(ctx.job_id, OUTPUT_UNWRITABLE) |
| 370 | return |
| 371 | created: list[Path] = [] |
| 372 | succeeded = False |
| 373 | try: |
| 374 | ctx.progress(STAGES[1], 1.0 / total) |
| 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 | ) |
| 396 | config.log( |
| 397 | "info", |
| 398 | f"is {ctx.job_id} metin cikarildi: {len(ctx.sources)} kaynak, " |
| 399 | f"{pages} sayfa, {len(text)} karakter, ocr={ocr_pages}", |
| 400 | ) |
| 401 | |
| 402 | chapters = split_chapters(text, int(settings.chapter_chars), limit) |
| 403 | if not chapters: |
| 404 | raise EngineError(SCRIPT_EMPTY, "metinden bolum uretilemedi") |
| 405 | script_dir = output_root / base.stem / DIR_SCRIPT / ctx.format |
| 406 | script_paths: list[Path] = [] |
| 407 | bodies: list[str] = [] |
| 408 | ctx.progress(STAGES[2], 2.0 / total) |
| 409 | for index, chapter in enumerate(chapters): |
| 410 | ctx.check() |
| 411 | body = _script_body(chapter, ctx.format, settings, ctx.check) |
| 412 | bodies.append(body) |
| 413 | script_path = script_dir / f"{base.stem}-b{index + 1:02d}.script.json" |
| 414 | _write_json( |
| 415 | script_path, |
| 416 | { |
| 417 | "kaynak": base.name, |
| 418 | "format": ctx.format, |
| 419 | "bolum": index + 1, |
| 420 | "baslik": _chapter_title(body), |
| 421 | "metin": body, |
| 422 | }, |
| 423 | ) |
| 424 | created.append(script_path) |
| 425 | script_paths.append(script_path) |
| 426 | ctx.progress( |
| 427 | STAGES[2], (2 + (index + 1) / len(chapters)) / total |
| 428 | ) |
| 429 | |
| 430 | audio_dir = output_root / base.stem / DIR_AUDIO / ctx.format |
| 431 | parts: list[Path] = [] |
| 432 | ctx.progress(STAGES[3], 3.0 / total) |
| 433 | for index, body in enumerate(bodies): |
| 434 | ctx.check() |
| 435 | audio = tts.synthesize(body, settings) |
| 436 | part = work / f"{base.stem}-b{index + 1:02d}.mp3" |
| 437 | _write_bytes(part, audio) |
| 438 | parts.append(part) |
| 439 | ctx.progress( |
| 440 | STAGES[3], (3 + (index + 1) / len(bodies)) / total |
| 441 | ) |
| 442 | |
| 443 | ctx.progress(STAGES[4], 4.0 / total) |
| 444 | final = audio_dir / f"{base.stem}.mp3" |
| 445 | _mux(parts, final, work) |
| 446 | created.append(final) |
| 447 | |
| 448 | record = ctx.finish( |
| 449 | audio_id=_relative(final, output_root), |
| 450 | duration_secs=duration_secs(final), |
| 451 | script_id=_relative(script_paths[0], output_root), |
| 452 | audio_ids=[_relative(final, output_root)], |
| 453 | script_ids=[_relative(path, output_root) for path in script_paths], |
| 454 | transcript="\n\n".join(bodies), |
| 455 | ) |
| 456 | if record["state"] == jobs.STATE_DONE: |
| 457 | succeeded = True |
| 458 | config.log( |
| 459 | "info", |
| 460 | f"is {ctx.job_id} tamamlandi (api motoru): " |
| 461 | f"{len(script_paths)} bolum, " |
| 462 | f"{record['duration_secs']:.1f}s ses", |
| 463 | ) |
| 464 | else: |
| 465 | config.log("info", f"is {ctx.job_id} bitis aninda iptal edildi") |
| 466 | except EngineError as exc: |
| 467 | config.log("error", f"is {ctx.job_id} {exc.code}: {exc}") |
| 468 | ctx.store.fail(ctx.job_id, exc.code) |
| 469 | except (llm.LlmError, tts.TtsError) as exc: |
| 470 | config.log("error", f"is {ctx.job_id} {exc.code}: {exc}") |
| 471 | ctx.store.fail(ctx.job_id, exc.code) |
| 472 | finally: |
| 473 | shutil.rmtree(work, ignore_errors=True) |
| 474 | if not succeeded: |
| 475 | for path in created: |
| 476 | if not path.exists(): |
| 477 | continue |
| 478 | try: |
| 479 | path.unlink() |
| 480 | except OSError: |
| 481 | pass |
| 482 | |
| 483 | return runner |
| 484 | |
| 485 | |
| 486 | def probe(settings: Any) -> dict[str, Any]: |
| 487 | llm_ready, llm_reason = llm.ready(settings) |
| 488 | tts_ready, tts_reason = tts.ready(settings) |
| 489 | voices = "hazir" if tts_ready else "EKSIK" |
| 490 | formats = ", ".join(capabilities.allowed_formats(llm_ready)) |
| 491 | if tts_ready and llm_ready: |
| 492 | reason = f"{llm_reason}; tts {tts_reason}" |
| 493 | else: |
| 494 | parts = [] |
| 495 | if not llm_ready: |
| 496 | parts.append(f"llm: {llm_reason}") |
| 497 | if not tts_ready: |
| 498 | parts.append(f"tts: {tts_reason}") |
| 499 | reason = "; ".join(parts) |
| 500 | return { |
| 501 | "llm_ready": llm_ready, |
| 502 | "llm_reason": llm_reason, |
| 503 | "tts_ready": tts_ready, |
| 504 | "tts_reason": tts_reason, |
| 505 | "tts_voices": voices, |
| 506 | "formats": formats, |
| 507 | "reason": reason, |
| 508 | } |
| 509 | |
| 510 | |
| 511 | def build_runner(settings: Any) -> tuple[Callable[[jobs.JobContext], None], dict[str, Any]]: |
| 512 | return make_runner(settings), probe(settings) |