Spaces:
Running
Running
Update conver.py
Browse files
conver.py
CHANGED
@@ -23,32 +23,99 @@ class URLToAudioConverter:
|
|
23 |
self.config = config
|
24 |
self.llm_client = OpenAI(api_key=llm_api_key, base_url="https://api.together.xyz/v1")
|
25 |
self.llm_out = None
|
26 |
-
self._start_cleaner() #
|
27 |
|
28 |
def _start_cleaner(self, max_age_hours: int = 24):
|
29 |
-
"""
|
30 |
def cleaner():
|
31 |
while True:
|
32 |
now = time.time()
|
33 |
for root, _, files in os.walk("."):
|
34 |
for file in files:
|
35 |
-
if file.endswith((".mp3", ".wav")):
|
36 |
filepath = os.path.join(root, file)
|
37 |
try:
|
38 |
-
|
39 |
-
if file_age > max_age_hours * 3600:
|
40 |
os.remove(filepath)
|
41 |
except:
|
42 |
-
|
43 |
-
time.sleep(3600)
|
44 |
-
|
45 |
Thread(target=cleaner, daemon=True).start()
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
-
# Método add_background_music_and_tags con paréntesis corregido (sin otros cambios)
|
52 |
def add_background_music_and_tags(
|
53 |
self,
|
54 |
speech_audio: AudioSegment,
|
@@ -57,7 +124,7 @@ class URLToAudioConverter:
|
|
57 |
) -> AudioSegment:
|
58 |
music = AudioSegment.from_file(music_path).fade_out(2000) - 25
|
59 |
if len(music) < len(speech_audio):
|
60 |
-
music = music * ((len(speech_audio) // len(music)) + 1
|
61 |
music = music[:len(speech_audio)]
|
62 |
mixed = speech_audio.overlay(music)
|
63 |
|
@@ -77,4 +144,42 @@ class URLToAudioConverter:
|
|
77 |
|
78 |
return final_audio
|
79 |
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
self.config = config
|
24 |
self.llm_client = OpenAI(api_key=llm_api_key, base_url="https://api.together.xyz/v1")
|
25 |
self.llm_out = None
|
26 |
+
self._start_cleaner() # Inicia limpieza automática
|
27 |
|
28 |
def _start_cleaner(self, max_age_hours: int = 24):
|
29 |
+
"""Elimina archivos antiguos cada hora"""
|
30 |
def cleaner():
|
31 |
while True:
|
32 |
now = time.time()
|
33 |
for root, _, files in os.walk("."):
|
34 |
for file in files:
|
35 |
+
if file.endswith((".mp3", ".wav")):
|
36 |
filepath = os.path.join(root, file)
|
37 |
try:
|
38 |
+
if now - os.path.getmtime(filepath) > max_age_hours * 3600:
|
|
|
39 |
os.remove(filepath)
|
40 |
except:
|
41 |
+
pass
|
42 |
+
time.sleep(3600)
|
|
|
43 |
Thread(target=cleaner, daemon=True).start()
|
44 |
|
45 |
+
def fetch_text(self, url: str) -> str:
|
46 |
+
if not url:
|
47 |
+
raise ValueError("URL cannot be empty")
|
48 |
+
full_url = f"{self.config.prefix_url}{url}"
|
49 |
+
try:
|
50 |
+
response = httpx.get(full_url, timeout=60.0)
|
51 |
+
response.raise_for_status()
|
52 |
+
return response.text
|
53 |
+
except httpx.HTTPError as e:
|
54 |
+
raise RuntimeError(f"Failed to fetch URL: {e}")
|
55 |
+
|
56 |
+
def extract_conversation(self, text: str) -> Dict:
|
57 |
+
if not text:
|
58 |
+
raise ValueError("Input text cannot be empty")
|
59 |
+
try:
|
60 |
+
prompt = f"{text}\nConvert this into a podcast dialogue between Host1 and Host2. Return ONLY:\nHost1: [text]\nHost2: [text]\n..."
|
61 |
+
response = self.llm_client.chat.completions.create(
|
62 |
+
messages=[{"role": "user", "content": prompt}],
|
63 |
+
model=self.config.model_name
|
64 |
+
)
|
65 |
+
raw_text = response.choices[0].message.content
|
66 |
+
dialogue = {"conversation": []}
|
67 |
+
for line in raw_text.split('\n'):
|
68 |
+
if ':' in line:
|
69 |
+
speaker, _, content = line.partition(':')
|
70 |
+
if speaker.strip() in ("Host1", "Host2"):
|
71 |
+
dialogue["conversation"].append({
|
72 |
+
"speaker": speaker.strip(),
|
73 |
+
"text": content.strip()
|
74 |
+
})
|
75 |
+
return dialogue
|
76 |
+
except Exception as e:
|
77 |
+
raise RuntimeError(f"Failed to parse dialogue: {str(e)}")
|
78 |
+
|
79 |
+
async def text_to_speech(self, conversation_json: Dict, voice_1: str, voice_2: str) -> Tuple[List[str], str]:
|
80 |
+
output_dir = Path(self._create_output_directory())
|
81 |
+
filenames = []
|
82 |
+
try:
|
83 |
+
for i, turn in enumerate(conversation_json["conversation"]):
|
84 |
+
filename = output_dir / f"segment_{i}.mp3"
|
85 |
+
voice = voice_1 if turn["speaker"] == "Host1" else voice_2
|
86 |
+
tmp_path = await self._generate_audio(turn["text"], voice)
|
87 |
+
os.rename(tmp_path, filename)
|
88 |
+
filenames.append(str(filename))
|
89 |
+
return filenames, str(output_dir)
|
90 |
+
except Exception as e:
|
91 |
+
raise RuntimeError(f"Text-to-speech failed: {e}")
|
92 |
+
|
93 |
+
async def _generate_audio(self, text: str, voice: str) -> str:
|
94 |
+
if not text.strip():
|
95 |
+
raise ValueError("Text cannot be empty")
|
96 |
+
communicate = edge_tts.Communicate(
|
97 |
+
text,
|
98 |
+
voice.split(" - ")[0],
|
99 |
+
rate="+0%",
|
100 |
+
pitch="+0Hz"
|
101 |
+
)
|
102 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
103 |
+
await communicate.save(tmp_file.name)
|
104 |
+
return tmp_file.name
|
105 |
+
|
106 |
+
def _create_output_directory(self) -> str:
|
107 |
+
folder_name = base64.urlsafe_b64encode(os.urandom(8)).decode("utf-8")
|
108 |
+
os.makedirs(folder_name, exist_ok=True)
|
109 |
+
return folder_name
|
110 |
+
|
111 |
+
def combine_audio_files(self, filenames: List[str]) -> AudioSegment:
|
112 |
+
if not filenames:
|
113 |
+
raise ValueError("No audio files provided")
|
114 |
+
combined = AudioSegment.empty()
|
115 |
+
for filename in filenames:
|
116 |
+
combined += AudioSegment.from_file(filename, format="mp3")
|
117 |
+
return combined
|
118 |
|
|
|
119 |
def add_background_music_and_tags(
|
120 |
self,
|
121 |
speech_audio: AudioSegment,
|
|
|
124 |
) -> AudioSegment:
|
125 |
music = AudioSegment.from_file(music_path).fade_out(2000) - 25
|
126 |
if len(music) < len(speech_audio):
|
127 |
+
music = music * ((len(speech_audio) // len(music)) + 1
|
128 |
music = music[:len(speech_audio)]
|
129 |
mixed = speech_audio.overlay(music)
|
130 |
|
|
|
144 |
|
145 |
return final_audio
|
146 |
|
147 |
+
async def url_to_audio(self, url: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
148 |
+
text = self.fetch_text(url)
|
149 |
+
if len(words := text.split()) > self.config.max_words:
|
150 |
+
text = " ".join(words[:self.config.max_words])
|
151 |
+
conversation = self.extract_conversation(text)
|
152 |
+
return await self._process_to_audio(conversation, voice_1, voice_2)
|
153 |
+
|
154 |
+
async def text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
155 |
+
conversation = self.extract_conversation(text)
|
156 |
+
return await self._process_to_audio(conversation, voice_1, voice_2)
|
157 |
+
|
158 |
+
async def raw_text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
159 |
+
conversation = {"conversation": [{"speaker": "Host1", "text": text}]}
|
160 |
+
return await self._process_to_audio(conversation, voice_1, voice_2)
|
161 |
+
|
162 |
+
async def _process_to_audio(
|
163 |
+
self,
|
164 |
+
conversation: Dict,
|
165 |
+
voice_1: str,
|
166 |
+
voice_2: str
|
167 |
+
) -> Tuple[str, str]:
|
168 |
+
audio_files, folder_name = await self.text_to_speech(conversation, voice_1, voice_2)
|
169 |
+
combined = self.combine_audio_files(audio_files)
|
170 |
+
final_audio = self.add_background_music_and_tags(
|
171 |
+
combined,
|
172 |
+
"musica.mp3",
|
173 |
+
["tag.mp3", "tag2.mp3"]
|
174 |
+
)
|
175 |
+
output_path = os.path.join(folder_name, "podcast_final.mp3")
|
176 |
+
final_audio.export(output_path, format="mp3")
|
177 |
+
|
178 |
+
for f in audio_files:
|
179 |
+
os.remove(f)
|
180 |
+
|
181 |
+
text_output = "\n".join(
|
182 |
+
f"{turn['speaker']}: {turn['text']}"
|
183 |
+
for turn in conversation["conversation"]
|
184 |
+
)
|
185 |
+
return output_path, text_output
|