Opera8 commited on
Commit
bc54095
·
verified ·
1 Parent(s): 2bbf851

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1926 -369
app.py CHANGED
@@ -34,8 +34,6 @@ def _coerce_audio_path(audio_path: Any) -> str:
34
 
35
  # pathlib.Path etc.
36
  if not isinstance(audio_path, (str, bytes, os.PathLike)):
37
- # Allow None
38
- if audio_path is None: return None
39
  raise TypeError(f"audio_path must be a path-like, got {type(audio_path)}: {audio_path}")
40
 
41
  return os.fspath(audio_path)
@@ -91,9 +89,6 @@ def match_audio_to_duration(
91
  Load audio, resample, (optionally) mono, then trim/pad to exactly target_seconds.
92
  Returns: (waveform[T] or [1,T], sr)
93
  """
94
- if audio_path is None:
95
- return None, None
96
-
97
  audio_path = _coerce_audio_path(audio_path)
98
 
99
  wav, sr = torchaudio.load(audio_path) # [C, T] float32 CPU
@@ -552,6 +547,690 @@ print("Pipeline fully loaded and ready!")
552
  print("=" * 80)
553
 
554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  ####################################################################################################
556
  ### PART 17: Wrapper Functions (Resolution, Duration, Examples)
557
  ####################################################################################################
@@ -642,129 +1321,118 @@ def generate_video(
642
  """
643
  Generate a short cinematic video from a text prompt and optional input image using the LTX-2 distilled pipeline.
644
  """
645
-
646
- # Explicitly catch and re-raise quota errors if they happen inside execution
647
- # though usually spaces.GPU catches them before.
648
- try:
649
 
650
- # Removed the 15s warning check since 15s option is removed from UI
651
 
652
- if audio_path is None:
653
- print(f'generating with duration:{duration} and LoRA:{camera_lora} in {width}x{height}')
654
- else:
655
- print(f'generating with duration:{duration} and audio in {width}x{height}')
 
 
 
 
 
 
 
 
656
 
657
- # Randomize seed if checkbox is enabled
658
- current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
659
 
660
- # Calculate num_frames from duration (using fixed 24 fps)
661
- frame_rate = 24.0
662
- num_frames = int(duration * frame_rate) + 1 # +1 to ensure we meet the duration
663
- video_seconds = int(duration)
664
 
665
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
666
- output_path = tmpfile.name
667
 
 
668
 
 
669
  images = []
670
- videos = []
671
-
672
- # Removed Motion Control block
673
-
674
- if first_frame is not None:
675
- images = []
676
- images.append((first_frame, 0, 1.0))
677
-
678
- # Updated logic for Persian string
679
- if generation_mode == "تکمیل فریم‌های میانی":
680
- if end_frame is not None:
681
- end_idx = max(0, num_frames - 1)
682
- images.append((end_frame, end_idx, 0.5))
683
-
684
- embeddings, final_prompt, status = encode_prompt(
685
- prompt=prompt,
686
- enhance_prompt=enhance_prompt,
687
- input_image=first_frame,
688
- seed=current_seed,
689
- negative_prompt="",
690
- )
691
-
692
- video_context = embeddings["video_context"].to("cuda", non_blocking=True)
693
- audio_context = embeddings["audio_context"].to("cuda", non_blocking=True)
694
- print("✓ Embeddings loaded successfully")
695
 
696
 
697
- # free prompt enhancer / encoder temps ASAP
698
- del embeddings, final_prompt, status
699
- torch.cuda.empty_cache()
700
 
701
- # ✅ if user provided audio, use a neutral audio_context
702
- n_audio_context = None
 
 
 
 
 
 
703
 
704
- if audio_path is not None:
705
- with torch.inference_mode():
706
- _, n_audio_context = encode_text_simple(text_encoder, "") # returns tensors on GPU already
707
- del audio_context
708
- audio_context = n_audio_context
709
 
710
- if len(videos) == 0:
711
- camera_lora = "Static"
712
 
713
- torch.cuda.empty_cache()
 
 
714
 
715
- # Map dropdown name -> adapter index
716
- name_to_idx = {name: idx for name, idx in RUNTIME_LORA_CHOICES}
717
- selected_idx = name_to_idx.get(camera_lora, -1)
718
 
719
- enable_only_lora(pipeline._transformer, selected_idx)
720
- torch.cuda.empty_cache()
721
 
722
- # True video duration in seconds based on your rounding
723
- video_seconds = (num_frames - 1) / frame_rate
 
 
 
 
 
 
 
 
 
 
724
 
725
- if audio_path is not None:
726
- input_waveform, input_waveform_sample_rate = match_audio_to_duration(
727
- audio_path=audio_path,
728
- target_seconds=video_seconds,
729
- target_sr=48000, # pick what your model expects; 48k is common for AV models
730
- to_mono=True, # set False if your model wants stereo
731
- pad_mode="silence", # or "repeat" if you prefer looping over silence
732
- device="cuda",
 
 
 
 
 
 
 
 
 
733
  )
734
- else:
735
- input_waveform = None
736
- input_waveform_sample_rate = None
737
-
738
- with timer(f'generating with LoRA:{camera_lora} in {width}x{height}'):
739
- with torch.inference_mode():
740
- pipeline(
741
- prompt=prompt,
742
- output_path=str(output_path),
743
- seed=current_seed,
744
- height=height,
745
- width=width,
746
- num_frames=num_frames,
747
- frame_rate=frame_rate,
748
- images=images,
749
- video_conditioning=videos,
750
- tiling_config=TilingConfig.default(),
751
- video_context=video_context,
752
- audio_context=audio_context,
753
- input_waveform=input_waveform,
754
- input_waveform_sample_rate=input_waveform_sample_rate,
755
- )
756
- del video_context, audio_context
757
- torch.cuda.empty_cache()
758
- print("successful generation")
759
 
760
- return str(output_path)
761
-
762
- except Exception as e:
763
- error_str = str(e)
764
- if "quota" in error_str.lower() or "exceeded" in error_str.lower():
765
- raise e
766
- print(f"Generation Error: {e}")
767
- raise e
768
 
769
 
770
  def apply_resolution(resolution: str):
@@ -779,11 +1447,7 @@ def apply_resolution(resolution: str):
779
  return int(w), int(h)
780
 
781
  def apply_duration(duration: str):
782
- # Standard format: "5s"
783
- try:
784
- duration_s = int(str(duration).replace("s", ""))
785
- except:
786
- duration_s = 5
787
  return duration_s
788
 
789
  def on_mode_change(selected: str):
@@ -798,10 +1462,51 @@ def on_mode_change(selected: str):
798
  ### PART 19: CSS Styles
799
  ####################################################################################################
800
  css = """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801
  #col-container {
802
  margin: 0 auto;
803
  max-width: 1600px;
804
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
805
  .button-gradient {
806
  background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
807
  border: none;
@@ -815,224 +1520,911 @@ css = """
815
  animation: 2s linear 0s infinite normal none running gradientAnimation;
816
  box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
817
  }
818
- @keyframes gradientAnimation {
819
- 0% { background-position: 0% 50%; }
820
- 50% { background-position: 100% 50%; }
821
- 100% { background-position: 0% 50%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823
 
824
- /* Footer Hiding */
825
- footer { display: none !important; }
826
- .gradio-container footer { display: none !important; }
827
- div.footer { display: none !important; }
828
- .flagging { display: none !important; }
829
- .api-logo, .built-with { display: none !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
 
831
- /* Center Title */
832
- .title-container { text-align: center; padding: 20px; }
833
- .title-text { font-size: 28px; font-weight: bold; margin-bottom: 10px; color: var(--body-text-color); }
834
- .subtitle-text { font-size: 18px; color: var(--body-text-color-subdued); margin: 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
835
  """
836
 
837
- # --- MODAL CSS Injection ---
838
  css += """
839
- /* Modal CSS */
840
- :root { --guide-bg: rgba(255, 255, 255, 0.98); --guide-border: rgba(102, 126, 234, 0.2); --guide-text-title: #2d3748; --guide-text-body: #4a5568; --guide-accent: #667eea; --primary-gradient-guide: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --success-gradient-guide: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%); --radius-md-guide: 12px; --radius-lg-guide: 16px; --shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05); }
841
- @keyframes float { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); } }
842
- @keyframes slideInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
843
- .ip-reset-guide-container { text-align: right; direction: rtl; background: var(--guide-bg); backdrop-filter: blur(10px); padding: 20px; border-radius: var(--radius-lg-guide); box-shadow: var(--shadow-xl); border: 1px solid var(--guide-border); animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) both; width: 90%; max-width: 420px; max-height: 90vh; overflow-y: auto; position: relative; box-sizing: border-box; font-family: 'Vazirmatn', sans-serif !important; }
844
- .ip-reset-guide-container::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: var(--primary-gradient-guide); }
845
- .guide-header { display: flex; align-items: center; margin-bottom: 15px; }
846
- .guide-header-icon { width: 45px; height: 45px; margin-left: 15px; animation: float 3s ease-in-out infinite; flex-shrink: 0; }
847
- .guide-header h2 { font-size: 1.2rem; color: var(--guide-text-title); font-weight: 700; margin: 0; }
848
- .guide-header p { color: var(--guide-text-body); font-size: 0.8rem; margin-top: 3px; margin-bottom: 0; }
849
- .guide-content { font-size: 0.9rem; color: var(--guide-text-body); line-height: 1.6; }
850
- .info-card { background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid rgba(102, 126, 234, 0.2); border-radius: var(--radius-md-guide); padding: 12px; margin: 12px 0; position: relative; overflow: hidden; }
851
- .info-card p { font-size: 0.85rem; line-height: 1.6; margin: 0; }
852
- .info-card::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--primary-gradient-guide); }
853
- .info-card-header { display: flex; align-items: center; margin-bottom: 8px; }
854
- .info-card-icon { width: 18px; height: 18px; margin-left: 8px; }
855
- .info-card-title { font-weight: 600; color: var(--guide-text-title); font-size: 0.95rem; }
856
- .summary-section { margin-top: 12px; padding: 12px; border-radius: var(--radius-md-guide); background: linear-gradient(135deg, #56ab2f15 0%, #a8e06315 100%); border: 1px solid rgba(86, 171, 47, 0.2); position: relative; overflow: hidden; }
857
- .summary-section::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--success-gradient-guide); }
858
- .summary-header { display: flex; align-items: center; margin-bottom: 8px; }
859
- .summary-icon { width: 18px; height: 18px; margin-left: 8px; }
860
- .summary-title { font-weight: 600; color: #2f5a33; font-size: 0.95rem; }
861
- .summary-text { color: #2f5a33; font-size: 0.85rem; line-height: 1.6; }
862
- .video-button-container { text-align: center; margin: 20px 0 15px 0; width: 100%; }
863
- .elegant-video-button { display: inline-flex !important; align-items: center; justify-content: center; padding: 10px 20px !important; background-color: #fff !important; color: var(--guide-accent) !important; border: 1px solid #e2e8f0 !important; text-decoration: none; border-radius: 50px !important; font-weight: 600 !important; font-size: 0.9rem !important; cursor: pointer !important; font-family: inherit; transition: all 0.3s ease !important; box-shadow: 0 2px 10px rgba(0,0,0,0.05) !important; width: auto !important; }
864
- .elegant-video-button:hover { background: var(--primary-gradient-guide) !important; color: white !important; border-color: transparent !important; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3) !important; }
865
- .elegant-video-button-icon { width: 18px; height: 18px; margin-left: 8px; fill: currentColor; }
866
- .guide-actions { display: flex !important; gap: 12px !important; margin-top: 20px; padding-top: 20px; border-top: 1px solid #e2e8f0; width: 100% !important; }
867
- .action-button { padding: 12px 15px !important; border: none !important; border-radius: 12px !important; font-size: 0.95rem !important; font-weight: 600 !important; cursor: pointer !important; flex: 1 !important; transition: all 0.3s ease !important; display: flex !important; align-items: center; justify-content: center; font-family: inherit; height: 48px !important; }
868
- .action-button-icon { width: 20px; height: 20px; margin-right: 0; margin-left: 8px; }
869
- .back-button { background: white !important; color: var(--guide-text-body) !important; border: 2px solid #e2e8f0 !important; }
870
- .back-button:hover { background: #f7fafc !important; border-color: var(--guide-accent) !important; transform: translateY(-2px); }
871
- .retry-button { background: var(--primary-gradient-guide) !important; color: white !important; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important; }
872
- .retry-button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important; }
873
  """
874
 
 
875
  def apply_example(idx: str):
876
- # Standard Gr.Examples handler (returns raw values)
877
- # The new Examples component passes the values directly, no need for complex lookup usually
878
- # But since we use a custom list, we might just pass the list values
879
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880
 
881
- # Since we are using standard gr.Examples, we don't need the complex lookup function
882
- # Gradio handles mapping automatically if set up right.
883
 
884
  ####################################################################################################
885
  ### PART 20: Gradio UI Layout & Launch
886
  ####################################################################################################
887
 
888
- with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
 
 
 
 
 
 
889
 
890
- # --- JS QUOTA HANDLER ---
891
- js_quota_handler = """
892
- <script>
893
- document.addEventListener('DOMContentLoaded', () => {
894
-
895
- // Per-Space Font loading
896
- const link = document.createElement('link');
897
- link.href = 'https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap';
898
- link.rel = 'stylesheet';
899
- document.head.appendChild(link);
900
-
901
- // ---------------------------------------------
902
- // GPU QUOTA HANDLER & UI FIXES
903
- // ---------------------------------------------
904
 
905
- window.quotaModalActive = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
906
 
907
- window.retryGeneration = function() {
908
- const modal = document.getElementById('custom-quota-modal');
909
- if (modal) modal.remove();
910
- window.quotaModalActive = false; // Reset flag
911
-
912
- // TARGET THE NEW GENERATE BUTTON ID
913
- const runBtn = document.getElementById('generate-btn');
914
- if(runBtn) {
915
- runBtn.click();
916
- setTimeout(() => runBtn.click(), 100);
917
- }
918
- };
919
-
920
- window.closeErrorModal = function() {
921
- const modal = document.getElementById('custom-quota-modal');
922
- if (modal) modal.remove();
923
- window.quotaModalActive = false; // Reset flag
924
-
925
- // Clear text errors
926
- document.querySelectorAll('.toast-body, .error, div[class*="error"]').forEach(el => {
927
- el.innerText = '';
928
- el.style.display = 'none';
929
- });
930
- };
931
-
932
- const showQuotaModal = () => {
933
- if (window.quotaModalActive || document.getElementById('custom-quota-modal')) return;
934
- window.quotaModalActive = true;
935
-
936
- const modalHtml = `
937
- <div id="custom-quota-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); backdrop-filter: blur(5px); z-index: 99999; display: flex; align-items: center; justify-content: center; font-family: 'Vazirmatn', sans-serif;">
938
- <div class="ip-reset-guide-container">
939
- <div class="guide-header">
940
- <svg class="guide-header-icon" viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
941
- <defs><lineargradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color: #667eea; stop-opacity: 1;"></stop><stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1;"></stop></lineargradient></defs>
942
- <circle cx="50" cy="50" r="45" fill="url(#grad1)" opacity="0.1"></circle>
943
- <circle cx="50" cy="50" r="35" fill="none" stroke="url(#grad1)" stroke-width="2" opacity="0.3"></circle>
944
- <path d="M35 50 L45 60 L65 40" stroke="url(#grad1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path>
945
- <circle cx="65" cy="35" r="8" fill="#fee140"></circle>
946
- <path d="M62 35 L68 35 M65 32 L65 38" stroke="white" stroke-width="2" stroke-linecap="round"></path>
947
- </svg>
948
- <div>
949
- <h2>یک قدم تا ساخت ویدیوهای جدید</h2>
950
- <p>نیازمند تغییر نقطه دستیابی</p>
951
- </div>
952
- </div>
953
-
954
- <div class="guide-content">
955
- <div class="info-card">
956
- <div class="info-card-header">
957
- <svg class="info-card-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" fill="#667eea" opacity="0.2"></path><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#667eea" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
958
- <span class="info-card-title">راه حل سریع</span>
959
- </div>
960
- <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
961
- </div>
962
-
963
- <div class="summary-section">
964
- <div class="summary-header">
965
- <svg class="summary-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="#56ab2f" opacity="0.2"></circle><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" stroke="#56ab2f" stroke-width="2"></path><path d="M9 12l2 2 4-4" stroke="#56ab2f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
966
- <span class="summary-title">خلاصه راهنما</span>
967
- </div>
968
- <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیم‌کارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید. با این روش ساده می‌توانید به صورت نامحدود تصویر بسازید! ☘️</div>
969
- </div>
970
-
971
- <div class="video-button-container">
972
- <button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210' }, '*')" class="elegant-video-button">
973
- <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
974
- <span>دیدن ویدیو آموزشی استفاده نامحدود</span>
975
- </button>
976
- </div>
977
- </div>
978
-
979
- <div class="guide-actions">
980
- <button class="action-button back-button" onclick="window.closeErrorModal()">
981
- <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
982
- <span>بازگشت</span>
983
- </button>
984
- <button class="action-button retry-button" onclick="window.retryGeneration()">
985
- <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M23 4v6h-6M1 20v-6h6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
986
- <span>تلاش مجدد</span>
987
- </button>
988
- </div>
989
- </div>
990
- </div>
991
- `;
992
-
993
- document.body.insertAdjacentHTML('beforeend', modalHtml);
994
- };
995
-
996
- // Polling loop to find errors
997
- setInterval(() => {
998
- document.querySelectorAll('.toast-body, .error, div[class*="error"]').forEach(el => {
999
- const text = (el.innerText||"").toLowerCase();
1000
- if (text.includes('quota') || text.includes('exceeded')) {
1001
- showQuotaModal();
1002
- el.style.display = 'none'; // Hide the ugly default error
1003
- }
1004
- });
1005
- }, 100);
1006
- });
1007
- </script>
1008
- """
1009
 
1010
- gr.HTML(js_quota_handler)
 
1011
 
1012
- # Standard HTML Header
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1013
  gr.HTML(
1014
  """
1015
- <div class="title-container">
1016
- <h1 class="title-text">ساخت ویدیو با هوش مصنوعی</h1>
1017
- <p class="subtitle-text">با پشتیبانی از صدا و دو تصویر</p>
 
 
 
 
1018
  </div>
1019
  """
1020
  )
1021
 
1022
  with gr.Column(elem_id="col-container"):
1023
- with gr.Row():
1024
- # Standard Radio Button instead of Custom one
1025
- mode_radio = gr.Radio(
1026
  choices=["تبدیل تصویر به ویدیو", "تکمیل فریم‌های میانی"],
1027
  value="تبدیل تصویر به ویدیو",
1028
- label="حالت اجرا",
1029
- interactive=True
1030
  )
1031
-
1032
  with gr.Row():
1033
  with gr.Column(elem_id="step-column"):
1034
 
1035
  with gr.Row():
 
1036
  first_frame = gr.Image(
1037
  label="تصویر اول (اختیاری)",
1038
  type="filepath",
@@ -1046,34 +2438,82 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
1046
  visible=False,
1047
  )
1048
 
1049
- # input_video is defined but hidden (backend legacy)
1050
  input_video = gr.Video(
1051
  label="Motion Reference Video",
1052
  height=256,
1053
  visible=False,
1054
  )
1055
 
1056
- # Standard Textbox instead of PromptBox
1057
- prompt = gr.Textbox(
1058
- label="متن دستور (Prompt)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1059
  value="این تصویر را با حرکت سینمایی و انیمیشن روان زنده کن",
1060
- lines=3,
1061
- placeholder="حرکت و انیمیشن مورد نظر خود را توصیف کنید...",
1062
  )
1063
 
1064
- # Standard Audio Input instead of Custom Uploader
1065
- audio_input = gr.Audio(
1066
- label="فایل صوتی (اختیاری)",
 
1067
  type="filepath",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1068
  )
1069
 
1070
  enhance_prompt = gr.Checkbox(
1071
- label="بهبود خودکار متن (Enhance Prompt)",
1072
  value=True,
1073
  visible=False
1074
  )
1075
 
1076
- with gr.Accordion("تنظیمات پیشرفته", open=False):
1077
  seed = gr.Slider(
1078
  label="سید (Seed)",
1079
  minimum=0,
@@ -1087,65 +2527,108 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
1087
 
1088
  with gr.Column(elem_id="step-column"):
1089
  output_video = gr.Video(label="ویدیوی ساخته شده", autoplay=True, height=512)
 
 
 
1090
 
1091
- with gr.Row():
1092
- # Standard Dropdowns instead of Custom
1093
- duration_dropdown = gr.Dropdown(
1094
  choices=["3s", "5s", "10s"],
1095
  value="5s",
1096
- label="مدت زمان",
1097
- interactive=True
 
 
 
 
 
 
 
 
 
1098
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
 
1100
- resolution_dropdown = gr.Dropdown(
1101
- choices=["16:9", "1:1", "9:16"],
 
 
 
 
1102
  value="16:9",
1103
- label="ابعاد تصویر",
1104
- interactive=True
1105
  )
1106
 
1107
- camera_dropdown = gr.Dropdown(
 
 
 
 
1108
  choices=[name for name, _ in VISIBLE_RUNTIME_LORA_CHOICES],
1109
  value="No LoRA",
1110
- label="افکت دوربین (LoRA)",
1111
- interactive=True
 
 
 
 
 
 
 
 
1112
  )
1113
 
1114
- # Hidden state holders
1115
- width = gr.Number(label="Width", value=DEFAULT_1_STAGE_WIDTH, visible=False)
1116
- height = gr.Number(label="Height", value=DEFAULT_1_STAGE_HEIGHT, visible=False)
1117
- duration_val = gr.Number(value=5.0, visible=False)
1118
 
1119
- # IMPORTANT: Added elem_id="generate-btn" for JS control
1120
- generate_btn = gr.Button("🤩 ساخت ویدیو", variant="primary", elem_classes="button-gradient", elem_id="generate-btn")
1121
 
 
 
 
 
 
 
1122
 
1123
- # Logic Linking
1124
-
1125
- def update_resolution_vars(choice):
1126
- w, h = apply_resolution(choice)
1127
- return w, h
1128
-
1129
- resolution_dropdown.change(
1130
- fn=update_resolution_vars,
1131
- inputs=resolution_dropdown,
1132
- outputs=[width, height]
1133
  )
1134
 
1135
- def update_duration_var(choice):
1136
- return apply_duration(choice)
1137
 
1138
- duration_dropdown.change(
1139
- fn=update_duration_var,
1140
- inputs=duration_dropdown,
1141
- outputs=[duration_val]
 
1142
  )
1143
-
1144
- mode_radio.change(
1145
- fn=on_mode_change,
1146
- inputs=mode_radio,
1147
- outputs=[input_video, end_frame],
 
 
 
 
 
 
1148
  )
 
1149
 
1150
  generate_btn.click(
1151
  fn=generate_video,
@@ -1153,70 +2636,144 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
1153
  first_frame,
1154
  end_frame,
1155
  prompt,
1156
- duration_val,
1157
  input_video,
1158
- mode_radio,
1159
  enhance_prompt,
1160
  seed,
1161
  randomize_seed,
1162
  height,
1163
  width,
1164
- camera_dropdown,
1165
  audio_input
1166
  ],
1167
  outputs=[output_video]
1168
  )
 
 
 
 
 
 
 
1169
 
1170
- # Standard Examples Component
1171
  examples_list = [
1172
  [
1173
  "examples/supergirl-2.png",
1174
- None, # End frame
1175
- "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit sleeping in bed and just waking up...",
1176
  "Static",
1177
  "16:9",
1178
  "تبدیل تصویر به ویدیو",
 
1179
  "examples/supergirl.m4a",
 
1180
  ],
1181
  [
1182
  "examples/frame3.png",
1183
- "examples/frame4.png", # End frame
1184
- "a woman in a white dress standing in a supermarket, looking at a stack of pomegranates...",
1185
  "Zoom In",
1186
  "16:9",
1187
  "تکمیل فریم‌های میانی",
1188
  None,
 
 
1189
  ],
1190
  [
1191
  "examples/supergirl.png",
 
 
 
 
 
 
1192
  None,
1193
- "A fuzzy puppet superhero character resembling a female puppet with blonde hair...",
 
 
 
1194
  "No LoRA",
1195
  "16:9",
1196
  "تبدیل تصویر به ویدیو",
1197
  None,
 
 
1198
  ],
1199
  [
1200
  "examples/wednesday.png",
1201
- None,
1202
- "A cinematic dolly out of Wednesday Addams frozen mid-dance...",
1203
- "Zoom Out",
1204
  "16:9",
1205
  "تبدیل تصویر به ویدیو",
1206
  None,
1207
- ]
 
 
 
 
 
 
 
 
 
 
 
 
1208
  ]
1209
 
1210
- # Map examples to inputs
1211
- # Inputs order in list: [first_frame, end_frame, prompt, camera, res, mode, audio]
1212
- # Inputs order in function: [first_frame, end_frame, prompt, duration, input_video, mode, enhance, seed, rand, h, w, cam, audio]
1213
-
1214
- # To simplify, we just use a clickable gallery or standard Examples that populates fields
1215
- gr.Examples(
1216
  examples=examples_list,
1217
- inputs=[first_frame, end_frame, prompt, camera_dropdown, resolution_dropdown, mode_radio, audio_input],
1218
- label="نمونه‌ها"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1219
  )
1220
 
1221
  if __name__ == "__main__":
1222
- demo.launch(ssr_mode=False, css=css, allowed_paths=["./examples"])
 
34
 
35
  # pathlib.Path etc.
36
  if not isinstance(audio_path, (str, bytes, os.PathLike)):
 
 
37
  raise TypeError(f"audio_path must be a path-like, got {type(audio_path)}: {audio_path}")
38
 
39
  return os.fspath(audio_path)
 
89
  Load audio, resample, (optionally) mono, then trim/pad to exactly target_seconds.
90
  Returns: (waveform[T] or [1,T], sr)
91
  """
 
 
 
92
  audio_path = _coerce_audio_path(audio_path)
93
 
94
  wav, sr = torchaudio.load(audio_path) # [C, T] float32 CPU
 
547
  print("=" * 80)
548
 
549
 
550
+ ####################################################################################################
551
+ ### PART 12: Custom Component - RadioAnimated
552
+ ####################################################################################################
553
+ class RadioAnimated(gr.HTML):
554
+ """
555
+ Animated segmented radio (like iOS pill selector).
556
+ Outputs: selected option string, e.g. "768x512"
557
+ """
558
+ def __init__(self, choices, value=None, **kwargs):
559
+ if not choices or len(choices) < 2:
560
+ raise ValueError("RadioAnimated requires at least 2 choices.")
561
+ if value is None:
562
+ value = choices[0]
563
+
564
+ uid = uuid.uuid4().hex[:8] # unique per instance
565
+ group_name = f"ra-{uid}"
566
+
567
+ inputs_html = "\n".join(
568
+ f"""
569
+ <input class="ra-input" type="radio" name="{group_name}" id="{group_name}-{i}" value="{c}">
570
+ <label class="ra-label" for="{group_name}-{i}">{c}</label>
571
+ """
572
+ for i, c in enumerate(choices)
573
+ )
574
+
575
+ # NOTE: use classes instead of duplicate IDs
576
+ html_template = f"""
577
+ <div class="ra-wrap" data-ra="{uid}">
578
+ <div class="ra-inner">
579
+ <div class="ra-highlight"></div>
580
+ {inputs_html}
581
+ </div>
582
+ </div>
583
+ """
584
+
585
+ js_on_load = r"""
586
+ (() => {
587
+ const wrap = element.querySelector('.ra-wrap');
588
+ const inner = element.querySelector('.ra-inner');
589
+ const highlight = element.querySelector('.ra-highlight');
590
+ const inputs = Array.from(element.querySelectorAll('.ra-input'));
591
+ const labels = Array.from(element.querySelectorAll('.ra-label'));
592
+
593
+ if (!inputs.length || !labels.length) return;
594
+
595
+ const choices = inputs.map(i => i.value);
596
+ const PAD = 6; // must match .ra-inner padding and .ra-highlight top/left
597
+
598
+ let currentIdx = 0;
599
+
600
+ function setHighlightByIndex(idx) {
601
+ currentIdx = idx;
602
+
603
+ const lbl = labels[idx];
604
+ if (!lbl) return;
605
+
606
+ const innerRect = inner.getBoundingClientRect();
607
+ const lblRect = lbl.getBoundingClientRect();
608
+
609
+ // width matches the label exactly
610
+ highlight.style.width = `${lblRect.width}px`;
611
+
612
+ // highlight has left: 6px, so subtract PAD to align
613
+ const x = (lblRect.left - innerRect.left - PAD);
614
+ highlight.style.transform = `translateX(${x}px)`;
615
+ }
616
+
617
+ function setCheckedByValue(val, shouldTrigger=false) {
618
+ const idx = Math.max(0, choices.indexOf(val));
619
+ inputs.forEach((inp, i) => { inp.checked = (i === idx); });
620
+
621
+ // Wait a frame in case fonts/layout settle (prevents rare drift)
622
+ requestAnimationFrame(() => setHighlightByIndex(idx));
623
+
624
+ props.value = choices[idx];
625
+ if (shouldTrigger) trigger('change', props.value);
626
+ }
627
+
628
+ // Init
629
+ setCheckedByValue(props.value ?? choices[0], false);
630
+
631
+ // Input handlers
632
+ inputs.forEach((inp) => {
633
+ inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
634
+ });
635
+
636
+ // Recalc on resize (important in Gradio layouts)
637
+ window.addEventListener('resize', () => setHighlightByIndex(currentIdx));
638
+
639
+ // sync from Python (Examples / backend updates)
640
+ let last = props.value;
641
+ const syncFromProps = () => {
642
+ if (props.value !== last) {
643
+ last = props.value;
644
+ setCheckedByValue(last, false);
645
+ }
646
+ requestAnimationFrame(syncFromProps);
647
+ };
648
+ requestAnimationFrame(syncFromProps);
649
+
650
+ })();
651
+
652
+ """
653
+
654
+ super().__init__(
655
+ value=value,
656
+ html_template=html_template,
657
+ js_on_load=js_on_load,
658
+ **kwargs
659
+ )
660
+
661
+
662
+ ####################################################################################################
663
+ ### PART 13: Custom Component - PromptBox
664
+ ####################################################################################################
665
+ class PromptBox(gr.HTML):
666
+ """
667
+ Prompt textarea with an internal footer slot (.ds-footer) where we can inject dropdowns.
668
+ """
669
+ def __init__(self, value="", placeholder="Describe what you want...", **kwargs):
670
+ uid = uuid.uuid4().hex[:8]
671
+
672
+ html_template = f"""
673
+ <div class="ds-card" data-ds="{uid}">
674
+ <div class="ds-top">
675
+ <textarea class="ds-textarea" rows="3" placeholder="{placeholder}"></textarea>
676
+
677
+ <!-- footer slot -->
678
+ <div class="ds-footer" aria-label="prompt-footer"></div>
679
+ </div>
680
+ </div>
681
+ """
682
+
683
+ js_on_load = r"""
684
+ (() => {
685
+ const textarea = element.querySelector(".ds-textarea");
686
+ if (!textarea) return;
687
+
688
+ const autosize = () => {
689
+ textarea.style.height = "0px";
690
+ textarea.style.height = Math.min(textarea.scrollHeight, 240) + "px";
691
+ };
692
+
693
+ const setValue = (v, triggerChange=false) => {
694
+ const val = (v ?? "");
695
+ if (textarea.value !== val) textarea.value = val;
696
+ autosize();
697
+ props.value = textarea.value;
698
+ if (triggerChange) trigger("change", props.value);
699
+ };
700
+
701
+ setValue(props.value, false);
702
+
703
+ textarea.addEventListener("input", () => {
704
+ autosize();
705
+ props.value = textarea.value;
706
+ trigger("change", props.value);
707
+ });
708
+
709
+ // ✅ Focus-on-load (robust)
710
+ const shouldAutoFocus = () => {
711
+ // don’t steal focus if user already clicked/typed somewhere
712
+ const ae = document.activeElement;
713
+ if (ae && ae !== document.body && ae !== document.documentElement) return false;
714
+ // don’t auto-focus on small screens (optional; avoids mobile keyboard pop)
715
+ if (window.matchMedia && window.matchMedia("(max-width: 768px)").matches) return false;
716
+ return true;
717
+ };
718
+
719
+ const focusWithRetry = (tries = 30) => {
720
+ if (!shouldAutoFocus()) return;
721
+ // only focus if still not focused
722
+ if (document.activeElement !== textarea) textarea.focus({ preventScroll: true });
723
+ if (document.activeElement === textarea) return;
724
+ if (tries > 0) requestAnimationFrame(() => focusWithRetry(tries - 1));
725
+ };
726
+
727
+ // wait a tick so Gradio/layout settles
728
+ requestAnimationFrame(() => focusWithRetry());
729
+
730
+ // keep your sync loop
731
+ let last = props.value;
732
+ const syncFromProps = () => {
733
+ if (props.value !== last) {
734
+ last = props.value;
735
+ setValue(last, false);
736
+ }
737
+ requestAnimationFrame(syncFromProps);
738
+ };
739
+ requestAnimationFrame(syncFromProps);
740
+ })();
741
+
742
+ """
743
+
744
+ super().__init__(value=value, html_template=html_template, js_on_load=js_on_load, **kwargs)
745
+
746
+
747
+ ####################################################################################################
748
+ ### PART 14: Custom Component - CameraDropdown
749
+ ####################################################################################################
750
+ class CameraDropdown(gr.HTML):
751
+ """
752
+ Custom dropdown (More-style) with optional icons per item.
753
+ Outputs: selected option string, e.g. "16:9"
754
+ """
755
+ def __init__(self, choices, value="None", title="Dropdown", **kwargs):
756
+ if not choices:
757
+ raise ValueError("CameraDropdown requires choices.")
758
+
759
+ # Normalize choices -> list of dicts: {label, value, icon(optional)}
760
+ norm = []
761
+ for c in choices:
762
+ if isinstance(c, dict):
763
+ label = str(c.get("label", c.get("value", "")))
764
+ val = str(c.get("value", label))
765
+ icon = c.get("icon", None) # emoji or svg/html
766
+ norm.append({"label": label, "value": val, "icon": icon})
767
+ else:
768
+ s = str(c)
769
+ norm.append({"label": s, "value": s, "icon": None})
770
+
771
+ uid = uuid.uuid4().hex[:8]
772
+
773
+ def render_item(item):
774
+ icon_html = ""
775
+ if item["icon"]:
776
+ icon_html = f'<span class="cd-icn">{item["icon"]}</span>'
777
+ return (
778
+ f'<button type="button" class="cd-item" '
779
+ f'data-value="{item["value"]}">'
780
+ f'{icon_html}<span class="cd-label">{item["label"]}</span>'
781
+ f'</button>'
782
+ )
783
+
784
+ items_html = "\n".join(render_item(item) for item in norm)
785
+
786
+ html_template = f"""
787
+ <div class="cd-wrap" data-cd="{uid}">
788
+ <button type="button" class="cd-trigger" aria-haspopup="menu" aria-expanded="false">
789
+ <span class="cd-trigger-icon"></span>
790
+ <span class="cd-trigger-text"></span>
791
+ <span class="cd-caret">▾</span>
792
+ </button>
793
+
794
+ <div class="cd-menu" role="menu" aria-hidden="true">
795
+ <div class="cd-title">{title}</div>
796
+ <div class="cd-items">
797
+ {items_html}
798
+ </div>
799
+ </div>
800
+ </div>
801
+ """
802
+
803
+ # Pass a mapping value->label so the trigger can show label text
804
+ # (and still output value to Python)
805
+ value_to_label = {it["value"]: it["label"] for it in norm}
806
+ value_to_icon = {it["value"]: (it["icon"] or "") for it in norm}
807
+
808
+ js_on_load = r"""
809
+ (() => {
810
+ const wrap = element.querySelector(".cd-wrap");
811
+ const trigger = element.querySelector(".cd-trigger");
812
+ const triggerIcon = element.querySelector(".cd-trigger-icon");
813
+ const triggerText = element.querySelector(".cd-trigger-text");
814
+ const menu = element.querySelector(".cd-menu");
815
+ const items = Array.from(element.querySelectorAll(".cd-item"));
816
+ if (!wrap || !trigger || !menu || !items.length) return;
817
+
818
+ const valueToLabel = __VALUE_TO_LABEL__;
819
+ const valueToIcon = __VALUE_TO_ICON__;
820
+
821
+ const safeLabel = (v) => (valueToLabel && valueToLabel[v]) ? valueToLabel[v] : (v ?? "None");
822
+ const safeIcon = (v) => (valueToIcon && valueToIcon[v]) ? valueToIcon[v] : "";
823
+
824
+
825
+ function closeMenu() {
826
+ menu.classList.remove("open");
827
+ trigger.setAttribute("aria-expanded", "false");
828
+ menu.setAttribute("aria-hidden", "true");
829
+ }
830
+
831
+ function openMenu() {
832
+ menu.classList.add("open");
833
+ trigger.setAttribute("aria-expanded", "true");
834
+ menu.setAttribute("aria-hidden", "false");
835
+ }
836
+
837
+ function setValue(val, shouldTrigger = false) {
838
+ const v = (val ?? "None");
839
+ props.value = v;
840
+
841
+ // Trigger shows LABEL only (icons stay in menu)
842
+ triggerText.textContent = safeLabel(v);
843
+ if (triggerIcon) {
844
+ triggerIcon.innerHTML = safeIcon(v);
845
+ triggerIcon.style.display = safeIcon(v) ? "inline-flex" : "none";
846
+ }
847
+
848
+
849
+ items.forEach(btn => {
850
+ btn.dataset.selected = (btn.dataset.value === v) ? "true" : "false";
851
+ });
852
+
853
+ if (shouldTrigger) trigger("change", props.value);
854
+ }
855
+
856
+ trigger.addEventListener("pointerdown", (e) => {
857
+ e.preventDefault();
858
+ e.stopPropagation();
859
+ if (menu.classList.contains("open")) closeMenu();
860
+ else openMenu();
861
+ });
862
+
863
+ document.addEventListener("pointerdown", (e) => {
864
+ if (!wrap.contains(e.target)) closeMenu();
865
+ }, true);
866
+
867
+ document.addEventListener("keydown", (e) => {
868
+ if (e.key === "Escape") closeMenu();
869
+ });
870
+
871
+ wrap.addEventListener("focusout", (e) => {
872
+ if (!wrap.contains(e.relatedTarget)) closeMenu();
873
+ });
874
+
875
+ items.forEach((btn) => {
876
+ btn.addEventListener("pointerdown", (e) => {
877
+ e.preventDefault();
878
+ e.stopPropagation();
879
+ closeMenu();
880
+ setValue(btn.dataset.value, true);
881
+ });
882
+ });
883
+
884
+ // init
885
+ setValue((props.value ?? "None"), false);
886
+
887
+ // sync from Python
888
+ let last = props.value;
889
+ const syncFromProps = () => {
890
+ if (props.value !== last) {
891
+ last = props.value;
892
+ setValue(last, false);
893
+ }
894
+ requestAnimationFrame(syncFromProps);
895
+ };
896
+ requestAnimationFrame(syncFromProps);
897
+ })();
898
+ """
899
+
900
+ # Inject mapping into JS safely
901
+ import json
902
+ js_on_load = js_on_load.replace("__VALUE_TO_LABEL__", json.dumps(value_to_label))
903
+ js_on_load = js_on_load.replace("__VALUE_TO_ICON__", json.dumps(value_to_icon))
904
+
905
+ super().__init__(
906
+ value=value,
907
+ html_template=html_template,
908
+ js_on_load=js_on_load,
909
+ **kwargs
910
+ )
911
+
912
+
913
+ ####################################################################################################
914
+ ### PART 15: Custom Component - PresetGallery
915
+ ####################################################################################################
916
+ class PresetGallery(gr.HTML):
917
+ """
918
+ Clickable image presets -> outputs selected index (int as string, then cast in python)
919
+ """
920
+ def __init__(self, items, title="Click an Example", **kwargs):
921
+ """
922
+ items: list[dict] with keys:
923
+ - thumb: str (path to image file, e.g. "supergirl.png")
924
+ - label: str (optional)
925
+ """
926
+ uid = uuid.uuid4().hex[:8]
927
+
928
+ cards_html = []
929
+ for i, it in enumerate(items):
930
+ thumb = it["thumb"]
931
+ label = it.get("label", "")
932
+ cards_html.append(f"""
933
+ <button type="button" class="pg-card" data-idx="{i}" aria-label="{label}">
934
+ <img class="pg-img" src="gradio_api/file={thumb}" alt="{label}">
935
+ </button>
936
+ """)
937
+
938
+ html_template = f"""
939
+ <div class="pg-wrap" data-pg="{uid}">
940
+ <div class="pg-title">
941
+ <div class="pg-h1">{title}</div>
942
+ </div>
943
+ <div class="pg-grid">
944
+ {''.join(cards_html)}
945
+ </div>
946
+ </div>
947
+ """
948
+
949
+ # --- JAVASCRIPT LOGIC UPDATED ---
950
+ # Removed "pointerenter" and "pointerleave" events.
951
+ # All logic is now inside "pointerdown" (click event).
952
+ js_on_load = r"""
953
+ (() => {
954
+ const wrap = element.querySelector(".pg-wrap");
955
+ const cards = Array.from(element.querySelectorAll(".pg-card"));
956
+ if (!wrap || !cards.length) return;
957
+
958
+ function setDim(activeIdx) {
959
+ cards.forEach((c, i) => {
960
+ // Dim cards that are not the active one.
961
+ c.dataset.dim = (activeIdx !== null && i !== activeIdx) ? "true" : "false";
962
+ // Set the active state for the clicked card.
963
+ c.dataset.active = (i === activeIdx) ? "true" : "false";
964
+ });
965
+ }
966
+
967
+ let lastSent = null;
968
+ let lock = false;
969
+
970
+ cards.forEach((card) => {
971
+ // REMOVED: "pointerenter" event listener. No action on hover.
972
+ // REMOVED: "pointerleave" event listener. No action on hover.
973
+
974
+ // Use pointerdown (click/tap) for all actions.
975
+ card.addEventListener("pointerdown", (e) => {
976
+ e.preventDefault();
977
+ e.stopPropagation();
978
+
979
+ if (lock) return;
980
+ lock = true;
981
+ setTimeout(() => (lock = false), 250);
982
+
983
+ const idxNumber = Number(card.dataset.idx);
984
+ const idxString = String(idxNumber);
985
+
986
+ // 1. Update visual state immediately on click.
987
+ setDim(idxNumber);
988
+
989
+ // 2. Only update Python backend if the value has actually changed.
990
+ if (idxString === lastSent) return;
991
+ lastSent = idxString;
992
+
993
+ // ✅ Set props.value to send data to Python.
994
+ props.value = idxString;
995
+ }, { passive: false });
996
+ });
997
+
998
+ // Initially, no card is selected.
999
+ setDim(null);
1000
+ })();
1001
+ """
1002
+
1003
+
1004
+ super().__init__(value="", html_template=html_template, js_on_load=js_on_load, **kwargs)
1005
+
1006
+
1007
+ ####################################################################################################
1008
+ ### PART 16: Custom Component - AudioDropUpload
1009
+ ####################################################################################################
1010
+ class AudioDropUpload(gr.HTML):
1011
+ """
1012
+ Custom audio drop/click UI that proxies file into a hidden gr.Audio component.
1013
+ IMPORTANT:
1014
+ - Pass target_audio_elem_id = elem_id of your hidden gr.Audio.
1015
+ - The hidden gr.Audio must be type="filepath" (or whatever you need).
1016
+ """
1017
+ def __init__(self, target_audio_elem_id: str, value=None, **kwargs):
1018
+ uid = uuid.uuid4().hex[:8]
1019
+
1020
+ html_template = f"""
1021
+ <div class="aud-wrap" data-aud="{uid}">
1022
+ <div class="aud-drop" role="button" tabindex="0" aria-label="بارگذاری صدا">
1023
+ <div><strong>(اختیاری) فایل صوتی را اینجا بکشید و رها کنید</strong></div>
1024
+ <div class="aud-hint">…یا برای انتخاب کلیک کنید</div>
1025
+ </div>
1026
+ <div class="aud-row" aria-live="polite">
1027
+ <audio class="aud-player" controls></audio>
1028
+ <button class="aud-remove" type="button" aria-label="حذف صدا">
1029
+ <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1030
+ <path d="M18 6L6 18M6 6l12 12"
1031
+ stroke="currentColor"
1032
+ stroke-width="2.25"
1033
+ stroke-linecap="round"/>
1034
+ </svg>
1035
+ </button>
1036
+ </div>
1037
+ <div class="aud-filelabel"></div>
1038
+ </div>
1039
+ """
1040
+
1041
+ # JS:
1042
+ # - finds the hidden gr.Audio upload <input type=file> inside the component with elem_id=target_audio_elem_id
1043
+ # - sets the selected file onto it (DataTransfer) and dispatches change
1044
+ js_on_load = """
1045
+ (() => {{
1046
+ // Helper: access Gradio shadow DOM safely
1047
+ function grRoot() {{
1048
+ const ga = document.querySelector("gradio-app");
1049
+ return (ga && ga.shadowRoot) ? ga.shadowRoot : document;
1050
+ }}
1051
+ const root = grRoot();
1052
+ const wrap = element.querySelector(".aud-wrap");
1053
+ const drop = element.querySelector(".aud-drop");
1054
+ const row = element.querySelector(".aud-row");
1055
+ const player = element.querySelector(".aud-player");
1056
+ const removeBtn = element.querySelector(".aud-remove");
1057
+ const label = element.querySelector(".aud-filelabel");
1058
+ const TARGET_ID = "__TARGET_ID__";
1059
+ let currentUrl = null;
1060
+ function findHiddenAudioFileInput() {{
1061
+ const host = root.querySelector("#" + CSS.escape(TARGET_ID));
1062
+ if (!host) return null;
1063
+ // Gradio's Audio component contains an <input type=file> for upload.
1064
+ // This selector works in most Gradio 3/4 themes.
1065
+ const inp = host.querySelector('input[type="file"]');
1066
+ return inp;
1067
+ }}
1068
+ function showDrop() {{
1069
+ drop.style.display = "";
1070
+ row.style.display = "none";
1071
+ label.style.display = "none";
1072
+ label.textContent = "";
1073
+ }}
1074
+ function showPlayer(filename) {{
1075
+ drop.style.display = "none";
1076
+ row.style.display = "flex";
1077
+ if (filename) {{
1078
+ label.textContent = "فایل بارگذاری شده: " + filename;
1079
+ label.style.display = "block";
1080
+ }}
1081
+ }}
1082
+ function clearPreview() {{
1083
+ player.pause();
1084
+ player.removeAttribute("src");
1085
+ player.load();
1086
+ if (currentUrl) {{
1087
+ URL.revokeObjectURL(currentUrl);
1088
+ currentUrl = null;
1089
+ }}
1090
+ }}
1091
+ function clearHiddenGradioAudio() {{
1092
+ const fileInput = findHiddenAudioFileInput();
1093
+ if (!fileInput) return;
1094
+ // Clear file input (works by replacing its files with empty DataTransfer)
1095
+ fileInput.value = "";
1096
+ const dt = new DataTransfer();
1097
+ fileInput.files = dt.files;
1098
+ fileInput.dispatchEvent(new Event("input", {{ bubbles: true }}));
1099
+ fileInput.dispatchEvent(new Event("change", {{ bubbles: true }}));
1100
+ }}
1101
+ function clearAll() {
1102
+ clearPreview();
1103
+
1104
+ // Attempt DOM clear (still useful)
1105
+ clearHiddenGradioAudio();
1106
+
1107
+ // Tell Gradio/Python explicitly to clear backend state
1108
+ props.value = "__CLEAR__";
1109
+ trigger("change", props.value);
1110
+
1111
+ showDrop();
1112
+ }
1113
+
1114
+ function loadFileToPreview(file) {{
1115
+ if (!file) return;
1116
+ if (!file.type || !file.type.startsWith("audio/")) {{
1117
+ alert("لطفا یک فایل صوتی انتخاب کنید.");
1118
+ return;
1119
+ }}
1120
+ clearPreview();
1121
+ currentUrl = URL.createObjectURL(file);
1122
+ player.src = currentUrl;
1123
+ showPlayer(file.name);
1124
+
1125
+ }}
1126
+ function pushFileIntoHiddenGradioAudio(file) {
1127
+ const fileInput = findHiddenAudioFileInput();
1128
+ if (!fileInput) {
1129
+ console.warn("Could not find hidden gr.File input. Check elem_id:", TARGET_ID);
1130
+ return;
1131
+ }
1132
+
1133
+ // Hard reset (important for re-selecting same file)
1134
+ fileInput.value = "";
1135
+
1136
+ const dt = new DataTransfer();
1137
+ dt.items.add(file);
1138
+ fileInput.files = dt.files;
1139
+
1140
+ // Trigger Gradio listeners
1141
+ fileInput.dispatchEvent(new Event("input", {{ bubbles: true }}));
1142
+ fileInput.dispatchEvent(new Event("change", {{ bubbles: true }}));
1143
+ }
1144
+
1145
+ function handleFile(file) {{
1146
+ loadFileToPreview(file);
1147
+ pushFileIntoHiddenGradioAudio(file);
1148
+ }}
1149
+ // Click-to-browse uses a *local* ephemeral input (not Gradio’s),
1150
+ // then we forward to hidden gr.Audio.
1151
+ const localPicker = document.createElement("input");
1152
+ localPicker.type = "file";
1153
+ localPicker.accept = "audio/*";
1154
+ localPicker.style.display = "none";
1155
+ wrap.appendChild(localPicker);
1156
+ localPicker.addEventListener("change", () => {{
1157
+ const f = localPicker.files && localPicker.files[0];
1158
+ if (f) handleFile(f);
1159
+ localPicker.value = "";
1160
+ }});
1161
+ drop.addEventListener("click", () => localPicker.click());
1162
+ drop.addEventListener("keydown", (e) => {{
1163
+ if (e.key === "Enter" || e.key === " ") {{
1164
+ e.preventDefault();
1165
+ localPicker.click();
1166
+ }}
1167
+ }});
1168
+ removeBtn.addEventListener("click", clearAll);
1169
+ // Drag & drop
1170
+ ["dragenter","dragover","dragleave","drop"].forEach(evt => {{
1171
+ drop.addEventListener(evt, (e) => {{
1172
+ e.preventDefault();
1173
+ e.stopPropagation();
1174
+ }});
1175
+ }});
1176
+ drop.addEventListener("dragover", () => drop.classList.add("dragover"));
1177
+ drop.addEventListener("dragleave", () => drop.classList.remove("dragover"));
1178
+ drop.addEventListener("drop", (e) => {{
1179
+ drop.classList.remove("dragover");
1180
+ const f = e.dataTransfer.files && e.dataTransfer.files[0];
1181
+ if (f) handleFile(f);
1182
+ }});
1183
+ // init
1184
+ showDrop();
1185
+
1186
+ function setPreviewFromPath(path) {
1187
+ if (path === "__CLEAR__") path = null;
1188
+
1189
+ if (!path) {
1190
+ clearPreview();
1191
+ showDrop();
1192
+ return;
1193
+ }
1194
+
1195
+ // If path already looks like a URL, use it directly
1196
+ // otherwise serve it through Gradio's file route.
1197
+ let url = path;
1198
+ if (!/^https?:\/\//.test(path) && !path.startsWith("gradio_api/file=") && !path.startsWith("/file=")) {
1199
+ url = "gradio_api/file=" + path;
1200
+ }
1201
+
1202
+ clearPreview();
1203
+ player.src = url;
1204
+ showPlayer(path.split("/").pop());
1205
+ }
1206
+
1207
+ // ---- sync from Python (Examples / backend updates) ----
1208
+ let last = props.value;
1209
+ const syncFromProps = () => {
1210
+ const v = props.value;
1211
+
1212
+ if (v !== last) {
1213
+ last = v;
1214
+ if (!v || v === "__CLEAR__") setPreviewFromPath(null);
1215
+ else setPreviewFromPath(String(v));
1216
+ }
1217
+ requestAnimationFrame(syncFromProps);
1218
+ };
1219
+ requestAnimationFrame(syncFromProps);
1220
+
1221
+
1222
+ }})();
1223
+ """
1224
+ js_on_load = js_on_load.replace("__TARGET_ID__", target_audio_elem_id)
1225
+
1226
+ super().__init__(
1227
+ value=value,
1228
+ html_template=html_template,
1229
+ js_on_load=js_on_load,
1230
+ **kwargs
1231
+ )
1232
+
1233
+
1234
  ####################################################################################################
1235
  ### PART 17: Wrapper Functions (Resolution, Duration, Examples)
1236
  ####################################################################################################
 
1321
  """
1322
  Generate a short cinematic video from a text prompt and optional input image using the LTX-2 distilled pipeline.
1323
  """
 
 
 
 
1324
 
1325
+ # Removed the 15s warning check since 15s option is removed from UI
1326
 
1327
+ if audio_path is None:
1328
+ print(f'generating with duration:{duration} and LoRA:{camera_lora} in {width}x{height}')
1329
+ else:
1330
+ print(f'generating with duration:{duration} and audio in {width}x{height}')
1331
+
1332
+ # Randomize seed if checkbox is enabled
1333
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
1334
+
1335
+ # Calculate num_frames from duration (using fixed 24 fps)
1336
+ frame_rate = 24.0
1337
+ num_frames = int(duration * frame_rate) + 1 # +1 to ensure we meet the duration
1338
+ video_seconds = int(duration)
1339
 
1340
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
1341
+ output_path = tmpfile.name
1342
 
 
 
 
 
1343
 
1344
+ images = []
1345
+ videos = []
1346
 
1347
+ # Removed Motion Control block
1348
 
1349
+ if first_frame is not None:
1350
  images = []
1351
+ images.append((first_frame, 0, 1.0))
1352
+
1353
+ # Updated logic for Persian string
1354
+ if generation_mode == "تکمیل فریم‌های میانی":
1355
+ if end_frame is not None:
1356
+ end_idx = max(0, num_frames - 1)
1357
+ images.append((end_frame, end_idx, 0.5))
1358
+
1359
+ embeddings, final_prompt, status = encode_prompt(
1360
+ prompt=prompt,
1361
+ enhance_prompt=enhance_prompt,
1362
+ input_image=first_frame,
1363
+ seed=current_seed,
1364
+ negative_prompt="",
1365
+ )
1366
+
1367
+ video_context = embeddings["video_context"].to("cuda", non_blocking=True)
1368
+ audio_context = embeddings["audio_context"].to("cuda", non_blocking=True)
1369
+ print("✓ Embeddings loaded successfully")
 
 
 
 
 
 
1370
 
1371
 
1372
+ # free prompt enhancer / encoder temps ASAP
1373
+ del embeddings, final_prompt, status
1374
+ torch.cuda.empty_cache()
1375
 
1376
+ # ✅ if user provided audio, use a neutral audio_context
1377
+ n_audio_context = None
1378
+
1379
+ if audio_path is not None:
1380
+ with torch.inference_mode():
1381
+ _, n_audio_context = encode_text_simple(text_encoder, "") # returns tensors on GPU already
1382
+ del audio_context
1383
+ audio_context = n_audio_context
1384
 
1385
+ if len(videos) == 0:
1386
+ camera_lora = "Static"
 
 
 
1387
 
1388
+ torch.cuda.empty_cache()
 
1389
 
1390
+ # Map dropdown name -> adapter index
1391
+ name_to_idx = {name: idx for name, idx in RUNTIME_LORA_CHOICES}
1392
+ selected_idx = name_to_idx.get(camera_lora, -1)
1393
 
1394
+ enable_only_lora(pipeline._transformer, selected_idx)
1395
+ torch.cuda.empty_cache()
 
1396
 
1397
+ # True video duration in seconds based on your rounding
1398
+ video_seconds = (num_frames - 1) / frame_rate
1399
 
1400
+ if audio_path is not None:
1401
+ input_waveform, input_waveform_sample_rate = match_audio_to_duration(
1402
+ audio_path=audio_path,
1403
+ target_seconds=video_seconds,
1404
+ target_sr=48000, # pick what your model expects; 48k is common for AV models
1405
+ to_mono=True, # set False if your model wants stereo
1406
+ pad_mode="silence", # or "repeat" if you prefer looping over silence
1407
+ device="cuda",
1408
+ )
1409
+ else:
1410
+ input_waveform = None
1411
+ input_waveform_sample_rate = None
1412
 
1413
+ with timer(f'generating with LoRA:{camera_lora} in {width}x{height}'):
1414
+ with torch.inference_mode():
1415
+ pipeline(
1416
+ prompt=prompt,
1417
+ output_path=str(output_path),
1418
+ seed=current_seed,
1419
+ height=height,
1420
+ width=width,
1421
+ num_frames=num_frames,
1422
+ frame_rate=frame_rate,
1423
+ images=images,
1424
+ video_conditioning=videos,
1425
+ tiling_config=TilingConfig.default(),
1426
+ video_context=video_context,
1427
+ audio_context=audio_context,
1428
+ input_waveform=input_waveform,
1429
+ input_waveform_sample_rate=input_waveform_sample_rate,
1430
  )
1431
+ del video_context, audio_context
1432
+ torch.cuda.empty_cache()
1433
+ print("successful generation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1434
 
1435
+ return str(output_path)
 
 
 
 
 
 
 
1436
 
1437
 
1438
  def apply_resolution(resolution: str):
 
1447
  return int(w), int(h)
1448
 
1449
  def apply_duration(duration: str):
1450
+ duration_s = int(duration[:-1])
 
 
 
 
1451
  return duration_s
1452
 
1453
  def on_mode_change(selected: str):
 
1462
  ### PART 19: CSS Styles
1463
  ####################################################################################################
1464
  css = """
1465
+
1466
+ /* Make the row behave nicely */
1467
+ #controls-row {
1468
+ display: none !important;
1469
+ align-items: center;
1470
+ gap: 12px;
1471
+ flex-wrap: nowrap; /* or wrap if you prefer on small screens */
1472
+ }
1473
+
1474
+ /* Stop these components from stretching */
1475
+ #controls-row > * {
1476
+ flex: 0 0 auto !important;
1477
+ width: auto !important;
1478
+ min-width: 0 !important;
1479
+ }
1480
+
1481
+
1482
  #col-container {
1483
  margin: 0 auto;
1484
  max-width: 1600px;
1485
  }
1486
+ #modal-container {
1487
+ width: 100vw; /* Take full viewport width */
1488
+ height: 100vh; /* Take full viewport height (optional) */
1489
+ display: flex;
1490
+ justify-content: center; /* Center content horizontally */
1491
+ align-items: center; /* Center content vertically if desired */
1492
+ }
1493
+ #modal-content {
1494
+ width: 100%;
1495
+ max-width: 700px; /* Limit content width */
1496
+ margin: 0 auto;
1497
+ border-radius: 8px;
1498
+ padding: 1.5rem;
1499
+ }
1500
+ #step-column {
1501
+ padding: 10px;
1502
+ border-radius: 8px;
1503
+ box-shadow: var(--card-shadow);
1504
+ margin: 10px;
1505
+ }
1506
+ #col-showcase {
1507
+ margin: 0 auto;
1508
+ max-width: 1100px;
1509
+ }
1510
  .button-gradient {
1511
  background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
1512
  border: none;
 
1520
  animation: 2s linear 0s infinite normal none running gradientAnimation;
1521
  box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
1522
  }
1523
+ .toggle-container {
1524
+ display: inline-flex;
1525
+ background-color: #ffd6ff; /* light pink background */
1526
+ border-radius: 9999px;
1527
+ padding: 4px;
1528
+ position: relative;
1529
+ width: fit-content;
1530
+ font-family: sans-serif;
1531
+ }
1532
+ .toggle-container input[type="radio"] {
1533
+ display: none;
1534
+ }
1535
+ .toggle-container label {
1536
+ position: relative;
1537
+ z-index: 2;
1538
+ flex: 1;
1539
+ text-align: center;
1540
+ font-weight: 700;
1541
+ color: #4b2ab5; /* dark purple text for unselected */
1542
+ padding: 6px 22px;
1543
+ border-radius: 9999px;
1544
+ cursor: pointer;
1545
+ transition: color 0.25s ease;
1546
+ }
1547
+ /* Moving highlight */
1548
+ .toggle-highlight {
1549
+ position: absolute;
1550
+ top: 4px;
1551
+ left: 4px;
1552
+ width: calc(50% - 4px);
1553
+ height: calc(100% - 8px);
1554
+ background-color: #4b2ab5; /* dark purple background */
1555
+ border-radius: 9999px;
1556
+ transition: transform 0.25s ease;
1557
+ z-index: 1;
1558
+ }
1559
+ /* When "True" is checked */
1560
+ #true:checked ~ label[for="true"] {
1561
+ color: #ffd6ff; /* light pink text */
1562
+ }
1563
+ /* When "False" is checked */
1564
+ #false:checked ~ label[for="false"] {
1565
+ color: #ffd6ff; /* light pink text */
1566
+ }
1567
+ /* Move highlight to right side when False is checked */
1568
+ #false:checked ~ .toggle-highlight {
1569
+ transform: translateX(100%);
1570
+ }
1571
+
1572
+ /* Center items inside that row */
1573
+ #mode-row{
1574
+ justify-content: center !important;
1575
+ align-items: center !important;
1576
+ }
1577
+
1578
+ /* Center the mode row contents */
1579
+ #mode-row {
1580
+ display: flex !important;
1581
+ justify-content: center !important;
1582
+ align-items: center !important;
1583
+ width: 100% !important;
1584
+ }
1585
+
1586
+ /* Stop Gradio from making children stretch */
1587
+ #mode-row > * {
1588
+ flex: 0 0 auto !important;
1589
+ width: auto !important;
1590
+ min-width: 0 !important;
1591
+ }
1592
+
1593
+ /* Specifically ensure the HTML component wrapper doesn't take full width */
1594
+ #mode-row .gr-html,
1595
+ #mode-row .gradio-html,
1596
+ #mode-row .prose,
1597
+ #mode-row .block {
1598
+ width: auto !important;
1599
+ flex: 0 0 auto !important;
1600
+ display: inline-block !important;
1601
+ }
1602
+
1603
+ /* Center the pill itself */
1604
+ #radioanimated_mode {
1605
+ display: inline-flex !important;
1606
+ justify-content: center !important;
1607
+ width: auto !important;
1608
+ }
1609
+
1610
+ """
1611
+
1612
+ css += """
1613
+ .cd-trigger-icon{
1614
+ color: rgba(255,255,255,0.9);
1615
+ display: inline-flex;
1616
+ align-items: center;
1617
+ justify-content: center;
1618
+ width: 18px;
1619
+ height: 18px;
1620
+ }
1621
+ .cd-trigger-icon svg {
1622
+ width: 18px;
1623
+ height: 18px;
1624
+ display: block;
1625
+ }
1626
+ """
1627
+
1628
+
1629
+ css += """
1630
+ /* ---- radioanimated ---- */
1631
+ .ra-wrap{
1632
+ width: fit-content;
1633
+ }
1634
+ .ra-inner{
1635
+ position: relative;
1636
+ display: inline-flex;
1637
+ align-items: center;
1638
+ gap: 0;
1639
+ padding: 6px;
1640
+ background: #0b0b0b;
1641
+ border-radius: 9999px;
1642
+ overflow: hidden;
1643
+ user-select: none;
1644
+ }
1645
+ .ra-input{
1646
+ display: none;
1647
+ }
1648
+ .ra-label{
1649
+ position: relative;
1650
+ z-index: 2;
1651
+ padding: 10px 18px;
1652
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1653
+ font-size: 14px;
1654
+ font-weight: 600;
1655
+ color: rgba(255,255,255,0.7);
1656
+ cursor: pointer;
1657
+ transition: color 180ms ease;
1658
+ white-space: nowrap;
1659
+ }
1660
+ .ra-highlight{
1661
+ position: absolute;
1662
+ z-index: 1;
1663
+ top: 6px;
1664
+ left: 6px;
1665
+ height: calc(100% - 12px);
1666
+ border-radius: 9999px;
1667
+ background: #8bff97; /* green knob */
1668
+ transition: transform 200ms ease, width 200ms ease;
1669
+ }
1670
+ /* selected label becomes darker like your screenshot */
1671
+ .ra-input:checked + .ra-label{
1672
+ color: rgba(0,0,0,0.75);
1673
+ }
1674
+ """
1675
+
1676
+ css += """
1677
+ .cd-icn svg{
1678
+ width: 18px;
1679
+ height: 18px;
1680
+ display: block;
1681
+ }
1682
+ .cd-icn svg *{
1683
+ stroke: rgba(255,255,255,0.9);
1684
+ }
1685
+ """
1686
+
1687
+
1688
+ css += """
1689
+ /* --- prompt box --- */
1690
+ .ds-prompt{
1691
+ width: 100%;
1692
+ max-width: 720px;
1693
+ margin-top: 3px;
1694
+ }
1695
+
1696
+ .ds-textarea{
1697
+ width: 100%;
1698
+ box-sizing: border-box;
1699
+ background: #2b2b2b;
1700
+ color: rgba(255,255,255,0.9);
1701
+ border: 1px solid rgba(255,255,255,0.12);
1702
+ border-radius: 14px;
1703
+ padding: 14px 16px;
1704
+ outline: none;
1705
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1706
+ font-size: 15px;
1707
+ line-height: 1.35;
1708
+ resize: none;
1709
+ min-height: 210px;
1710
+ max-height: 210px;
1711
+ overflow-y: auto;
1712
+
1713
+ /* IMPORTANT: space for the footer controls */
1714
+ padding-bottom: 72px;
1715
+ }
1716
+
1717
+
1718
+ .ds-card{
1719
+ width: 100%;
1720
+ max-width: 720px;
1721
+ margin: 0 auto;
1722
+ }
1723
+ .ds-top{
1724
+ position: relative;
1725
+ }
1726
+
1727
+ /* Make room for footer inside textarea */
1728
+ .ds-textarea{
1729
+ padding-bottom: 72px;
1730
+ }
1731
+
1732
+ /* Footer positioning */
1733
+ .ds-footer{
1734
+ position: absolute;
1735
+ right: 12px;
1736
+ bottom: 10px;
1737
+ display: flex;
1738
+ gap: 8px;
1739
+ align-items: center;
1740
+ justify-content: flex-end;
1741
+ z-index: 3;
1742
+ }
1743
+
1744
+ /* Smaller pill buttons inside footer */
1745
+ .ds-footer .cd-trigger{
1746
+ min-height: 32px;
1747
+ padding: 6px 10px;
1748
+ font-size: 12px;
1749
+ gap: 6px;
1750
+ border-radius: 9999px;
1751
+ }
1752
+ .ds-footer .cd-trigger-icon,
1753
+ .ds-footer .cd-icn{
1754
+ width: 14px;
1755
+ height: 14px;
1756
+ }
1757
+ .ds-footer .cd-trigger-icon svg,
1758
+ .ds-footer .cd-icn svg{
1759
+ width: 14px;
1760
+ height: 14px;
1761
+ }
1762
+ .ds-footer .cd-caret{
1763
+ font-size: 11px;
1764
+ }
1765
+
1766
+ /* Bottom safe area bar (optional but looks nicer) */
1767
+ .ds-top::after{
1768
+ content: "";
1769
+ position: absolute;
1770
+ left: 1px;
1771
+ right: 1px;
1772
+ bottom: 1px;
1773
+ height: 56px;
1774
+ background: #2b2b2b;
1775
+ border-bottom-left-radius: 13px;
1776
+ border-bottom-right-radius: 13px;
1777
+ pointer-events: none;
1778
+ z-index: 2;
1779
+ }
1780
+
1781
+ """
1782
+
1783
+ css += """
1784
+ /* ---- camera dropdown ---- */
1785
+
1786
+ /* 1) Fix overlap: make the Gradio HTML block shrink-to-fit when it contains a CameraDropdown.
1787
+ Gradio uses .gr-html for HTML components in most versions; older themes sometimes use .gradio-html.
1788
+ This keeps your big header HTML unaffected because it doesn't contain .cd-wrap.
1789
+ */
1790
+
1791
+ /* 2) Actual dropdown layout */
1792
+ .cd-wrap{
1793
+ position: relative;
1794
+ display: inline-block;
1795
  }
1796
+
1797
+ /* 3) Match RadioAnimated pill size/feel */
1798
+ .cd-trigger{
1799
+ margin-top: 2px;
1800
+ display: inline-flex;
1801
+ align-items: center;
1802
+ justify-content: center;
1803
+ gap: 10px;
1804
+
1805
+ border: none;
1806
+
1807
+ box-sizing: border-box;
1808
+ padding: 10px 18px;
1809
+ min-height: 52px;
1810
+ line-height: 1.2;
1811
+
1812
+ border-radius: 9999px;
1813
+ background: #0b0b0b;
1814
+
1815
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1816
+ font-size: 14px;
1817
+
1818
+ /* ✅ match .ra-label exactly */
1819
+ color: rgba(255,255,255,0.7) !important;
1820
+ font-weight: 600 !important;
1821
+
1822
+ cursor: pointer;
1823
+ user-select: none;
1824
+ white-space: nowrap;
1825
+ }
1826
+
1827
+ /* Ensure inner spans match too */
1828
+ .cd-trigger .cd-trigger-text,
1829
+ .cd-trigger .cd-caret{
1830
+ color: rgba(255,255,255,0.7) !important;
1831
+ }
1832
+
1833
+ /* keep caret styling */
1834
+ .cd-caret{
1835
+ opacity: 0.8;
1836
+ font-weight: 900;
1837
+ }
1838
+
1839
+ /* 4) Ensure menu overlays neighbors and isn't clipped */
1840
+ /* Move dropdown a tiny bit up (closer to the trigger) */
1841
+ .cd-menu{
1842
+ position: absolute;
1843
+ top: calc(100% + 4px); /* was +10px */
1844
+ left: 0;
1845
 
1846
+ min-width: 240px;
1847
+ background: #2b2b2b;
1848
+ border: 1px solid rgba(255,255,255,0.14);
1849
+ border-radius: 14px;
1850
+ box-shadow: 0 18px 40px rgba(0,0,0,0.35);
1851
+ padding: 10px;
1852
+
1853
+ opacity: 0;
1854
+ transform: translateY(-6px);
1855
+ pointer-events: none;
1856
+ transition: opacity 160ms ease, transform 160ms ease;
1857
+
1858
+ z-index: 9999;
1859
+ }
1860
+
1861
+ .cd-title{
1862
+ font-size: 12px;
1863
+ font-weight: 600;
1864
+ text-transform: uppercase;
1865
+ letter-spacing: 0.04em;
1866
+
1867
+ color: rgba(255,255,255,0.45); /* 👈 muted grey */
1868
+ margin-bottom: 6px;
1869
+ padding: 0 6px;
1870
+ pointer-events: none; /* title is non-interactive */
1871
+ }
1872
 
1873
+
1874
+ .cd-menu.open{
1875
+ opacity: 1;
1876
+ transform: translateY(0);
1877
+ pointer-events: auto;
1878
+ }
1879
+
1880
+ .cd-items{
1881
+ display: flex;
1882
+ flex-direction: column;
1883
+ gap: 0px; /* tighter, more like a native menu */
1884
+ }
1885
+
1886
+ /* Items: NO "boxed" buttons by default */
1887
+ .cd-item{
1888
+ width: 100%;
1889
+ text-align: left;
1890
+ border: none;
1891
+ background: transparent; /* ✅ removes box look */
1892
+ color: rgba(255,255,255,0.92);
1893
+ padding: 8px 34px 8px 12px; /* right padding leaves room for tick */
1894
+ border-radius: 10px; /* only matters on hover */
1895
+ cursor: pointer;
1896
+
1897
+ font-size: 14px;
1898
+ font-weight: 700;
1899
+
1900
+ position: relative;
1901
+ transition: background 120ms ease;
1902
+ }
1903
+
1904
+ /* “Box effect” only on hover (not always) */
1905
+ .cd-item:hover{
1906
+ background: rgba(255,255,255,0.08);
1907
+ }
1908
+
1909
+ /* Tick on the right ONLY on hover */
1910
+ .cd-item::after{
1911
+ content: "✓";
1912
+ position: absolute;
1913
+ right: 12px;
1914
+ top: 50%;
1915
+ transform: translateY(-50%);
1916
+ opacity: 0; /* hidden by default */
1917
+ transition: opacity 120ms ease;
1918
+ color: rgba(255,255,255,0.9);
1919
+ font-weight: 900;
1920
+ }
1921
+
1922
+ /* show tick ONLY for selected item */
1923
+ .cd-item[data-selected="true"]::after{
1924
+ opacity: 1;
1925
+ }
1926
+
1927
+ /* keep hover box effect, but no tick change */
1928
+ .cd-item:hover{
1929
+ background: rgba(255,255,255,0.08);
1930
+ }
1931
+
1932
+
1933
+ /* Kill any old “selected” styling just in case */
1934
+ .cd-item.selected{
1935
+ background: transparent !important;
1936
+ border: none !important;
1937
+ }
1938
+
1939
+
1940
+ """
1941
+
1942
+ css += """
1943
+ /* icons in dropdown items */
1944
+ .cd-item{
1945
+ display: flex;
1946
+ align-items: center;
1947
+ gap: 10px;
1948
+ }
1949
+ .cd-icn{
1950
+ display: inline-flex;
1951
+ align-items: center;
1952
+ justify-content: center;
1953
+ width: 18px;
1954
+ height: 18px;
1955
+ flex: 0 0 18px;
1956
+ }
1957
+ .cd-label{
1958
+ flex: 1;
1959
+ }
1960
+
1961
+ /* =========================
1962
+ FIX: prompt border + scrollbar bleed
1963
+ ========================= */
1964
+
1965
+ /* Put the border + background on the wrapper, not the textarea */
1966
+ .ds-top{
1967
+ position: relative;
1968
+ background: #2b2b2b;
1969
+ border: 1px solid rgba(255,255,255,0.12);
1970
+ border-radius: 14px;
1971
+ overflow: hidden; /* ensures the footer bar is clipped to rounded corners */
1972
+ }
1973
+
1974
+ /* Make textarea "transparent" so wrapper owns the border/background */
1975
+ .ds-textarea{
1976
+ background: transparent !important;
1977
+ border: none !important;
1978
+ border-radius: 0 !important; /* wrapper handles radius */
1979
+ outline: none;
1980
+
1981
+ /* keep your spacing */
1982
+ padding: 14px 16px;
1983
+ padding-bottom: 72px; /* room for footer */
1984
+ width: 100%;
1985
+ box-sizing: border-box;
1986
+
1987
+ /* keep scroll behavior */
1988
+ overflow-y: auto;
1989
+
1990
+ /* prevent scrollbar bleed by hiding native scrollbar */
1991
+ scrollbar-width: none; /* Firefox */
1992
+ }
1993
+ .ds-textarea::-webkit-scrollbar{ /* Chrome/Safari */
1994
+ width: 0;
1995
+ height: 0;
1996
+ }
1997
+
1998
+ /* Safe-area bar: now it matches perfectly because it's inside the same bordered wrapper */
1999
+ .ds-top::after{
2000
+ content: "";
2001
+ position: absolute;
2002
+ left: 0;
2003
+ right: 0;
2004
+ bottom: 0;
2005
+ height: 56px;
2006
+ background: #2b2b2b;
2007
+ pointer-events: none;
2008
+ z-index: 2;
2009
+ }
2010
+
2011
+ /* Footer above the bar */
2012
+ .ds-footer{
2013
+ position: absolute;
2014
+ right: 12px;
2015
+ bottom: 10px;
2016
+ display: flex;
2017
+ gap: 8px;
2018
+ align-items: center;
2019
+ justify-content: flex-end;
2020
+ z-index: 3;
2021
+ }
2022
+
2023
+ /* Ensure textarea content sits below overlays */
2024
+ .ds-textarea{
2025
+ position: relative;
2026
+ z-index: 1;
2027
+ }
2028
+
2029
+ /* ===== FIX dropdown menu being clipped/behind ===== */
2030
+
2031
+ /* Let the dropdown menu escape the prompt wrapper */
2032
+ .ds-top{
2033
+ overflow: visible !important; /* IMPORTANT: do not clip the menu */
2034
+ }
2035
+
2036
+ /* Keep the rounded "safe area" look without clipping the menu */
2037
+ .ds-top::after{
2038
+ left: 0 !important;
2039
+ right: 0 !important;
2040
+ bottom: 0 !important;
2041
+ border-bottom-left-radius: 14px !important;
2042
+ border-bottom-right-radius: 14px !important;
2043
+ }
2044
+
2045
+ /* Ensure the footer stays above the safe-area bar */
2046
+ .ds-footer{
2047
+ z-index: 20 !important;
2048
+ }
2049
+
2050
+ /* Make sure the opened menu is above EVERYTHING */
2051
+ .ds-footer .cd-menu{
2052
+ z-index: 999999 !important;
2053
+ }
2054
+
2055
+ /* Sometimes Gradio/columns/cards create stacking contexts;
2056
+ force the whole prompt card above nearby panels */
2057
+ .ds-card{
2058
+ position: relative;
2059
+ z-index: 50;
2060
+ }
2061
+
2062
+ /* --- Fix focus highlight shape (make it match rounded container) --- */
2063
+
2064
+ /* Kill any theme focus ring on the textarea itself */
2065
+ .ds-textarea:focus,
2066
+ .ds-textarea:focus-visible{
2067
+ outline: none !important;
2068
+ box-shadow: none !important;
2069
+ }
2070
+
2071
+ /* Optional: if some themes apply it even when not focused */
2072
+ .ds-textarea{
2073
+ outline: none !important;
2074
+ }
2075
+
2076
+ /* Apply the focus ring to the rounded wrapper instead */
2077
+ .ds-top:focus-within{
2078
+ border-color: rgba(255,255,255,0.22) !important;
2079
+ box-shadow: 0 0 0 3px rgba(255,255,255,0.06) !important;
2080
+ border-radius: 14px !important;
2081
+ }
2082
+
2083
+ /* If you see any tiny square corners, ensure the wrapper clips its own shadow properly */
2084
+ .ds-top{
2085
+ border-radius: 14px !important;
2086
+ }
2087
+
2088
+ /* =========================
2089
+ CameraDropdown: force readable menu text in BOTH themes
2090
+ ========================= */
2091
+
2092
+ /* Menu surface */
2093
+ .cd-menu{
2094
+ background: #2b2b2b !important;
2095
+ border: 1px solid rgba(255,255,255,0.14) !important;
2096
+ }
2097
+
2098
+ /* Title */
2099
+ .cd-title{
2100
+ color: rgba(255,255,255,0.55) !important;
2101
+ }
2102
+
2103
+ /* Items + all descendants (fixes spans / inherited theme colors) */
2104
+ .cd-item,
2105
+ .cd-item *{
2106
+ color: rgba(255,255,255,0.92) !important;
2107
+ }
2108
+
2109
+ /* Hover state */
2110
+ .cd-item:hover{
2111
+ background: rgba(255,255,255,0.10) !important;
2112
+ }
2113
+
2114
+ /* Checkmark */
2115
+ .cd-item::after{
2116
+ color: rgba(255,255,255,0.92) !important;
2117
+ }
2118
+
2119
+ /* (Optional) make sure the trigger stays readable too */
2120
+ .cd-trigger,
2121
+ .cd-trigger *{
2122
+ color: rgba(255,255,255,0.75) !important;
2123
+ }
2124
+
2125
+ /* ---- preset gallery ---- */
2126
+ .pg-wrap{
2127
+ width: 100%;
2128
+ max-width: 1100px;
2129
+ margin: 18px auto 0 auto;
2130
+ }
2131
+ .pg-title{
2132
+ text-align: center;
2133
+ margin-bottom: 14px;
2134
+ }
2135
+ .pg-h1{
2136
+ font-size: 34px;
2137
+ font-weight: 800;
2138
+ line-height: 1.1;
2139
+
2140
+ /* ✅ theme-aware */
2141
+ color: var(--body-text-color);
2142
+ }
2143
+ .pg-h2{
2144
+ font-size: 14px;
2145
+ font-weight: 600;
2146
+ color: var(--body-text-color-subdued);
2147
+ margin-top: 6px;
2148
+ }
2149
+
2150
+ .pg-grid{
2151
+ display: grid;
2152
+ grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 per row */
2153
+ gap: 18px;
2154
+ }
2155
+
2156
+ .pg-card{
2157
+ border: none;
2158
+ background: transparent;
2159
+ padding: 0;
2160
+ cursor: pointer;
2161
+ border-radius: 12px;
2162
+ overflow: hidden;
2163
+ position: relative;
2164
+ transform: translateZ(0);
2165
+ }
2166
+
2167
+ .pg-img{
2168
+ width: 100%;
2169
+ height: 220px; /* adjust to match your look */
2170
+ object-fit: cover;
2171
+ display: block;
2172
+ border-radius: 12px;
2173
+ transition: transform 160ms ease, filter 160ms ease, opacity 160ms ease;
2174
+ }
2175
+
2176
+ /* hover: slight zoom on hovered card */
2177
+ .pg-card:hover .pg-img{
2178
+ transform: scale(1.02);
2179
+ }
2180
+
2181
+ /* dim others while hovering */
2182
+ .pg-card[data-dim="true"] .pg-img{
2183
+ opacity: 0.35;
2184
+ filter: saturate(0.9);
2185
+ }
2186
+
2187
+ /* keep hovered/active crisp */
2188
+ .pg-card[data-active="true"] .pg-img{
2189
+ opacity: 1.0;
2190
+ filter: none;
2191
+ }
2192
+
2193
+
2194
+ """
2195
+
2196
+
2197
+ css += """
2198
+ /* ---- AudioDropUpload ---- */
2199
+ .aud-wrap{
2200
+ width: 100%;
2201
+ max-width: 720px;
2202
+ }
2203
+ .aud-drop{
2204
+ border: 2px dashed var(--body-text-color-subdued);
2205
+ border-radius: 16px;
2206
+ padding: 18px;
2207
+ text-align: center;
2208
+ cursor: pointer;
2209
+ user-select: none;
2210
+ color: var(--body-text-color);
2211
+ background: var(--block-background-fill);
2212
+ }
2213
+ .aud-drop.dragover{
2214
+ border-color: rgba(255,255,255,0.35);
2215
+ background: rgba(255,255,255,0.06);
2216
+ }
2217
+ .aud-hint{
2218
+ color: var(--body-text-color-subdued);
2219
+ font-size: 0.95rem;
2220
+ margin-top: 6px;
2221
+ }
2222
+ /* pill row like your other controls */
2223
+ .aud-row{
2224
+ display: none;
2225
+ align-items: center;
2226
+ gap: 10px;
2227
+ background: #0b0b0b;
2228
+ border-radius: 9999px;
2229
+ padding: 8px 10px;
2230
+ }
2231
+ .aud-player{
2232
+ flex: 1;
2233
+ width: 100%;
2234
+ height: 34px;
2235
+ border-radius: 9999px;
2236
+ }
2237
+ .aud-remove{
2238
+ appearance: none;
2239
+ border: none;
2240
+ background: transparent;
2241
+ color: rgba(255,255,255);
2242
+ cursor: pointer;
2243
+ width: 36px;
2244
+ height: 36px;
2245
+ border-radius: 9999px;
2246
+ display: inline-flex;
2247
+ align-items: center;
2248
+ justify-content: center;
2249
+ padding: 0;
2250
+ transition: background 120ms ease, color 120ms ease, opacity 120ms ease;
2251
+ opacity: 0.9;
2252
+ flex: 0 0 auto;
2253
+ }
2254
+ .aud-remove:hover{
2255
+ background: rgba(255,255,255,0.08);
2256
+ color: rgb(255,255,255);
2257
+ opacity: 1;
2258
+ }
2259
+ .aud-filelabel{
2260
+ margin: 10px 6px 0;
2261
+ color: var(--body-text-color-subdued);
2262
+ font-size: 0.95rem;
2263
+ display: none;
2264
+ }
2265
+ #audio_input_hidden { display: none !important; }
2266
  """
2267
 
2268
+ # Hiding Gradio Footer, Branding and Settings
2269
  css += """
2270
+ footer {
2271
+ display: none !important;
2272
+ }
2273
+ .gradio-container footer {
2274
+ display: none !important;
2275
+ }
2276
+ div.footer {
2277
+ display: none !important;
2278
+ }
2279
+ .flagging {
2280
+ display: none !important;
2281
+ }
2282
+ /* Hide the 'Use via API' link if visible */
2283
+ .api-logo, .built-with {
2284
+ display: none !important;
2285
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2286
  """
2287
 
2288
+
2289
  def apply_example(idx: str):
2290
+ idx = int(idx)
2291
+
2292
+ # Read the example row from your list
2293
+ img, prompt_txt, cam, res, mode, vid, aud, end_img = examples_list[idx]
2294
+
2295
+ img_path = img if img else None
2296
+ vid_path = vid if vid else None
2297
+ aud_path = aud if aud else None
2298
+
2299
+ input_image_update = img_path
2300
+ prompt_update = prompt_txt
2301
+ camera_update = cam
2302
+ resolution_update = res
2303
+ mode_update = mode
2304
+ video_update = gr.update(value=vid_path, visible=(mode == "Motion Control"))
2305
+ audio_update = aud_path
2306
+ end_image = end_img
2307
+
2308
+ return (
2309
+ input_image_update,
2310
+ prompt_update,
2311
+ camera_update,
2312
+ resolution_update,
2313
+ mode_update,
2314
+ video_update,
2315
+ audio_update,
2316
+ audio_update,
2317
+ end_image,
2318
+ )
2319
 
 
 
2320
 
2321
  ####################################################################################################
2322
  ### PART 20: Gradio UI Layout & Launch
2323
  ####################################################################################################
2324
 
2325
+ # JS Function to handle download request via PostMessage
2326
+ js_download_video = """
2327
+ async (video) => {
2328
+ if (!video) {
2329
+ alert("لطفاً ابتدا ویدیو را تولید کنید.");
2330
+ return;
2331
+ }
2332
 
2333
+ // Gradio Video component passes an object or string
2334
+ let fileUrl = "";
2335
+ if (typeof video === 'string') {
2336
+ fileUrl = video;
2337
+ } else if (video && video.url) {
2338
+ fileUrl = video.url;
2339
+ } else if (video && video.path) {
2340
+ fileUrl = video.path;
2341
+ }
2342
+
2343
+ // Fix relative paths to absolute URLs for the parent iframe
2344
+ if (fileUrl && !fileUrl.startsWith('http')) {
2345
+ // Remove leading slash if exists to prevent double slash with origin
2346
+ let cleanPath = fileUrl.startsWith('/') ? fileUrl.substring(1) : fileUrl;
2347
 
2348
+ // Check if it's already a file route
2349
+ if (cleanPath.startsWith('file=')) {
2350
+ fileUrl = window.location.origin + "/" + cleanPath;
2351
+ } else {
2352
+ fileUrl = window.location.origin + "/file=" + cleanPath;
2353
+ }
2354
+ }
2355
+
2356
+ if (fileUrl) {
2357
+ console.log("Sending download request for:", fileUrl);
2358
+ window.parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: fileUrl }, '*');
2359
+ }
2360
+ }
2361
+ """
2362
 
2363
+ def apply_example(idx: str):
2364
+ idx = int(idx)
2365
+
2366
+ # Read the example row from your list
2367
+ img, prompt_txt, cam, res, mode, vid, aud, end_img = examples_list[idx]
2368
+
2369
+ img_path = img if img else None
2370
+ vid_path = vid if vid else None
2371
+ aud_path = aud if aud else None
2372
+
2373
+ input_image_update = img_path
2374
+ prompt_update = prompt_txt
2375
+ camera_update = cam
2376
+ resolution_update = res
2377
+ mode_update = mode
2378
+ video_update = gr.update(value=vid_path, visible=(mode == "Motion Control"))
2379
+ audio_update = aud_path
2380
+ end_image = end_img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2381
 
2382
+ # Clear the output video when loading a new example
2383
+ output_video_update = gr.update(value=None)
2384
 
2385
+ return (
2386
+ input_image_update,
2387
+ prompt_update,
2388
+ camera_update,
2389
+ resolution_update,
2390
+ mode_update,
2391
+ video_update,
2392
+ audio_update,
2393
+ audio_update,
2394
+ end_image,
2395
+ output_video_update
2396
+ )
2397
+
2398
+
2399
+ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
2400
+
2401
+ # Updated Header to Persian
2402
  gr.HTML(
2403
  """
2404
+ <div style="text-align: center; padding: 20px;">
2405
+ <h1 style="font-size: 28px; font-weight: bold; margin-bottom: 10px; color: var(--body-text-color);">
2406
+ ساخت ویدیو با هوش مصنوعی
2407
+ </h1>
2408
+ <p style="font-size: 18px; color: var(--body-text-color-subdued); margin: 0;">
2409
+ با پشتیبانی از صدا و دو تصویر
2410
+ </p>
2411
  </div>
2412
  """
2413
  )
2414
 
2415
  with gr.Column(elem_id="col-container"):
2416
+ with gr.Row(elem_id="mode-row"):
2417
+ # Updated choices to Persian
2418
+ radioanimated_mode = RadioAnimated(
2419
  choices=["تبدیل تصویر به ویدیو", "تکمیل فریم‌های میانی"],
2420
  value="تبدیل تصویر به ویدیو",
2421
+ elem_id="radioanimated_mode"
 
2422
  )
 
2423
  with gr.Row():
2424
  with gr.Column(elem_id="step-column"):
2425
 
2426
  with gr.Row():
2427
+
2428
  first_frame = gr.Image(
2429
  label="تصویر اول (اختیاری)",
2430
  type="filepath",
 
2438
  visible=False,
2439
  )
2440
 
2441
+ # input_video is defined but hidden
2442
  input_video = gr.Video(
2443
  label="Motion Reference Video",
2444
  height=256,
2445
  visible=False,
2446
  )
2447
 
2448
+ relocate = gr.HTML(
2449
+ value="",
2450
+ html_template="<div></div>",
2451
+ js_on_load=r"""
2452
+ (() => {
2453
+ function moveIntoFooter() {
2454
+ const promptRoot = document.querySelector("#prompt_ui");
2455
+ if (!promptRoot) return false;
2456
+
2457
+ const footer = promptRoot.querySelector(".ds-footer");
2458
+ if (!footer) return false;
2459
+
2460
+ const dur = document.querySelector("#duration_ui .cd-wrap");
2461
+ const res = document.querySelector("#resolution_ui .cd-wrap");
2462
+ const cam = document.querySelector("#camera_ui .cd-wrap");
2463
+
2464
+ if (!dur || !res || !cam) return false;
2465
+
2466
+ footer.appendChild(dur);
2467
+ footer.appendChild(res);
2468
+ footer.appendChild(cam);
2469
+
2470
+ return true;
2471
+ }
2472
+
2473
+ const tick = () => {
2474
+ if (!moveIntoFooter()) requestAnimationFrame(tick);
2475
+ };
2476
+ requestAnimationFrame(tick);
2477
+ })();
2478
+ """
2479
+ )
2480
+
2481
+
2482
+ prompt_ui = PromptBox(
2483
  value="این تصویر را با حرکت سینمایی و انیمیشن روان زنده کن",
2484
+ elem_id="prompt_ui",
 
2485
  )
2486
 
2487
+ # Hidden real audio input (backend value)
2488
+ audio_input = gr.File(
2489
+ label="Audio (Optional)",
2490
+ file_types=["audio"],
2491
  type="filepath",
2492
+ elem_id="audio_input_hidden",
2493
+ )
2494
+
2495
+ # Custom UI that feeds the hidden gr.Audio above
2496
+ audio_ui = AudioDropUpload(
2497
+ target_audio_elem_id="audio_input_hidden",
2498
+ elem_id="audio_ui",
2499
+ )
2500
+
2501
+ prompt = gr.Textbox(
2502
+ label="Prompt",
2503
+ value="این تصویر را با حرکت سینمایی و انیمیشن روان زنده کن",
2504
+ lines=3,
2505
+ max_lines=3,
2506
+ placeholder="حرکت و انیمیشن مورد نظر خود را توصیف کنید...",
2507
+ visible=False
2508
  )
2509
 
2510
  enhance_prompt = gr.Checkbox(
2511
+ label="Enhance Prompt",
2512
  value=True,
2513
  visible=False
2514
  )
2515
 
2516
+ with gr.Accordion("تنظیمات پیشرفته", open=False, visible=False):
2517
  seed = gr.Slider(
2518
  label="سید (Seed)",
2519
  minimum=0,
 
2527
 
2528
  with gr.Column(elem_id="step-column"):
2529
  output_video = gr.Video(label="ویدیوی ساخته شده", autoplay=True, height=512)
2530
+
2531
+ # --- دکمه دانلود اضافه شده ---
2532
+ download_btn = gr.Button("📥 دانلود ویدیو", variant="secondary", elem_classes="button-gradient")
2533
 
2534
+ with gr.Row(elem_id="controls-row"):
2535
+
2536
+ duration_ui = CameraDropdown(
2537
  choices=["3s", "5s", "10s"],
2538
  value="5s",
2539
+ title="مدت زمان ویدیو",
2540
+ elem_id="duration_ui"
2541
+ )
2542
+
2543
+ duration = gr.Slider(
2544
+ label="Duration (seconds)",
2545
+ minimum=1.0,
2546
+ maximum=10.0,
2547
+ value=5.0,
2548
+ step=0.1,
2549
+ visible=False
2550
  )
2551
+
2552
+ ICON_16_9 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2553
+ <rect x="3" y="7" width="18" height="10" rx="2" stroke="currentColor" stroke-width="2"/>
2554
+ </svg>"""
2555
+
2556
+ ICON_1_1 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2557
+ <rect x="6" y="6" width="12" height="12" rx="2" stroke="currentColor" stroke-width="2"/>
2558
+ </svg>"""
2559
+
2560
+ ICON_9_16 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2561
+ <rect x="7" y="3" width="10" height="18" rx="2" stroke="currentColor" stroke-width="2"/>
2562
+ </svg>"""
2563
+
2564
 
2565
+ resolution_ui = CameraDropdown(
2566
+ choices=[
2567
+ {"label": "16:9", "value": "16:9", "icon": ICON_16_9},
2568
+ {"label": "1:1", "value": "1:1", "icon": ICON_1_1},
2569
+ {"label": "9:16", "value": "9:16", "icon": ICON_9_16},
2570
+ ],
2571
  value="16:9",
2572
+ title="ابعاد تصویر",
2573
+ elem_id="resolution_ui"
2574
  )
2575
 
2576
+
2577
+ width = gr.Number(label="Width", value=DEFAULT_1_STAGE_WIDTH, precision=0, visible=False)
2578
+ height = gr.Number(label="Height", value=DEFAULT_1_STAGE_HEIGHT, precision=0, visible=False)
2579
+
2580
+ camera_ui = CameraDropdown(
2581
  choices=[name for name, _ in VISIBLE_RUNTIME_LORA_CHOICES],
2582
  value="No LoRA",
2583
+ title="افکت دوربین (LoRA)",
2584
+ elem_id="camera_ui",
2585
+ )
2586
+
2587
+ # Hidden real dropdown (backend value)
2588
+ camera_lora = gr.Dropdown(
2589
+ label="Camera Control LoRA",
2590
+ choices=[name for name, _ in VISIBLE_RUNTIME_LORA_CHOICES],
2591
+ value="No LoRA",
2592
+ visible=False
2593
  )
2594
 
2595
+ generate_btn = gr.Button("🤩 ساخت ویدیو", variant="primary", elem_classes="button-gradient")
 
 
 
2596
 
 
 
2597
 
2598
+ camera_ui.change(
2599
+ fn=lambda x: x,
2600
+ inputs=camera_ui,
2601
+ outputs=camera_lora,
2602
+ api_visibility="private"
2603
+ )
2604
 
2605
+ radioanimated_mode.change(
2606
+ fn=on_mode_change,
2607
+ inputs=radioanimated_mode,
2608
+ outputs=[input_video, end_frame],
2609
+ api_visibility="private",
 
 
 
 
 
2610
  )
2611
 
 
 
2612
 
2613
+ duration_ui.change(
2614
+ fn=apply_duration,
2615
+ inputs=duration_ui,
2616
+ outputs=[duration],
2617
+ api_visibility="private"
2618
  )
2619
+ resolution_ui.change(
2620
+ fn=apply_resolution,
2621
+ inputs=resolution_ui,
2622
+ outputs=[width, height],
2623
+ api_visibility="private"
2624
+ )
2625
+ prompt_ui.change(
2626
+ fn=lambda x: x,
2627
+ inputs=prompt_ui,
2628
+ outputs=prompt,
2629
+ api_visibility="private"
2630
  )
2631
+
2632
 
2633
  generate_btn.click(
2634
  fn=generate_video,
 
2636
  first_frame,
2637
  end_frame,
2638
  prompt,
2639
+ duration,
2640
  input_video,
2641
+ radioanimated_mode,
2642
  enhance_prompt,
2643
  seed,
2644
  randomize_seed,
2645
  height,
2646
  width,
2647
+ camera_lora,
2648
  audio_input
2649
  ],
2650
  outputs=[output_video]
2651
  )
2652
+
2653
+ # --- اتصال دکمه دانلود به جاوا اسکریپت ---
2654
+ download_btn.click(
2655
+ fn=None,
2656
+ inputs=[output_video],
2657
+ js=js_download_video
2658
+ )
2659
 
2660
+ # Updated Examples to use Persian modes
2661
  examples_list = [
2662
  [
2663
  "examples/supergirl-2.png",
2664
+ "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit sleeping in bed and just waking up, she gradually gets up, rubbing her eyes and looking at her dog that just popped on the bed. the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation",
 
2665
  "Static",
2666
  "16:9",
2667
  "تبدیل تصویر به ویدیو",
2668
+ None,
2669
  "examples/supergirl.m4a",
2670
+ None,
2671
  ],
2672
  [
2673
  "examples/frame3.png",
2674
+ "a woman in a white dress standing in a supermarket, looking at a stack of pomegranates, she picks one and takes a bite, the camera zooms in to a close up of the pomegranate seeds. A calm music is playing in the supermarket and you can hear her taking a bite.",
 
2675
  "Zoom In",
2676
  "16:9",
2677
  "تکمیل فریم‌های میانی",
2678
  None,
2679
+ None,
2680
+ "examples/frame4.png",
2681
  ],
2682
  [
2683
  "examples/supergirl.png",
2684
+ "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit stands inside an icy cave made of frozen walls and icicles, she looks panicked and frantic, rapidly turning her head left and right and scanning the cave while waving her arms and shouting angrily and desperately, mouthing the words “where the hell is my dog,” her movements exaggerated and puppet-like with high energy and urgency, suddenly a second puppet dog bursts into frame from the side, jumping up excitedly and tackling her affectionately while licking her face repeatedly, she freezes in surprise and then breaks into relief and laughter as the dog continues licking her, the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation",
2685
+ "No LoRA",
2686
+ "16:9",
2687
+ "تبدیل تصویر به ویدیو",
2688
+ None,
2689
+ None,
2690
  None,
2691
+ ],
2692
+ [
2693
+ "examples/highland.png",
2694
+ "Realistic POV selfie-style video in a snowy, foggy field. Two shaggy Highland cows with long curved horns stand ahead. The camera is handheld and slightly shaky. The woman filming talks nervously and excitedly in a vlog tone: \"Oh my god guys… look how big those horns are… I’m kinda scared.\" The cow on the left walks toward the camera in a cute, bouncy, hopping way, curious and gentle. Snow crunches under its hooves, breath visible in the cold air. The horns look massive from the POV. As the cow gets very close, its wet nose with slight dripping fills part of the frame. She laughs nervously but reaches out and pets the cow. The cow makes deep, soft, interesting mooing and snorting sounds, calm and friendly. Ultra-realistic, natural lighting, immersive audio, documentary-style realism.",
2695
  "No LoRA",
2696
  "16:9",
2697
  "تبدیل تصویر به ویدیو",
2698
  None,
2699
+ None,
2700
+ None,
2701
  ],
2702
  [
2703
  "examples/wednesday.png",
2704
+ "A cinematic dolly out of Wednesday Addams frozen mid-dance on a dark, blue-lit ballroom floor as students move indistinctly behind her, their footsteps and muffled music reduced to a distant, underwater thrum; the audio foregrounds her steady breathing and the faint rustle of fabric as she slowly raises one arm, never breaking eye contact with the camera, then after a deliberately long silence she speaks in a flat, dry, perfectly controlled voice, “I don’t dance… I vibe code,” each word crisp and unemotional, followed by an abrupt cutoff of her voice as the background sound swells slightly, reinforcing the deadpan humor, with precise lip sync, minimal facial movement, stark gothic lighting, and cinematic realism.",
2705
+ "Zoom Out",
 
2706
  "16:9",
2707
  "تبدیل تصویر به ویدیو",
2708
  None,
2709
+ None,
2710
+ None,
2711
+ ],
2712
+ [
2713
+ "examples/astronaut.png",
2714
+ "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",
2715
+ "Static",
2716
+ "1:1",
2717
+ "تبدیل تصویر به ویدیو",
2718
+ None,
2719
+ None,
2720
+ None,
2721
+ ],
2722
  ]
2723
 
2724
+ examples_obj = create_examples(
 
 
 
 
 
2725
  examples=examples_list,
2726
+ fn=generate_video_example,
2727
+ inputs=[first_frame, prompt_ui, camera_ui, resolution_ui, radioanimated_mode, input_video, audio_input, end_frame],
2728
+ outputs = [output_video],
2729
+ label="نمونه‌ها",
2730
+ cache_examples=True,
2731
+ visible=False
2732
+ )
2733
+
2734
+ preset_gallery = PresetGallery(
2735
+ items=[
2736
+ {"thumb": "examples/supergirl-2.png", "label": "تصویر و صدا به ویدیو"},
2737
+ {"thumb": "examples/frame3.png", "label": "تصویر اول و آخر"},
2738
+ {"thumb": "examples/supergirl.png", "label": "تصویر به ویدیو (عروسک)"},
2739
+ {"thumb": "examples/highland.png", "label": "تصویر به ویدیو (گاو)"},
2740
+ {"thumb": "examples/wednesday.png", "label": "تصویر به ویدیو (ونزدی)"},
2741
+ {"thumb": "examples/astronaut.png", "label": "تصویر به ویدیو (فضانورد)"},
2742
+ ],
2743
+ title="برای شروع روی یکی از نمونه‌ها کلیک کنید",
2744
+ )
2745
+
2746
+ def on_audio_ui_change(v):
2747
+ # Our JS sends "__CLEAR__" when the user presses the X
2748
+ if v == "__CLEAR__" or v is None or v == "":
2749
+ return None
2750
+ # For normal events (uploads), do nothing (keep whatever gr.File already has)
2751
+ return gr.update()
2752
+
2753
+ audio_ui.change(
2754
+ fn=on_audio_ui_change,
2755
+ inputs=audio_ui,
2756
+ outputs=audio_input,
2757
+ api_visibility="private",
2758
+ )
2759
+
2760
+ preset_gallery.change(
2761
+ fn=apply_example,
2762
+ inputs=preset_gallery,
2763
+ outputs=[
2764
+ first_frame,
2765
+ prompt_ui,
2766
+ camera_ui,
2767
+ resolution_ui,
2768
+ radioanimated_mode,
2769
+ input_video,
2770
+ audio_input,
2771
+ audio_ui,
2772
+ end_frame,
2773
+ output_video # Clears the output video
2774
+ ],
2775
+ api_visibility="private",
2776
  )
2777
 
2778
  if __name__ == "__main__":
2779
+ demo.launch(ssr_mode=False, mcp_server=True, css=css, allowed_paths=["./examples"])