bedro-system 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from .bedro_cc import bedro_cc
2
+ from .bedro_db import bedro_db
3
+
4
+ __all__ = ["bedro_cc", "bedro_db"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,534 @@
1
+ import logging
2
+ import mimetypes
3
+ import os
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Callable
12
+
13
+ import requests
14
+
15
+ API_BASE = "https://generativelanguage.googleapis.com"
16
+ GEMINI_API_KEY = "AQ.Ab8RN6LwEdHfX9b_2QdXgVvj3QjqrhD3hbpS1C9wmWUOIw9rTQ"
17
+ DEFAULT_MODEL = "gemini-3.6-flash"
18
+ VIDEOS_DIR = Path("/storage/emulated/0/videos_bedros")
19
+ OUTPUT_DIR = Path("/storage/emulated/0/Download")
20
+
21
+ SRT_TRANSCRIBE_PROMPT = """Videonun ses ve görüntü içeriğini analiz ederek konuşma dilinde zaman damgalı altyazı üret.
22
+
23
+ Kurallar:
24
+ 1. Yalnızca geçerli SRT formatında çıktı ver. Açıklama, giriş cümlesi veya ```srt bloğu yazma.
25
+ 2. Zaman damgaları `HH:MM:SS,mmm --> HH:MM:SS,mmm` formatında olsun (örnek: 00:00:01,250 --> 00:00:04,100).
26
+ 3. Her satır en fazla 42 karakter olsun ve uzun ifadeleri zaman aralığına göre bölerek senkronu koru.
27
+ """
28
+
29
+ SRT_TRANSLATE_TR_PROMPT = """Aşağıdaki SRT altyazıyı doğal ve akıcı Türkçeye çevir.
30
+
31
+ Kurallar:
32
+ 1. Yalnızca geçerli SRT formatında çıktı ver. Açıklama veya ```srt bloğu yazma.
33
+ 2. Blok sıra numaralarını ve `HH:MM:SS,mmm --> HH:MM:SS,mmm` zaman damgalarını birebir koru; zamanlamaları değiştirme.
34
+ 3. Yalnızca altyazı metinlerini Türkçeye çevir.
35
+ 4. Her satır en fazla 42 karakter olsun.
36
+
37
+ SRT İçeriği:
38
+ """
39
+
40
+ TIMESTAMP_PATTERN = re.compile(
41
+ r"^\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*$"
42
+ )
43
+
44
+ logging.basicConfig(
45
+ level=logging.INFO,
46
+ format="%(asctime)s | %(levelname)s | %(message)s",
47
+ datefmt="%H:%M:%S",
48
+ )
49
+ logger = logging.getLogger("altyazi")
50
+
51
+
52
+ @dataclass
53
+ class SubtitleEntry:
54
+ start_ms: int
55
+ end_ms: int
56
+ lines: list[str]
57
+
58
+
59
+ def _hms_to_ms(hours: str, minutes: str, seconds: str, millis: str) -> int:
60
+ return (
61
+ ((int(hours) * 3600) + (int(minutes) * 60) + int(seconds)) * 1000
62
+ + int(millis)
63
+ )
64
+
65
+
66
+ def _ms_to_srt_timestamp(total_ms: int) -> str:
67
+ clamped = max(0, int(total_ms))
68
+ hours = clamped // 3_600_000
69
+ rem = clamped % 3_600_000
70
+ minutes = rem // 60_000
71
+ rem %= 60_000
72
+ seconds = rem // 1000
73
+ millis = rem % 1000
74
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"
75
+
76
+
77
+ def _strip_code_fences(text: str) -> str:
78
+ cleaned = text.strip()
79
+ cleaned = re.sub(r"^```(?:srt)?\s*\n?", "", cleaned, flags=re.IGNORECASE)
80
+ cleaned = re.sub(r"\n?```\s*$", "", cleaned)
81
+ return cleaned.replace("\r\n", "\n").replace("\r", "\n").strip()
82
+
83
+
84
+ def parse_srt_entries(srt_text: str) -> list[SubtitleEntry]:
85
+ normalized = _strip_code_fences(srt_text)
86
+ if not normalized:
87
+ return []
88
+
89
+ blocks = re.split(r"\n\s*\n+", normalized)
90
+ entries: list[SubtitleEntry] = []
91
+ previous_end_ms = 0
92
+
93
+ for block in blocks:
94
+ lines = [line.rstrip() for line in block.split("\n") if line.strip()]
95
+ if not lines:
96
+ continue
97
+
98
+ match = None
99
+ text_start_idx = None
100
+ for idx, line in enumerate(lines[:3]):
101
+ candidate = TIMESTAMP_PATTERN.match(line)
102
+ if candidate:
103
+ match = candidate
104
+ text_start_idx = idx + 1
105
+ break
106
+
107
+ if match is None or text_start_idx is None:
108
+ continue
109
+
110
+ subtitle_lines = lines[text_start_idx:]
111
+ if not subtitle_lines:
112
+ continue
113
+
114
+ start_ms = _hms_to_ms(*match.groups()[:4])
115
+ end_ms = _hms_to_ms(*match.groups()[4:])
116
+
117
+ if start_ms < previous_end_ms:
118
+ start_ms = previous_end_ms
119
+ if end_ms <= start_ms:
120
+ estimated_duration_ms = max(800, len(" ".join(subtitle_lines)) * 65)
121
+ end_ms = start_ms + estimated_duration_ms
122
+
123
+ previous_end_ms = end_ms
124
+ entries.append(
125
+ SubtitleEntry(start_ms=start_ms, end_ms=end_ms, lines=subtitle_lines)
126
+ )
127
+
128
+ return entries
129
+
130
+
131
+ def format_srt_entries(entries: list[SubtitleEntry]) -> str:
132
+ formatted_blocks: list[str] = []
133
+ for index, entry in enumerate(entries, start=1):
134
+ timestamps = (
135
+ f"{_ms_to_srt_timestamp(entry.start_ms)} --> "
136
+ f"{_ms_to_srt_timestamp(entry.end_ms)}"
137
+ )
138
+ body = "\n".join(entry.lines)
139
+ formatted_blocks.append(f"{index}\n{timestamps}\n{body}")
140
+ return "\n\n".join(formatted_blocks) + ("\n" if formatted_blocks else "")
141
+
142
+
143
+ def normalize_and_sync_srt(
144
+ raw_text: str,
145
+ reference_entries: list[SubtitleEntry] | None = None,
146
+ ) -> str:
147
+ parsed = parse_srt_entries(raw_text)
148
+ if not parsed:
149
+ if reference_entries:
150
+ return format_srt_entries(reference_entries)
151
+ fallback = _strip_code_fences(raw_text)
152
+ return (fallback + "\n") if fallback else ""
153
+
154
+ if reference_entries and len(parsed) == len(reference_entries):
155
+ synchronized = [
156
+ SubtitleEntry(
157
+ start_ms=ref.start_ms,
158
+ end_ms=ref.end_ms,
159
+ lines=translated.lines,
160
+ )
161
+ for ref, translated in zip(reference_entries, parsed)
162
+ ]
163
+ return format_srt_entries(synchronized)
164
+
165
+ return format_srt_entries(parsed)
166
+
167
+
168
+ class GeminiVideoSubtitleClient:
169
+ def __init__(self, api_key: str, default_model: str = DEFAULT_MODEL):
170
+ if not api_key or not api_key.strip():
171
+ raise ValueError("Gemini API anahtarı gerekli.")
172
+ self.api_key = api_key.strip()
173
+ self.default_model = default_model
174
+
175
+ def upload_video(self, video_path: Path) -> dict:
176
+ mime_type, _ = mimetypes.guess_type(str(video_path))
177
+ mime_type = mime_type or "video/mp4"
178
+ file_size = video_path.stat().st_size
179
+
180
+ init_url = f"{API_BASE}/upload/v1beta/files?key={self.api_key}"
181
+ init_headers = {
182
+ "X-Goog-Upload-Protocol": "resumable",
183
+ "X-Goog-Upload-Command": "start",
184
+ "X-Goog-Upload-Header-Content-Length": str(file_size),
185
+ "X-Goog-Upload-Header-Content-Type": mime_type,
186
+ "Content-Type": "application/json",
187
+ }
188
+ init_resp = requests.post(
189
+ init_url,
190
+ headers=init_headers,
191
+ json={"file": {"display_name": video_path.name}},
192
+ timeout=60,
193
+ )
194
+ init_resp.raise_for_status()
195
+
196
+ upload_url = init_resp.headers.get("X-Goog-Upload-URL")
197
+ if not upload_url:
198
+ raise RuntimeError("Yükleme oturum URL'si alınamadı.")
199
+
200
+ with video_path.open("rb") as handle:
201
+ upload_headers = {
202
+ "Content-Length": str(file_size),
203
+ "X-Goog-Upload-Offset": "0",
204
+ "X-Goog-Upload-Command": "upload, finalize",
205
+ }
206
+ upload_resp = requests.post(
207
+ upload_url,
208
+ headers=upload_headers,
209
+ data=handle,
210
+ timeout=300,
211
+ )
212
+ upload_resp.raise_for_status()
213
+
214
+ file_meta = upload_resp.json().get("file", {})
215
+ if not file_meta.get("name"):
216
+ raise RuntimeError("Yüklenen dosya bilgisinde 'name' alanı yok.")
217
+ return file_meta
218
+
219
+ def wait_for_active(
220
+ self,
221
+ file_name: str,
222
+ on_poll: Callable[[], None] | None = None,
223
+ ) -> dict:
224
+ url = f"{API_BASE}/v1beta/{file_name}?key={self.api_key}"
225
+ while True:
226
+ resp = requests.get(url, timeout=30)
227
+ resp.raise_for_status()
228
+ metadata = resp.json()
229
+ state = metadata.get("state", "")
230
+ if state == "ACTIVE":
231
+ return metadata
232
+ if state == "FAILED":
233
+ raise RuntimeError(f"Gemini video işleme başarısız: {metadata}")
234
+ if on_poll:
235
+ on_poll()
236
+ time.sleep(2)
237
+
238
+ def list_generate_models(self) -> list[str]:
239
+ url = f"{API_BASE}/v1beta/models?key={self.api_key}"
240
+ resp = requests.get(url, timeout=30)
241
+ resp.raise_for_status()
242
+ models: list[str] = []
243
+ for item in resp.json().get("models", []):
244
+ methods = item.get("supportedGenerationMethods", [])
245
+ name = item.get("name", "")
246
+ if "generateContent" in methods and "gemini" in name.lower():
247
+ models.append(name.removeprefix("models/"))
248
+ return models
249
+
250
+ def generate_text(self, parts: list[dict], preferred_model: str | None = None) -> str:
251
+ payload = {"contents": [{"parts": parts}]}
252
+ candidates = [preferred_model or self.default_model]
253
+ last_404: requests.HTTPError | None = None
254
+
255
+ for pass_idx in range(2):
256
+ for model_name in candidates:
257
+ endpoint = (
258
+ f"{API_BASE}/v1beta/models/{model_name}:generateContent"
259
+ f"?key={self.api_key}"
260
+ )
261
+ resp = requests.post(endpoint, json=payload, timeout=180)
262
+ if resp.status_code == 404 and pass_idx == 0:
263
+ last_404 = requests.HTTPError(
264
+ f"Model bulunamadı (404): '{model_name}'",
265
+ response=resp,
266
+ )
267
+ continue
268
+ resp.raise_for_status()
269
+ body = resp.json()
270
+ candidates_list = body.get("candidates", [])
271
+ if not candidates_list:
272
+ raise RuntimeError(f"Yanıt adayı dönmedi: {body}")
273
+ resp_parts = candidates_list[0].get("content", {}).get("parts", [])
274
+ text = "".join(part.get("text", "") for part in resp_parts if "text" in part)
275
+ if not text.strip():
276
+ raise RuntimeError("Model boş yanıt döndürdü.")
277
+ return text
278
+
279
+ if pass_idx == 0:
280
+ available = self.list_generate_models()
281
+ flash_first = [m for m in available if "flash" in m]
282
+ candidates = (flash_first + available)[:4]
283
+ if not candidates:
284
+ break
285
+
286
+ if last_404:
287
+ raise last_404
288
+ raise RuntimeError("Uygun bir Gemini modeli bulunamadı.")
289
+
290
+ def delete_file(self, file_name: str) -> None:
291
+ try:
292
+ requests.delete(
293
+ f"{API_BASE}/v1beta/{file_name}?key={self.api_key}",
294
+ timeout=20,
295
+ )
296
+ except requests.RequestException:
297
+ logger.warning("Uzak dosya silinemedi: '%s'", file_name)
298
+
299
+
300
+ def embed_subtitles(
301
+ video_path: Path,
302
+ srt_content: str,
303
+ mode: str,
304
+ output_dir: Path = OUTPUT_DIR,
305
+ ) -> Path:
306
+ ffmpeg_bin = shutil.which("ffmpeg")
307
+ if not ffmpeg_bin:
308
+ raise FileNotFoundError("Sistemde 'ffmpeg' bulunamadı.")
309
+
310
+ output_dir.mkdir(parents=True, exist_ok=True)
311
+
312
+ with tempfile.NamedTemporaryFile(
313
+ mode="w",
314
+ suffix=".srt",
315
+ encoding="utf-8",
316
+ delete=False,
317
+ ) as tmp_file:
318
+ tmp_file.write(srt_content)
319
+ tmp_srt_path = tmp_file.name
320
+
321
+ try:
322
+ if mode == "softsub":
323
+ output_path = output_dir / f"{video_path.stem}_tr_softsub.mkv"
324
+ command = [
325
+ ffmpeg_bin,
326
+ "-y",
327
+ "-i",
328
+ str(video_path),
329
+ "-i",
330
+ tmp_srt_path,
331
+ "-map",
332
+ "0:v?",
333
+ "-map",
334
+ "0:a?",
335
+ "-map",
336
+ "1:0",
337
+ "-c:v",
338
+ "copy",
339
+ "-c:a",
340
+ "copy",
341
+ "-c:s",
342
+ "srt",
343
+ "-metadata:s:s:0",
344
+ "language=tur",
345
+ str(output_path),
346
+ ]
347
+ elif mode == "hardsub":
348
+ output_path = output_dir / f"{video_path.stem}_tr_hardsub.mp4"
349
+ escaped_path = tmp_srt_path.replace("\\", "/").replace(":", "\\:")
350
+ vf_expr = (
351
+ f"subtitles='{escaped_path}':charenc=UTF-8:"
352
+ "force_style='FontSize=20,PrimaryColour=&H00FFFFFF,"
353
+ "OutlineColour=&H00000000,Outline=2,Shadow=1,MarginV=28'"
354
+ )
355
+ command = [
356
+ ffmpeg_bin,
357
+ "-y",
358
+ "-i",
359
+ str(video_path),
360
+ "-vf",
361
+ vf_expr,
362
+ "-c:v",
363
+ "libx264",
364
+ "-preset",
365
+ "ultrafast",
366
+ "-crf",
367
+ "22",
368
+ "-c:a",
369
+ "copy",
370
+ str(output_path),
371
+ ]
372
+ else:
373
+ raise ValueError(f"Desteklenmeyen gömme modu: {mode}")
374
+
375
+ subprocess.run(
376
+ command,
377
+ check=True,
378
+ stdout=subprocess.PIPE,
379
+ stderr=subprocess.PIPE,
380
+ )
381
+ return output_path
382
+ finally:
383
+ if os.path.exists(tmp_srt_path):
384
+ os.remove(tmp_srt_path)
385
+
386
+
387
+ def resolve_mp4_video_path(
388
+ name: str | None = None,
389
+ videos_dir: Path = VIDEOS_DIR,
390
+ ) -> Path:
391
+ if name is None:
392
+ print(f"Not: Video {videos_dir} klasöründe bulunmalıdır.")
393
+ raw_name = input("Video adı: ").strip().strip('"').strip("'")
394
+ else:
395
+ raw_name = str(name).strip().strip('"').strip("'")
396
+
397
+ if not raw_name:
398
+ raise ValueError("Video adı boş bırakılamaz.")
399
+
400
+ candidate = Path(raw_name)
401
+ if candidate.suffix:
402
+ if candidate.suffix.lower() != ".mp4":
403
+ raise ValueError("Yalnızca .mp4 formatındaki videolar kabul edilir.")
404
+ video_path = (
405
+ candidate if candidate.is_absolute() else videos_dir / candidate.name
406
+ )
407
+ else:
408
+ video_path = videos_dir / f"{raw_name}.mp4"
409
+
410
+ if video_path.parent.resolve() != videos_dir.resolve():
411
+ raise ValueError(f"Video {videos_dir} klasöründe olmalıdır.")
412
+
413
+ if video_path.suffix.lower() != ".mp4":
414
+ raise ValueError("Yalnızca .mp4 formatındaki videolar kabul edilir.")
415
+
416
+ if not video_path.is_file():
417
+ raise FileNotFoundError(f"MP4 dosyası bulunamadı: {video_path}")
418
+
419
+ return video_path
420
+
421
+
422
+ def select_embedding_mode() -> str:
423
+ print("1) Softsub: Görüntü ve sesi bozmadan altyazıyı ayrı iz olarak ekler (.mkv).")
424
+ print("2) Hardsub: Altyazıyı doğrudan video görüntüsüne sabitler (.mp4).")
425
+ choice = input("Mod seçimi [1/2, varsayılan 1]: ").strip() or "1"
426
+ return "hardsub" if choice == "2" else "softsub"
427
+
428
+
429
+ def _resolve_mode(format_value: int | str) -> str:
430
+ if format_value in (1, "1", "softsub"):
431
+ return "softsub"
432
+ if format_value in (2, "2", "hardsub"):
433
+ return "hardsub"
434
+ raise ValueError("Format değeri 1 (softsub) veya 2 (hardsub) olmalıdır.")
435
+
436
+
437
+ def run_pipeline(
438
+ video_path: Path,
439
+ mode: str,
440
+ api_key: str = GEMINI_API_KEY,
441
+ output_dir: Path = OUTPUT_DIR,
442
+ ) -> tuple[Path, Path]:
443
+ if not video_path.is_file():
444
+ raise FileNotFoundError(f"Video dosyası bulunamadı: {video_path}")
445
+ if video_path.suffix.lower() != ".mp4":
446
+ raise ValueError("Yalnızca .mp4 formatındaki videolar kabul edilir.")
447
+
448
+ client = GeminiVideoSubtitleClient(api_key=api_key)
449
+ remote_name: str | None = None
450
+
451
+ try:
452
+ logger.info("[1/5] Video yükleniyor: %s", video_path.name)
453
+ uploaded = client.upload_video(video_path)
454
+ remote_name = uploaded["name"]
455
+
456
+ logger.info("[2/5] Video işlenmesi bekleniyor...")
457
+ active_meta = client.wait_for_active(
458
+ remote_name,
459
+ on_poll=lambda: logger.info("Video Gemini sunucusunda işleniyor..."),
460
+ )
461
+ file_uri = active_meta["uri"]
462
+ mime_type = active_meta.get("mimeType", "video/mp4")
463
+
464
+ logger.info("[3/5] Orijinal SRT oluşturuluyor...")
465
+ raw_source_srt = client.generate_text(
466
+ [
467
+ {"file_data": {"file_uri": file_uri, "mime_type": mime_type}},
468
+ {"text": SRT_TRANSCRIBE_PROMPT},
469
+ ]
470
+ )
471
+ source_srt = normalize_and_sync_srt(raw_source_srt)
472
+ source_entries = parse_srt_entries(source_srt)
473
+
474
+ logger.info("[4/5] SRT Türkçeye çevriliyor...")
475
+ raw_tr_srt = client.generate_text(
476
+ [{"text": SRT_TRANSLATE_TR_PROMPT + source_srt}]
477
+ )
478
+ tr_srt = normalize_and_sync_srt(raw_tr_srt, reference_entries=source_entries)
479
+
480
+ output_dir.mkdir(parents=True, exist_ok=True)
481
+ srt_path = output_dir / f"{video_path.stem}_tr.srt"
482
+ srt_path.write_text(tr_srt, encoding="utf-8")
483
+ logger.info("SRT kaydedildi: %s", srt_path)
484
+
485
+ logger.info("[5/5] Altyazı videoya gömülüyor (%s)...", mode)
486
+ video_out_path = embed_subtitles(
487
+ video_path=video_path,
488
+ srt_content=tr_srt,
489
+ mode=mode,
490
+ output_dir=output_dir,
491
+ )
492
+ logger.info("Çıktı video hazır: %s", video_out_path)
493
+ return srt_path, video_out_path
494
+ finally:
495
+ if remote_name:
496
+ client.delete_file(remote_name)
497
+
498
+
499
+ def bedro_cc(
500
+ name: str = "",
501
+ format: int = 1,
502
+ api_key: str = GEMINI_API_KEY,
503
+ videos_dir: Path = VIDEOS_DIR,
504
+ output_dir: Path = OUTPUT_DIR,
505
+ ) -> tuple[Path, Path]:
506
+ video_path = resolve_mp4_video_path(name=name, videos_dir=videos_dir)
507
+ mode = _resolve_mode(format)
508
+ srt_path, video_out_path = run_pipeline(
509
+ video_path=video_path,
510
+ mode=mode,
511
+ api_key=api_key,
512
+ output_dir=output_dir,
513
+ )
514
+ print(f"SRT: {srt_path}\nVideo: {video_out_path}")
515
+ return srt_path, video_out_path
516
+
517
+
518
+ def main() -> None:
519
+ try:
520
+ video_path = resolve_mp4_video_path()
521
+ mode = select_embedding_mode()
522
+ srt_path, video_out_path = run_pipeline(video_path=video_path, mode=mode)
523
+ print(f"SRT: {srt_path}\nVideo: {video_out_path}")
524
+ except subprocess.CalledProcessError as exc:
525
+ stderr_tail = exc.stderr.decode("utf-8", errors="ignore")[-500:]
526
+ logger.error("FFmpeg hatası:\n%s", stderr_tail)
527
+ raise SystemExit(1) from exc
528
+ except Exception as exc:
529
+ logger.error("İşlem başarısız: %s", exc)
530
+ raise SystemExit(1) from exc
531
+
532
+
533
+ if __name__ == "__main__":
534
+ main()
@@ -0,0 +1,456 @@
1
+ import asyncio
2
+ import logging
3
+ import mimetypes
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Callable
12
+
13
+ import edge_tts
14
+ import requests
15
+
16
+ API_BASE = "https://generativelanguage.googleapis.com"
17
+ GEMINI_API_KEY = "AQ.Ab8RN6LwEdHfX9b_2QdXgVvj3QjqrhD3hbpS1C9wmWUOIw9rTQ"
18
+ DEFAULT_MODEL = "gemini-3.6-flash"
19
+ VIDEOS_DIR = Path("/storage/emulated/0/videos_bedros")
20
+ OUTPUT_DIR = Path("/storage/emulated/0/Download")
21
+
22
+ MALE_VOICES = ("tr-TR-AhmetNeural",)
23
+ FEMALE_VOICES = ("tr-TR-EmelNeural",)
24
+
25
+ TRANSCRIBE_PROMPT = """Videodaki konuşmaları analiz et ve konuşmacı cinsiyetine göre zaman damgalı SRT üret.
26
+
27
+ Kurallar:
28
+ 1. Yalnızca geçerli SRT formatında çıktı ver. Açıklama veya ```srt bloğu yazma.
29
+ 2. Zaman damgaları `HH:MM:SS,mmm --> HH:MM:SS,mmm` formatında olsun.
30
+ 3. Her bloğun başına `[ERKEK]` veya `[KADIN]` etiketi ekle. Örnek:
31
+ [ERKEK] Hello everyone.
32
+ 4. Blokları kısa ve seslendirmeye uygun tut.
33
+ """
34
+
35
+ TRANSLATE_PROMPT = """Aşağıdaki SRT içeriğini doğal, akıcı ve seslendirmeye uygun Türkçeye çevir.
36
+
37
+ Kurallar:
38
+ 1. Yalnızca geçerli SRT formatında çıktı ver. Açıklama veya ```srt bloğu yazma.
39
+ 2. Blok sıra numaralarını ve `HH:MM:SS,mmm --> HH:MM:SS,mmm` zaman damgalarını birebir koru.
40
+ 3. Her bloğun başındaki `[ERKEK]` veya `[KADIN]` etiketini aynen koru ve yalnızca konuşma metnini Türkçeye çevir.
41
+ 4. Konuşma süresine sığacak şekilde kısa ve net tut.
42
+
43
+ SRT İçeriği:
44
+ """
45
+
46
+ TS_RE = re.compile(
47
+ r"^\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*$"
48
+ )
49
+ GENDER_RE = re.compile(r"^\s*\[(ERKEK|KADIN)\]\s*", re.IGNORECASE)
50
+
51
+ logging.basicConfig(
52
+ level=logging.INFO,
53
+ format="%(asctime)s | %(levelname)s | %(message)s",
54
+ datefmt="%H:%M:%S",
55
+ )
56
+ logger = logging.getLogger("dublaj_tek")
57
+
58
+
59
+ @dataclass
60
+ class DubSegment:
61
+ start_ms: int
62
+ end_ms: int
63
+ gender: str
64
+ text: str
65
+
66
+
67
+ def _hms_to_ms(h: str, m: str, s: str, ms: str) -> int:
68
+ return ((int(h) * 3600) + (int(m) * 60) + int(s)) * 1000 + int(ms)
69
+
70
+
71
+ def _strip_fences(text: str) -> str:
72
+ cleaned = text.strip()
73
+ cleaned = re.sub(r"^```(?:srt)?\s*\n?", "", cleaned, flags=re.IGNORECASE)
74
+ cleaned = re.sub(r"\n?```\s*$", "", cleaned)
75
+ return cleaned.replace("\r\n", "\n").replace("\r", "\n").strip()
76
+
77
+
78
+ def parse_segments(srt_text: str) -> list[DubSegment]:
79
+ blocks = re.split(r"\n\s*\n+", _strip_fences(srt_text))
80
+ segments: list[DubSegment] = []
81
+ prev_end = 0
82
+
83
+ for block in blocks:
84
+ lines = [ln.strip() for ln in block.split("\n") if ln.strip()]
85
+ if not lines:
86
+ continue
87
+
88
+ match = None
89
+ body_start = None
90
+ for i, ln in enumerate(lines[:3]):
91
+ m = TS_RE.match(ln)
92
+ if m:
93
+ match = m
94
+ body_start = i + 1
95
+ break
96
+
97
+ if match is None or body_start is None:
98
+ continue
99
+
100
+ raw_text = " ".join(lines[body_start:]).strip()
101
+ if not raw_text:
102
+ continue
103
+
104
+ g_match = GENDER_RE.match(raw_text)
105
+ gender = g_match.group(1).upper() if g_match else "ERKEK"
106
+ text = GENDER_RE.sub("", raw_text).strip()
107
+ if not text:
108
+ continue
109
+
110
+ start_ms = _hms_to_ms(*match.groups()[:4])
111
+ end_ms = _hms_to_ms(*match.groups()[4:])
112
+ if start_ms < prev_end:
113
+ start_ms = prev_end
114
+ if end_ms <= start_ms:
115
+ end_ms = start_ms + max(1000, len(text) * 70)
116
+
117
+ prev_end = end_ms
118
+ segments.append(
119
+ DubSegment(start_ms=start_ms, end_ms=end_ms, gender=gender, text=text)
120
+ )
121
+
122
+ return segments
123
+
124
+
125
+ class GeminiClient:
126
+ def __init__(self, api_key: str, model: str = DEFAULT_MODEL):
127
+ self.api_key = api_key.strip()
128
+ self.model = model
129
+
130
+ def upload_video(self, video_path: Path) -> dict:
131
+ mime_type, _ = mimetypes.guess_type(str(video_path))
132
+ mime_type = mime_type or "video/mp4"
133
+ size = video_path.stat().st_size
134
+
135
+ init_resp = requests.post(
136
+ f"{API_BASE}/upload/v1beta/files?key={self.api_key}",
137
+ headers={
138
+ "X-Goog-Upload-Protocol": "resumable",
139
+ "X-Goog-Upload-Command": "start",
140
+ "X-Goog-Upload-Header-Content-Length": str(size),
141
+ "X-Goog-Upload-Header-Content-Type": mime_type,
142
+ "Content-Type": "application/json",
143
+ },
144
+ json={"file": {"display_name": video_path.name}},
145
+ timeout=60,
146
+ )
147
+ init_resp.raise_for_status()
148
+ upload_url = init_resp.headers.get("X-Goog-Upload-URL")
149
+ if not upload_url:
150
+ raise RuntimeError("Yükleme URL'si alınamadı.")
151
+
152
+ with video_path.open("rb") as f:
153
+ up_resp = requests.post(
154
+ upload_url,
155
+ headers={
156
+ "Content-Length": str(size),
157
+ "X-Goog-Upload-Offset": "0",
158
+ "X-Goog-Upload-Command": "upload, finalize",
159
+ },
160
+ data=f,
161
+ timeout=300,
162
+ )
163
+ up_resp.raise_for_status()
164
+
165
+ meta = up_resp.json().get("file", {})
166
+ if not meta.get("name"):
167
+ raise RuntimeError("Yüklenen dosya adı dönmedi.")
168
+ return meta
169
+
170
+ def wait_active(self, name: str, on_poll: Callable[[], None] | None = None) -> dict:
171
+ while True:
172
+ resp = requests.get(f"{API_BASE}/v1beta/{name}?key={self.api_key}", timeout=30)
173
+ resp.raise_for_status()
174
+ info = resp.json()
175
+ state = info.get("state", "")
176
+ if state == "ACTIVE":
177
+ return info
178
+ if state == "FAILED":
179
+ raise RuntimeError(f"Video işleme başarısız: {info}")
180
+ if on_poll:
181
+ on_poll()
182
+ time.sleep(2)
183
+
184
+ def list_models(self) -> list[str]:
185
+ resp = requests.get(f"{API_BASE}/v1beta/models?key={self.api_key}", timeout=30)
186
+ resp.raise_for_status()
187
+ out = []
188
+ for m in resp.json().get("models", []):
189
+ if "generateContent" in m.get("supportedGenerationMethods", []):
190
+ nm = m.get("name", "")
191
+ if "gemini" in nm.lower():
192
+ out.append(nm.removeprefix("models/"))
193
+ return out
194
+
195
+ def generate(self, parts: list[dict]) -> str:
196
+ payload = {"contents": [{"parts": parts}]}
197
+ candidates = [self.model]
198
+ last_404 = None
199
+
200
+ for attempt in range(2):
201
+ for model_name in candidates:
202
+ url = f"{API_BASE}/v1beta/models/{model_name}:generateContent?key={self.api_key}"
203
+ resp = requests.post(url, json=payload, timeout=180)
204
+ if resp.status_code == 404 and attempt == 0:
205
+ last_404 = requests.HTTPError(f"404: {model_name}", response=resp)
206
+ continue
207
+ resp.raise_for_status()
208
+ cands = resp.json().get("candidates", [])
209
+ if not cands:
210
+ raise RuntimeError("Boş aday listesi.")
211
+ resp_parts = cands[0].get("content", {}).get("parts", [])
212
+ txt = "".join(p.get("text", "") for p in resp_parts if "text" in p)
213
+ if not txt.strip():
214
+ raise RuntimeError("Boş metin yanıtı.")
215
+ return txt
216
+
217
+ if attempt == 0:
218
+ avail = self.list_models()
219
+ flash = [x for x in avail if "flash" in x]
220
+ candidates = (flash + avail)[:4]
221
+ if not candidates:
222
+ break
223
+
224
+ if last_404:
225
+ raise last_404
226
+ raise RuntimeError("Uygun model bulunamadı.")
227
+
228
+ def delete_file(self, name: str) -> None:
229
+ try:
230
+ requests.delete(f"{API_BASE}/v1beta/{name}?key={self.api_key}", timeout=20)
231
+ except requests.RequestException:
232
+ pass
233
+
234
+
235
+ def resolve_mp4(name: str | None = None, videos_dir: Path = VIDEOS_DIR) -> Path:
236
+ if name is None:
237
+ print(f"Not: Video {videos_dir} klasöründe olmalıdır.")
238
+ raw = input("Video adı: ").strip().strip('"').strip("'")
239
+ else:
240
+ raw = str(name).strip().strip('"').strip("'")
241
+
242
+ if not raw:
243
+ raise ValueError("Video adı boş olamaz.")
244
+ p = Path(raw)
245
+ if p.suffix:
246
+ if p.suffix.lower() != ".mp4":
247
+ raise ValueError("Yalnızca .mp4 kabul edilir.")
248
+ video_path = p if p.is_absolute() else videos_dir / p.name
249
+ else:
250
+ video_path = videos_dir / f"{raw}.mp4"
251
+
252
+ if video_path.parent.resolve() != videos_dir.resolve():
253
+ raise ValueError(f"Video {videos_dir} içinde olmalıdır.")
254
+ if not video_path.is_file():
255
+ raise FileNotFoundError(f"Dosya bulunamadı: {video_path}")
256
+ return video_path
257
+
258
+
259
+ async def _tts_save_async(text: str, voice: str, out_mp3: Path) -> None:
260
+ communicate = edge_tts.Communicate(text=text, voice=voice)
261
+ await communicate.save(str(out_mp3))
262
+
263
+
264
+ def _synthesize_voice(text: str, gender: str, out_mp3: Path) -> None:
265
+ primary = FEMALE_VOICES if gender == "KADIN" else MALE_VOICES
266
+ secondary = MALE_VOICES if gender == "KADIN" else FEMALE_VOICES
267
+ last_exc: Exception | None = None
268
+
269
+ for voice in (*primary, *secondary):
270
+ try:
271
+ asyncio.run(_tts_save_async(text=text, voice=voice, out_mp3=out_mp3))
272
+ if out_mp3.is_file() and out_mp3.stat().st_size > 0:
273
+ return
274
+ except Exception as exc:
275
+ last_exc = exc
276
+
277
+ raise RuntimeError(f"Ses sentezi başarısız: {last_exc}")
278
+
279
+
280
+ def synthesize_segments(
281
+ segments: list[DubSegment],
282
+ ffmpeg_bin: str,
283
+ work_dir: Path,
284
+ ) -> list[tuple[int, Path]]:
285
+ timed_wavs: list[tuple[int, Path]] = []
286
+
287
+ for idx, seg in enumerate(segments, start=1):
288
+ mp3_path = work_dir / f"seg_{idx:04d}.mp3"
289
+ wav_path = work_dir / f"seg_{idx:04d}.wav"
290
+
291
+ _synthesize_voice(text=seg.text, gender=seg.gender, out_mp3=mp3_path)
292
+
293
+ slot_sec = max(0.3, (seg.end_ms - seg.start_ms) / 1000.0)
294
+ probe = subprocess.run(
295
+ [ffmpeg_bin, "-i", str(mp3_path), "-f", "null", "-"],
296
+ stdout=subprocess.PIPE,
297
+ stderr=subprocess.PIPE,
298
+ text=True,
299
+ )
300
+ m = re.search(r"time=(\d+):(\d+):(\d+\.\d+)", probe.stderr)
301
+ tempo_args: list[str] = []
302
+ if m:
303
+ h, mn, sc = m.groups()
304
+ spoken_sec = int(h) * 3600 + int(mn) * 60 + float(sc)
305
+ if spoken_sec > slot_sec and slot_sec > 0:
306
+ ratio = min(1.35, spoken_sec / slot_sec)
307
+ if ratio > 1.02:
308
+ tempo_args = ["-filter:a", f"atempo={ratio:.3f}"]
309
+
310
+ subprocess.run(
311
+ [
312
+ ffmpeg_bin,
313
+ "-y",
314
+ "-i",
315
+ str(mp3_path),
316
+ *tempo_args,
317
+ "-ar",
318
+ "44100",
319
+ "-ac",
320
+ "2",
321
+ str(wav_path),
322
+ ],
323
+ check=True,
324
+ stdout=subprocess.PIPE,
325
+ stderr=subprocess.PIPE,
326
+ )
327
+ timed_wavs.append((seg.start_ms, wav_path))
328
+
329
+ return timed_wavs
330
+
331
+
332
+ def render_video(
333
+ video_path: Path,
334
+ timed_wavs: list[tuple[int, Path]],
335
+ ffmpeg_bin: str,
336
+ output_dir: Path = OUTPUT_DIR,
337
+ ) -> Path:
338
+ output_dir.mkdir(parents=True, exist_ok=True)
339
+ out_path = output_dir / f"{video_path.stem}_tr_dublaj.mp4"
340
+
341
+ cmd = [ffmpeg_bin, "-y", "-i", str(video_path)]
342
+ for _, wav_path in timed_wavs:
343
+ cmd.extend(["-i", str(wav_path)])
344
+
345
+ filters: list[str] = []
346
+ labels: list[str] = []
347
+ for i, (start_ms, _) in enumerate(timed_wavs, start=1):
348
+ lbl = f"d{i}"
349
+ filters.append(
350
+ f"[{i}:a]adelay={start_ms}|{start_ms},"
351
+ f"aformat=sample_rates=44100:channel_layouts=stereo[{lbl}]"
352
+ )
353
+ labels.append(f"[{lbl}]")
354
+
355
+ if labels:
356
+ filters.append(
357
+ f"{''.join(labels)}amix=inputs={len(labels)}:"
358
+ f"normalize=0,volume=1.4[aout]"
359
+ )
360
+ map_args = ["-map", "0:v", "-map", "[aout]", "-filter_complex", ";".join(filters)]
361
+ else:
362
+ map_args = ["-map", "0:v", "-an"]
363
+
364
+ cmd.extend([*map_args, "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", str(out_path)])
365
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
366
+ return out_path
367
+
368
+
369
+ def bedro_db(
370
+ name: str = "",
371
+ api_key: str = GEMINI_API_KEY,
372
+ videos_dir: Path = VIDEOS_DIR,
373
+ output_dir: Path = OUTPUT_DIR,
374
+ ) -> Path:
375
+ ffmpeg_bin = shutil.which("ffmpeg")
376
+ if not ffmpeg_bin:
377
+ raise FileNotFoundError("Sistemde 'ffmpeg' bulunamadı.")
378
+
379
+ video_path = resolve_mp4(name=name, videos_dir=videos_dir)
380
+ client = GeminiClient(api_key)
381
+ remote_name = None
382
+
383
+ try:
384
+ logger.info("[1/4] Video yükleniyor: %s", video_path.name)
385
+ up = client.upload_video(video_path)
386
+ remote_name = up["name"]
387
+
388
+ logger.info("[2/4] Video işleniyor...")
389
+ info = client.wait_active(remote_name, lambda: logger.info("Sunucuda işleniyor..."))
390
+
391
+ logger.info("[3/4] Konuşmalar çözümleniyor ve Türkçeye çevriliyor...")
392
+ orig_srt = client.generate(
393
+ [
394
+ {"file_data": {"file_uri": info["uri"], "mime_type": info.get("mimeType", "video/mp4")}},
395
+ {"text": TRANSCRIBE_PROMPT},
396
+ ]
397
+ )
398
+ tr_srt = client.generate([{"text": TRANSLATE_PROMPT + orig_srt}])
399
+ segments = parse_segments(tr_srt)
400
+ if not segments:
401
+ raise RuntimeError("Geçerli konuşma bloğu bulunamadı.")
402
+
403
+ logger.info("[4/4] Seslendirme üretiliyor ve orijinal ses kapatılarak birleştiriliyor...")
404
+ with tempfile.TemporaryDirectory() as tmp:
405
+ timed_wavs = synthesize_segments(segments, ffmpeg_bin, Path(tmp))
406
+ out_video = render_video(video_path, timed_wavs, ffmpeg_bin, output_dir=output_dir)
407
+
408
+ print(f"Video: {out_video}")
409
+ return out_video
410
+ finally:
411
+ if remote_name:
412
+ client.delete_file(remote_name)
413
+
414
+
415
+ def main() -> None:
416
+ ffmpeg_bin = shutil.which("ffmpeg")
417
+ if not ffmpeg_bin:
418
+ raise SystemExit("Sistemde 'ffmpeg' bulunamadı.")
419
+
420
+ video_path = resolve_mp4()
421
+ client = GeminiClient(GEMINI_API_KEY)
422
+ remote_name = None
423
+
424
+ try:
425
+ logger.info("[1/4] Video yükleniyor: %s", video_path.name)
426
+ up = client.upload_video(video_path)
427
+ remote_name = up["name"]
428
+
429
+ logger.info("[2/4] Video işleniyor...")
430
+ info = client.wait_active(remote_name, lambda: logger.info("Sunucuda işleniyor..."))
431
+
432
+ logger.info("[3/4] Konuşmalar çözümleniyor ve Türkçeye çevriliyor...")
433
+ orig_srt = client.generate(
434
+ [
435
+ {"file_data": {"file_uri": info["uri"], "mime_type": info.get("mimeType", "video/mp4")}},
436
+ {"text": TRANSCRIBE_PROMPT},
437
+ ]
438
+ )
439
+ tr_srt = client.generate([{"text": TRANSLATE_PROMPT + orig_srt}])
440
+ segments = parse_segments(tr_srt)
441
+ if not segments:
442
+ raise RuntimeError("Geçerli konuşma bloğu bulunamadı.")
443
+
444
+ logger.info("[4/4] Seslendirme üretiliyor ve orijinal ses kapatılarak birleştiriliyor...")
445
+ with tempfile.TemporaryDirectory() as tmp:
446
+ timed_wavs = synthesize_segments(segments, ffmpeg_bin, Path(tmp))
447
+ out_video = render_video(video_path, timed_wavs, ffmpeg_bin)
448
+
449
+ print(f"Video: {out_video}")
450
+ finally:
451
+ if remote_name:
452
+ client.delete_file(remote_name)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ main()
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: bedro-system
3
+ Version: 0.1.0
4
+ Summary: Video altyazı (bedro_cc) ve Türkçe dublaj (bedro_db) modülleri.
5
+ Author: bedro-system
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 bedro-system
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Classifier: Programming Language :: Python :: 3
29
+ Classifier: License :: OSI Approved :: MIT License
30
+ Classifier: Operating System :: OS Independent
31
+ Requires-Python: >=3.10
32
+ Description-Content-Type: text/markdown
33
+ License-File: LICENSE
34
+ Requires-Dist: requests>=2.31.0
35
+ Requires-Dist: edge-tts>=6.1.0
36
+ Dynamic: license-file
37
+
38
+ # bedro-system
39
+
40
+ Videolar için Türkçe altyazı gömme (`bedro_cc`) ve Türkçe seslendirme/dublaj (`bedro_db`) modüllerini içeren Python kütüphanesi.
41
+
42
+ ## Kurulum
43
+
44
+ ```bash
45
+ pip install bedro-system
46
+ ```
47
+
48
+ > Not: Sistemde `ffmpeg` kurulu olmalıdır.
49
+
50
+ ## Kullanım
51
+
52
+ ```python
53
+ from bedro_system import bedro_cc, bedro_db
54
+
55
+ # Softsub (.mkv) için format=1, Hardsub (.mp4) için format=2
56
+ bedro_cc(name="ornek_video", format=1)
57
+ bedro_cc(name="ornek_video", format=2)
58
+
59
+ # Türkçe dublaj (.mp4)
60
+ bedro_db(name="ornek_video")
61
+ ```
@@ -0,0 +1,9 @@
1
+ bedro_system/__init__.py,sha256=jLiTa8KraDbX1_2oEuMRxI8wcslsxjn4PMRktDTwG8k,120
2
+ bedro_system/bedro_cc.py,sha256=AHPDmKMKj0uwbrgvILzWrRrOx3WT_H9v-XhMIg9IAjk,18085
3
+ bedro_system/bedro_db.py,sha256=HzVD0eB35v54-jfEqxCp5OsffiCkpaiYMEBzW2lM6Sg,15673
4
+ bedro_system-0.1.0.dist-info/licenses/LICENSE,sha256=iUfBOW4N1OUD_U-v446MqtqLsPk3wCghgXhRurAqnDA,1069
5
+ bedro_system-0.1.0.dist-info/METADATA,sha256=qYcyDCmk6t-KGETl4bjnliNbv4Q3MCJ9vub8yCttLfY,2241
6
+ bedro_system-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ bedro_system-0.1.0.dist-info/entry_points.txt,sha256=T0pKtlGRpqjc9SSAxJxj5OeHDNtKgd4zKap4woui0ZE,94
8
+ bedro_system-0.1.0.dist-info/top_level.txt,sha256=HNrW-4hhyU4rzrKLNE7zL8Tqztv0xZr0Unu2GUHZyFc,13
9
+ bedro_system-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ bedro-cc = bedro_system.bedro_cc:main
3
+ bedro-db = bedro_system.bedro_db:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bedro-system
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ bedro_system