Foydalanuvchi commited on
Commit
5ebc955
·
1 Parent(s): 87df0c1

Phase 12: Auto-Subtitle (Whisper AI) - avtomatik til aniqlash va subtitle yozish

Browse files
Files changed (3) hide show
  1. filters.py +229 -0
  2. main.py +9 -3
  3. requirements.txt +1 -0
filters.py CHANGED
@@ -666,3 +666,232 @@ def process_video_nnsfw(video_path, output_path, progress_callback=None):
666
  except Exception as e:
667
  logger.error(f"Video NSFW xatosi: {e}")
668
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  except Exception as e:
667
  logger.error(f"Video NSFW xatosi: {e}")
668
  return None
669
+
670
+ # ============================================================
671
+ # AUTO-SUBTITLE (Whisper AI) 📝🎬
672
+ # ============================================================
673
+
674
+ _whisper_model = None
675
+
676
+ def get_whisper_model():
677
+ """Whisper modelini faqat kerak bo'lganda yuklaydi (lazy loading)."""
678
+ global _whisper_model
679
+ if _whisper_model is None:
680
+ try:
681
+ from faster_whisper import WhisperModel
682
+ _whisper_model = WhisperModel("small", device="cpu", compute_type="int8")
683
+ logger.info("Whisper model (small/int8) muvaffaqiyatli yuklandi.")
684
+ except ImportError:
685
+ logger.error("faster-whisper kutubxonasi o'rnatilmagan.")
686
+ return None
687
+ except Exception as e:
688
+ logger.error(f"Whisper modelni yuklashda xatolik: {e}")
689
+ return None
690
+ return _whisper_model
691
+
692
+ def _transcribe_audio(audio_path):
693
+ """Audio faylni matnga o'giradi va segmentlar ro'yxatini qaytaradi."""
694
+ model = get_whisper_model()
695
+ if model is None:
696
+ return [], "unknown"
697
+
698
+ try:
699
+ segments, info = model.transcribe(
700
+ audio_path,
701
+ beam_size=3,
702
+ vad_filter=True,
703
+ vad_parameters=dict(min_silence_duration_ms=300)
704
+ )
705
+
706
+ lang = info.language if info else "unknown"
707
+ logger.info(f"Aniqlangan til: {lang} (ehtimollik: {info.language_probability:.2f})")
708
+
709
+ result = []
710
+ for seg in segments:
711
+ result.append({
712
+ 'start': seg.start,
713
+ 'end': seg.end,
714
+ 'text': seg.text.strip()
715
+ })
716
+
717
+ logger.info(f"Jami {len(result)} ta segment topildi.")
718
+ return result, lang
719
+ except Exception as e:
720
+ logger.error(f"Transkriptsiya xatosi: {e}")
721
+ return [], "unknown"
722
+
723
+ def process_video_subtitle(video_path, output_path, progress_callback=None):
724
+ """Videoga avtomatik subtitle (Whisper AI) qo'shadi."""
725
+ from PIL import ImageFont, ImageDraw
726
+
727
+ try:
728
+ video_path = os.path.abspath(video_path)
729
+ output_path = os.path.abspath(output_path)
730
+
731
+ # 1. Videodan vaqtinchalik audio ajratish
732
+ video = VideoFileClip(video_path)
733
+
734
+ # Video uzunligini tekshirish (max 5 daqiqa)
735
+ if video.duration > 300:
736
+ logger.warning(f"Video juda uzun: {video.duration:.0f}s (max 300s)")
737
+ video.close()
738
+ return None
739
+
740
+ if video.audio is None:
741
+ logger.warning("Videoda audio topilmadi.")
742
+ video.close()
743
+ return None
744
+
745
+ temp_audio = os.path.join(os.path.dirname(video_path), f"tmp_audio_{os.getpid()}.wav")
746
+ video.audio.write_audiofile(temp_audio, fps=16000, nbytes=2, codec='pcm_s16le', logger=None)
747
+ video.close()
748
+
749
+ if progress_callback:
750
+ progress_callback(15)
751
+
752
+ # 2. Whisper orqali nutqni aniqlash
753
+ segments, lang = _transcribe_audio(temp_audio)
754
+
755
+ # Audio faylni tozalash
756
+ if os.path.exists(temp_audio):
757
+ try: os.remove(temp_audio)
758
+ except: pass
759
+
760
+ if not segments:
761
+ logger.warning("Hech qanday nutq aniqlanmadi.")
762
+ return None
763
+
764
+ if progress_callback:
765
+ progress_callback(50)
766
+
767
+ # 3. Shrift sozlamalari
768
+ font_path = None
769
+ font_paths_to_try = [
770
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
771
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
772
+ "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf",
773
+ "C:/Windows/Fonts/arialbd.ttf",
774
+ "C:/Windows/Fonts/arial.ttf",
775
+ ]
776
+ for fp in font_paths_to_try:
777
+ if os.path.exists(fp):
778
+ font_path = fp
779
+ break
780
+
781
+ # 4. Videoni qayta ochib, subtitle yozish
782
+ def subtitle_frame(get_frame, t):
783
+ frame = get_frame(t)
784
+ h, w = frame.shape[:2]
785
+
786
+ # Joriy vaqtga mos segmentni topish
787
+ current_text = None
788
+ for seg in segments:
789
+ if seg['start'] <= t <= seg['end']:
790
+ current_text = seg['text']
791
+ break
792
+
793
+ if not current_text:
794
+ return frame
795
+
796
+ # PIL orqali chiroyli matn yozish
797
+ pil_img = Image.fromarray(frame)
798
+ draw = ImageDraw.Draw(pil_img)
799
+
800
+ # Shrift o'lchami (video o'lchamiga qarab)
801
+ font_size = max(18, int(h * 0.04))
802
+ try:
803
+ if font_path:
804
+ font = ImageFont.truetype(font_path, font_size)
805
+ else:
806
+ font = ImageFont.load_default()
807
+ except:
808
+ font = ImageFont.load_default()
809
+
810
+ # Matnni satrga bo'lish (juda uzun bo'lsa)
811
+ max_chars = max(20, int(w / (font_size * 0.55)))
812
+ lines = []
813
+ words = current_text.split()
814
+ current_line = ""
815
+ for word in words:
816
+ test = current_line + (" " if current_line else "") + word
817
+ if len(test) <= max_chars:
818
+ current_line = test
819
+ else:
820
+ if current_line:
821
+ lines.append(current_line)
822
+ current_line = word
823
+ if current_line:
824
+ lines.append(current_line)
825
+
826
+ if not lines:
827
+ return frame
828
+
829
+ # Matn o'lchami hisoblash
830
+ line_height = font_size + 6
831
+ total_text_height = line_height * len(lines)
832
+
833
+ # Yarim-shaffof qora fon (pastda)
834
+ bg_y_start = h - total_text_height - 30
835
+ bg_y_end = h - 5
836
+
837
+ overlay = np.array(pil_img)
838
+ sub_bg = overlay[bg_y_start:bg_y_end, 10:w-10].copy()
839
+ dark_bg = (sub_bg * 0.3).astype(np.uint8)
840
+ overlay[bg_y_start:bg_y_end, 10:w-10] = dark_bg
841
+ pil_img = Image.fromarray(overlay)
842
+ draw = ImageDraw.Draw(pil_img)
843
+
844
+ # Matnni yozish (markazda, oq rang, qora soya)
845
+ for i, line in enumerate(lines):
846
+ bbox = draw.textbbox((0, 0), line, font=font)
847
+ text_w = bbox[2] - bbox[0]
848
+ x = (w - text_w) // 2
849
+ y = bg_y_start + 10 + (i * line_height)
850
+
851
+ # Qora soya (3D effekt)
852
+ draw.text((x+2, y+2), line, font=font, fill=(0, 0, 0))
853
+ draw.text((x-1, y-1), line, font=font, fill=(0, 0, 0))
854
+ # Asosiy oq matn
855
+ draw.text((x, y), line, font=font, fill=(255, 255, 255))
856
+
857
+ return np.array(pil_img)
858
+
859
+ # Video yuklab subtitle qo'shish
860
+ video = VideoFileClip(video_path)
861
+ from moviepy import VideoClip
862
+
863
+ subtitled = VideoClip(
864
+ lambda t: subtitle_frame(video.get_frame, t),
865
+ duration=video.duration
866
+ )
867
+
868
+ audio_params = {"audio_codec": "aac"} if video.audio else {"audio": False}
869
+ if video.audio:
870
+ subtitled = subtitled.with_audio(video.audio)
871
+
872
+ subtitled.write_videofile(
873
+ output_path,
874
+ codec="libx264",
875
+ fps=video.fps or 24,
876
+ preset="ultrafast",
877
+ threads=4,
878
+ logger=None,
879
+ **audio_params
880
+ )
881
+
882
+ video.close()
883
+ subtitled.close()
884
+
885
+ if progress_callback:
886
+ progress_callback(99)
887
+
888
+ return output_path if os.path.exists(output_path) else None
889
+ except Exception as e:
890
+ logger.error(f"Auto-Subtitle xatosi: {e}")
891
+ return None
892
+ finally:
893
+ # Vaqtinchalik fayllarni tozalash
894
+ temp_audio_path = os.path.join(os.path.dirname(video_path), f"tmp_audio_{os.getpid()}.wav")
895
+ if os.path.exists(temp_audio_path):
896
+ try: os.remove(temp_audio_path)
897
+ except: pass
main.py CHANGED
@@ -53,7 +53,8 @@ from filters import (
53
  process_video_retro, process_video_upscale, process_video_slowmo,
54
  process_video_bw, process_video_color_correct, process_video_remove_audio,
55
  process_video_trim, process_video_face_fix, process_video_auto_enhance,
56
- process_video_fps_boost, apply_nudenet_filter, process_video_nnsfw
 
57
  )
58
  from database import db
59
  from concurrent.futures import ThreadPoolExecutor
@@ -291,6 +292,9 @@ async def handle_video(update: Update, context: ContextTypes.DEFAULT_TYPE):
291
  [
292
  InlineKeyboardButton("🛡️ Media Shield", callback_data=f"n|v|{short_id}")
293
  ],
 
 
 
294
  [
295
  InlineKeyboardButton("🔙 Bekor qilish", callback_data="nav|main")
296
  ]
@@ -413,7 +417,8 @@ async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
413
  "t": process_video_trim,
414
  "vf": process_video_face_fix,
415
  "va": process_video_auto_enhance,
416
- "n": process_video_nnsfw
 
417
  }
418
  func = video_funcs.get(action)
419
  if not func:
@@ -432,7 +437,8 @@ async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
432
  "ra": "ovoz olib tashlash", "t": "kesish", "vf": "video face fix",
433
  "va": "video auto enhance", "fps30": "30 FPS boost",
434
  "fps60": "60 FPS boost", "fps120": "120 FPS boost",
435
- "n": "media shield"
 
436
  }.get(action, f"filter_{action}")
437
  db.log_history(query.from_user.id, "photo" if m_type == "p" else "video", f_name, file_id)
438
 
 
53
  process_video_retro, process_video_upscale, process_video_slowmo,
54
  process_video_bw, process_video_color_correct, process_video_remove_audio,
55
  process_video_trim, process_video_face_fix, process_video_auto_enhance,
56
+ process_video_fps_boost, apply_nudenet_filter, process_video_nnsfw,
57
+ process_video_subtitle
58
  )
59
  from database import db
60
  from concurrent.futures import ThreadPoolExecutor
 
292
  [
293
  InlineKeyboardButton("🛡️ Media Shield", callback_data=f"n|v|{short_id}")
294
  ],
295
+ [
296
+ InlineKeyboardButton("📝 Auto-Subtitle", callback_data=f"sub|v|{short_id}")
297
+ ],
298
  [
299
  InlineKeyboardButton("🔙 Bekor qilish", callback_data="nav|main")
300
  ]
 
417
  "t": process_video_trim,
418
  "vf": process_video_face_fix,
419
  "va": process_video_auto_enhance,
420
+ "n": process_video_nnsfw,
421
+ "sub": process_video_subtitle
422
  }
423
  func = video_funcs.get(action)
424
  if not func:
 
437
  "ra": "ovoz olib tashlash", "t": "kesish", "vf": "video face fix",
438
  "va": "video auto enhance", "fps30": "30 FPS boost",
439
  "fps60": "60 FPS boost", "fps120": "120 FPS boost",
440
+ "n": "media shield",
441
+ "sub": "auto-subtitle"
442
  }.get(action, f"filter_{action}")
443
  db.log_history(query.from_user.id, "photo" if m_type == "p" else "video", f_name, file_id)
444
 
requirements.txt CHANGED
@@ -11,3 +11,4 @@ dnspython
11
  httpx[socks]
12
  nudenet
13
  onnxruntime
 
 
11
  httpx[socks]
12
  nudenet
13
  onnxruntime
14
+ faster-whisper