NickVerri commited on
Commit
476feb2
·
verified ·
1 Parent(s): d929156

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -42
app.py CHANGED
@@ -5,32 +5,12 @@ import json
5
  import os
6
  import requests
7
  import torch
8
- import numpy as np
9
  from datetime import timedelta
10
  from pyannote.audio import Pipeline
11
- from huggingface_hub import login, hf_hub_download
12
  from pydub import AudioSegment
13
 
14
- # --- Safe Globals for PyTorch 2.6+ ---
15
- try:
16
- from pyannote.audio.core.task import Specifications, Problem, Resolution
17
- from pyannote.audio.core.model import Model
18
- from pyannote.audio.pipelines.speaker_diarization import SpeakerDiarization
19
-
20
- torch.serialization.add_safe_globals([
21
- torch.torch_version.TorchVersion,
22
- Specifications,
23
- Problem,
24
- Resolution,
25
- Model,
26
- SpeakerDiarization,
27
- np.dtype,
28
- torch.nn.modules.container.ModuleList,
29
- np.core.multiarray.scalar
30
- ])
31
- except Exception as e:
32
- print(f"Safe Globals Warning: {e}")
33
-
34
  # --- Configuration & Tokens ---
35
  HARDCODED_HF_TOKEN = "PASTE_YOUR_HF_TOKEN_HERE"
36
  HARDCODED_GEMINI_KEY = ""
@@ -71,7 +51,7 @@ def generate_cmx_edl(edl_title, segments, source_name, fps=25):
71
  def call_gemini_for_edl(transcript_data, story_prompt, api_key):
72
  """Sends diarized, word-level transcript to Gemini Senior Editor."""
73
  if not api_key:
74
- st.error("Gemini API Key is missing. Set it in Space Secrets or app.py.")
75
  return None
76
 
77
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key={api_key}"
@@ -106,7 +86,7 @@ def call_gemini_for_edl(transcript_data, story_prompt, api_key):
106
 
107
  # --- Streamlit UI ---
108
  st.set_page_config(page_title="DocAI Editor", layout="wide")
109
- st.title("Documentary AI: Pipeline (Stable v2.1)")
110
 
111
  with st.sidebar:
112
  st.header("Project Settings")
@@ -127,14 +107,13 @@ if uploaded_file:
127
  if not ACTIVE_HF_TOKEN or "PASTE_YOUR_HF_TOKEN" in ACTIVE_HF_TOKEN:
128
  st.error("Please provide a valid Hugging Face Token.")
129
  else:
130
- with st.spinner("Processing... This may take a moment."):
131
- # Save local temp file
132
  with open("temp_input", "wb") as f:
133
  f.write(uploaded_file.getbuffer())
134
 
135
  st.write("🎵 **Preprocessing Audio...**")
136
  try:
137
- # Use PyDub to convert to WAV (Mono, 16kHz)
138
  audio = AudioSegment.from_file("temp_input")
139
  audio = audio.set_channels(1)
140
  audio = audio.set_frame_rate(16000)
@@ -147,15 +126,15 @@ if uploaded_file:
147
  st.write("🗣️ **Running Speaker Diarization...**")
148
  diarization = None
149
  try:
150
- # FIX: Pass revision separately, remove @ from repo_id
151
- config_path = hf_hub_download(
152
- repo_id="pyannote/speaker-diarization",
153
- revision="2.1", # Explicit revision
154
- filename="config.yaml",
155
- token=ACTIVE_HF_TOKEN
156
- )
157
 
158
- pipeline = Pipeline.from_pretrained(config_path)
 
 
 
 
 
159
 
160
  if torch.cuda.is_available():
161
  st.write("🚀 Using GPU for Diarization")
@@ -181,13 +160,16 @@ if uploaded_file:
181
 
182
  if diarization:
183
  # 2.1.1 returns a proper Annotation object directly
184
- for turn, _, speaker_id in diarization.itertracks(yield_label=True):
185
- speaker_turns.append({"start": turn.start, "end": turn.end, "speaker": speaker_id})
186
-
187
- if len(speaker_turns) > 0:
188
- st.write(f"✅ Found {len(speaker_turns)} speaker turns.")
189
- else:
190
- st.warning("⚠️ Pipeline ran but returned no tracks.")
 
 
 
191
 
192
  for segment in result['segments']:
193
  mid_time = (segment['start'] + segment['end']) / 2
 
5
  import os
6
  import requests
7
  import torch
8
+ import torchaudio
9
  from datetime import timedelta
10
  from pyannote.audio import Pipeline
11
+ from huggingface_hub import login
12
  from pydub import AudioSegment
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # --- Configuration & Tokens ---
15
  HARDCODED_HF_TOKEN = "PASTE_YOUR_HF_TOKEN_HERE"
16
  HARDCODED_GEMINI_KEY = ""
 
51
  def call_gemini_for_edl(transcript_data, story_prompt, api_key):
52
  """Sends diarized, word-level transcript to Gemini Senior Editor."""
53
  if not api_key:
54
+ st.error("Gemini API Key is missing.")
55
  return None
56
 
57
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key={api_key}"
 
86
 
87
  # --- Streamlit UI ---
88
  st.set_page_config(page_title="DocAI Editor", layout="wide")
89
+ st.title("Documentary AI: Pipeline (Stable 2.1)")
90
 
91
  with st.sidebar:
92
  st.header("Project Settings")
 
107
  if not ACTIVE_HF_TOKEN or "PASTE_YOUR_HF_TOKEN" in ACTIVE_HF_TOKEN:
108
  st.error("Please provide a valid Hugging Face Token.")
109
  else:
110
+ with st.spinner("Processing..."):
 
111
  with open("temp_input", "wb") as f:
112
  f.write(uploaded_file.getbuffer())
113
 
114
  st.write("🎵 **Preprocessing Audio...**")
115
  try:
116
+ # Use PyDub for robust WAV conversion
117
  audio = AudioSegment.from_file("temp_input")
118
  audio = audio.set_channels(1)
119
  audio = audio.set_frame_rate(16000)
 
126
  st.write("🗣️ **Running Speaker Diarization...**")
127
  diarization = None
128
  try:
129
+ # Login with token first
130
+ login(token=ACTIVE_HF_TOKEN)
 
 
 
 
 
131
 
132
+ # Load pipeline using legacy API (use_auth_token is valid here)
133
+ # NOTE: Using the older model ID for 2.1 compatibility
134
+ pipeline = Pipeline.from_pretrained(
135
+ "pyannote/speaker-diarization@2.1",
136
+ use_auth_token=ACTIVE_HF_TOKEN
137
+ )
138
 
139
  if torch.cuda.is_available():
140
  st.write("🚀 Using GPU for Diarization")
 
160
 
161
  if diarization:
162
  # 2.1.1 returns a proper Annotation object directly
163
+ try:
164
+ for turn, _, speaker_id in diarization.itertracks(yield_label=True):
165
+ speaker_turns.append({"start": turn.start, "end": turn.end, "speaker": speaker_id})
166
+
167
+ if len(speaker_turns) > 0:
168
+ st.write(f"✅ Found {len(speaker_turns)} speaker turns.")
169
+ else:
170
+ st.warning("⚠️ Pipeline ran but returned no tracks.")
171
+ except AttributeError:
172
+ st.error("Could not iterate tracks.")
173
 
174
  for segment in result['segments']:
175
  mid_time = (segment['start'] + segment['end']) / 2