Spaces:
Running
Running
Update conver.py
Browse files
conver.py
CHANGED
@@ -1,15 +1,14 @@
|
|
1 |
from dataclasses import dataclass
|
2 |
from typing import List, Tuple, Dict
|
3 |
import os
|
4 |
-
import httpx
|
5 |
import json
|
|
|
6 |
from openai import OpenAI
|
7 |
import edge_tts
|
8 |
import tempfile
|
9 |
from pydub import AudioSegment
|
10 |
import base64
|
11 |
from pathlib import Path
|
12 |
-
import time
|
13 |
|
14 |
@dataclass
|
15 |
class ConversationConfig:
|
@@ -18,22 +17,14 @@ class ConversationConfig:
|
|
18 |
model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
|
19 |
|
20 |
class URLToAudioConverter:
|
21 |
-
BASE_OUTPUT_DIR = "outputs"
|
22 |
-
|
23 |
def __init__(self, config: ConversationConfig, llm_api_key: str):
|
24 |
self.config = config
|
25 |
self.llm_client = OpenAI(api_key=llm_api_key, base_url="https://api.together.xyz/v1")
|
26 |
self.llm_out = None
|
27 |
-
self._ensure_base_output_dir()
|
28 |
-
|
29 |
-
def _ensure_base_output_dir(self):
|
30 |
-
if not os.path.exists(self.BASE_OUTPUT_DIR):
|
31 |
-
os.makedirs(self.BASE_OUTPUT_DIR, exist_ok=True)
|
32 |
|
33 |
def fetch_text(self, url: str) -> str:
|
34 |
if not url:
|
35 |
raise ValueError("URL cannot be empty")
|
36 |
-
|
37 |
full_url = f"{self.config.prefix_url}{url}"
|
38 |
try:
|
39 |
response = httpx.get(full_url, timeout=60.0)
|
@@ -45,33 +36,27 @@ class URLToAudioConverter:
|
|
45 |
def extract_conversation(self, text: str) -> Dict:
|
46 |
if not text:
|
47 |
raise ValueError("Input text cannot be empty")
|
48 |
-
|
49 |
try:
|
50 |
prompt = (
|
51 |
f"{text}\nConvert the provided text into a short informative podcast conversation "
|
52 |
f"between two experts. Return ONLY a JSON object with the following structure:\n"
|
53 |
'{"conversation": [{"speaker": "Speaker1", "text": "..."}, {"speaker": "Speaker2", "text": "..."}]}'
|
54 |
)
|
55 |
-
|
56 |
chat_completion = self.llm_client.chat.completions.create(
|
57 |
messages=[{"role": "user", "content": prompt}],
|
58 |
model=self.config.model_name,
|
59 |
response_format={"type": "json_object"}
|
60 |
)
|
61 |
-
|
62 |
response_content = chat_completion.choices[0].message.content
|
63 |
json_str = response_content.strip()
|
64 |
-
|
65 |
if not json_str.startswith('{'):
|
66 |
start = json_str.find('{')
|
67 |
if start != -1:
|
68 |
json_str = json_str[start:]
|
69 |
-
|
70 |
if not json_str.endswith('}'):
|
71 |
end = json_str.rfind('}')
|
72 |
if end != -1:
|
73 |
json_str = json_str[:end+1]
|
74 |
-
|
75 |
return json.loads(json_str)
|
76 |
except Exception as e:
|
77 |
print(f"Error en extract_conversation: {str(e)}")
|
@@ -81,19 +66,15 @@ class URLToAudioConverter:
|
|
81 |
async def text_to_speech(self, conversation_json: Dict, voice_1: str, voice_2: str) -> Tuple[List[str], str]:
|
82 |
output_dir = Path(self._create_output_directory())
|
83 |
filenames = []
|
84 |
-
|
85 |
try:
|
86 |
for i, turn in enumerate(conversation_json["conversation"]):
|
87 |
filename = output_dir / f"output_{i}.mp3"
|
88 |
voice = voice_1 if i % 2 == 0 else voice_2
|
89 |
-
|
90 |
tmp_path, error = await self._generate_audio(turn["text"], voice)
|
91 |
if error:
|
92 |
raise RuntimeError(f"Text-to-speech failed: {error}")
|
93 |
-
|
94 |
os.rename(tmp_path, filename)
|
95 |
filenames.append(str(filename))
|
96 |
-
|
97 |
return filenames, str(output_dir)
|
98 |
except Exception as e:
|
99 |
raise RuntimeError(f"Failed to convert text to speech: {e}")
|
@@ -103,110 +84,101 @@ class URLToAudioConverter:
|
|
103 |
return None, "Text cannot be empty"
|
104 |
if not voice:
|
105 |
return None, "Voice cannot be empty"
|
106 |
-
|
107 |
voice_short_name = voice.split(" - ")[0]
|
108 |
rate_str = f"{rate:+d}%"
|
109 |
pitch_str = f"{pitch:+d}Hz"
|
110 |
communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
|
111 |
-
|
112 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
113 |
tmp_path = tmp_file.name
|
114 |
await communicate.save(tmp_path)
|
115 |
-
|
116 |
return tmp_path, None
|
117 |
|
118 |
def _create_output_directory(self) -> str:
|
119 |
-
# Crear carpeta única dentro de outputs/
|
120 |
random_bytes = os.urandom(8)
|
121 |
-
folder_name = base64.urlsafe_b64encode(random_bytes).decode("utf-8")
|
122 |
-
|
123 |
-
|
124 |
-
return full_path
|
125 |
|
126 |
-
def combine_audio_files(self, filenames: List[str]
|
127 |
if not filenames:
|
128 |
raise ValueError("No input files provided")
|
129 |
-
|
130 |
try:
|
131 |
combined = AudioSegment.empty()
|
132 |
for filename in filenames:
|
133 |
audio_segment = AudioSegment.from_file(filename, format="mp3")
|
134 |
combined += audio_segment
|
135 |
-
|
136 |
-
combined.export(output_file, format="mp3")
|
137 |
-
|
138 |
-
# NO eliminar archivos aquí. Solo en limpieza periódica.
|
139 |
-
|
140 |
except Exception as e:
|
141 |
raise RuntimeError(f"Failed to combine audio files: {e}")
|
142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
async def url_to_audio(self, url: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
144 |
text = self.fetch_text(url)
|
145 |
-
|
146 |
words = text.split()
|
147 |
if len(words) > self.config.max_words:
|
148 |
text = " ".join(words[:self.config.max_words])
|
149 |
-
|
150 |
conversation_json = self.extract_conversation(text)
|
151 |
conversation_text = "\n".join(
|
152 |
f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
|
153 |
)
|
154 |
self.llm_out = conversation_json
|
155 |
-
audio_files, folder_name = await self.text_to_speech(
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
|
|
|
|
|
|
161 |
return final_output, conversation_text
|
162 |
|
163 |
async def text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
164 |
-
"""Procesamiento normal con LLM"""
|
165 |
conversation_json = self.extract_conversation(text)
|
166 |
conversation_text = "\n".join(
|
167 |
f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
|
168 |
)
|
169 |
-
audio_files, folder_name = await self.text_to_speech(
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
self.
|
|
|
|
|
|
|
|
|
174 |
return final_output, conversation_text
|
175 |
|
176 |
async def raw_text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
Borra carpetas y archivos en BASE_OUTPUT_DIR que tengan más de max_age_seconds (por defecto 24h)
|
194 |
-
"""
|
195 |
-
if not os.path.exists(self.BASE_OUTPUT_DIR):
|
196 |
-
return
|
197 |
-
now = time.time()
|
198 |
-
for folder in os.listdir(self.BASE_OUTPUT_DIR):
|
199 |
-
folder_path = os.path.join(self.BASE_OUTPUT_DIR, folder)
|
200 |
-
if os.path.isdir(folder_path):
|
201 |
-
try:
|
202 |
-
mtime = os.path.getmtime(folder_path)
|
203 |
-
if now - mtime > max_age_seconds:
|
204 |
-
# Borramos carpeta completa
|
205 |
-
for root, dirs, files in os.walk(folder_path, topdown=False):
|
206 |
-
for name in files:
|
207 |
-
os.remove(os.path.join(root, name))
|
208 |
-
for name in dirs:
|
209 |
-
os.rmdir(os.path.join(root, name))
|
210 |
-
os.rmdir(folder_path)
|
211 |
-
except Exception:
|
212 |
-
pass
|
|
|
1 |
from dataclasses import dataclass
|
2 |
from typing import List, Tuple, Dict
|
3 |
import os
|
|
|
4 |
import json
|
5 |
+
import httpx
|
6 |
from openai import OpenAI
|
7 |
import edge_tts
|
8 |
import tempfile
|
9 |
from pydub import AudioSegment
|
10 |
import base64
|
11 |
from pathlib import Path
|
|
|
12 |
|
13 |
@dataclass
|
14 |
class ConversationConfig:
|
|
|
17 |
model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
|
18 |
|
19 |
class URLToAudioConverter:
|
|
|
|
|
20 |
def __init__(self, config: ConversationConfig, llm_api_key: str):
|
21 |
self.config = config
|
22 |
self.llm_client = OpenAI(api_key=llm_api_key, base_url="https://api.together.xyz/v1")
|
23 |
self.llm_out = None
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
def fetch_text(self, url: str) -> str:
|
26 |
if not url:
|
27 |
raise ValueError("URL cannot be empty")
|
|
|
28 |
full_url = f"{self.config.prefix_url}{url}"
|
29 |
try:
|
30 |
response = httpx.get(full_url, timeout=60.0)
|
|
|
36 |
def extract_conversation(self, text: str) -> Dict:
|
37 |
if not text:
|
38 |
raise ValueError("Input text cannot be empty")
|
|
|
39 |
try:
|
40 |
prompt = (
|
41 |
f"{text}\nConvert the provided text into a short informative podcast conversation "
|
42 |
f"between two experts. Return ONLY a JSON object with the following structure:\n"
|
43 |
'{"conversation": [{"speaker": "Speaker1", "text": "..."}, {"speaker": "Speaker2", "text": "..."}]}'
|
44 |
)
|
|
|
45 |
chat_completion = self.llm_client.chat.completions.create(
|
46 |
messages=[{"role": "user", "content": prompt}],
|
47 |
model=self.config.model_name,
|
48 |
response_format={"type": "json_object"}
|
49 |
)
|
|
|
50 |
response_content = chat_completion.choices[0].message.content
|
51 |
json_str = response_content.strip()
|
|
|
52 |
if not json_str.startswith('{'):
|
53 |
start = json_str.find('{')
|
54 |
if start != -1:
|
55 |
json_str = json_str[start:]
|
|
|
56 |
if not json_str.endswith('}'):
|
57 |
end = json_str.rfind('}')
|
58 |
if end != -1:
|
59 |
json_str = json_str[:end+1]
|
|
|
60 |
return json.loads(json_str)
|
61 |
except Exception as e:
|
62 |
print(f"Error en extract_conversation: {str(e)}")
|
|
|
66 |
async def text_to_speech(self, conversation_json: Dict, voice_1: str, voice_2: str) -> Tuple[List[str], str]:
|
67 |
output_dir = Path(self._create_output_directory())
|
68 |
filenames = []
|
|
|
69 |
try:
|
70 |
for i, turn in enumerate(conversation_json["conversation"]):
|
71 |
filename = output_dir / f"output_{i}.mp3"
|
72 |
voice = voice_1 if i % 2 == 0 else voice_2
|
|
|
73 |
tmp_path, error = await self._generate_audio(turn["text"], voice)
|
74 |
if error:
|
75 |
raise RuntimeError(f"Text-to-speech failed: {error}")
|
|
|
76 |
os.rename(tmp_path, filename)
|
77 |
filenames.append(str(filename))
|
|
|
78 |
return filenames, str(output_dir)
|
79 |
except Exception as e:
|
80 |
raise RuntimeError(f"Failed to convert text to speech: {e}")
|
|
|
84 |
return None, "Text cannot be empty"
|
85 |
if not voice:
|
86 |
return None, "Voice cannot be empty"
|
|
|
87 |
voice_short_name = voice.split(" - ")[0]
|
88 |
rate_str = f"{rate:+d}%"
|
89 |
pitch_str = f"{pitch:+d}Hz"
|
90 |
communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
|
|
|
91 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
92 |
tmp_path = tmp_file.name
|
93 |
await communicate.save(tmp_path)
|
|
|
94 |
return tmp_path, None
|
95 |
|
96 |
def _create_output_directory(self) -> str:
|
|
|
97 |
random_bytes = os.urandom(8)
|
98 |
+
folder_name = base64.urlsafe_b64encode(random_bytes).decode("utf-8")
|
99 |
+
os.makedirs(folder_name, exist_ok=True)
|
100 |
+
return folder_name
|
|
|
101 |
|
102 |
+
def combine_audio_files(self, filenames: List[str]) -> AudioSegment:
|
103 |
if not filenames:
|
104 |
raise ValueError("No input files provided")
|
|
|
105 |
try:
|
106 |
combined = AudioSegment.empty()
|
107 |
for filename in filenames:
|
108 |
audio_segment = AudioSegment.from_file(filename, format="mp3")
|
109 |
combined += audio_segment
|
110 |
+
return combined
|
|
|
|
|
|
|
|
|
111 |
except Exception as e:
|
112 |
raise RuntimeError(f"Failed to combine audio files: {e}")
|
113 |
|
114 |
+
def add_background_music_and_tags(
|
115 |
+
self, speech_audio: AudioSegment, music_file: str, tags_files: List[str]
|
116 |
+
) -> AudioSegment:
|
117 |
+
music = AudioSegment.from_file(music_file)
|
118 |
+
if len(music) < len(speech_audio):
|
119 |
+
loops = (len(speech_audio) // len(music)) + 1
|
120 |
+
music = music * loops
|
121 |
+
music = music[:len(speech_audio)] - 20 # bajar volumen música
|
122 |
+
mixed = speech_audio.overlay(music)
|
123 |
+
for i, tag_path in enumerate(tags_files):
|
124 |
+
tag_audio = AudioSegment.from_file(tag_path) - 5
|
125 |
+
if i == 0:
|
126 |
+
mixed = tag_audio + mixed
|
127 |
+
else:
|
128 |
+
mixed = mixed + tag_audio
|
129 |
+
return mixed
|
130 |
+
|
131 |
async def url_to_audio(self, url: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
132 |
text = self.fetch_text(url)
|
|
|
133 |
words = text.split()
|
134 |
if len(words) > self.config.max_words:
|
135 |
text = " ".join(words[:self.config.max_words])
|
|
|
136 |
conversation_json = self.extract_conversation(text)
|
137 |
conversation_text = "\n".join(
|
138 |
f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
|
139 |
)
|
140 |
self.llm_out = conversation_json
|
141 |
+
audio_files, folder_name = await self.text_to_speech(conversation_json, voice_1, voice_2)
|
142 |
+
combined_audio = self.combine_audio_files(audio_files)
|
143 |
+
music_path = "assets/musica.mp3"
|
144 |
+
tags_paths = ["assets/tag.mp3", "assets/tag2.mp3"]
|
145 |
+
final_audio = self.add_background_music_and_tags(combined_audio, music_path, tags_paths)
|
146 |
+
final_output = os.path.join(folder_name, "combined_output_with_music.mp3")
|
147 |
+
final_audio.export(final_output, format="mp3")
|
148 |
+
for f in audio_files:
|
149 |
+
os.remove(f)
|
150 |
return final_output, conversation_text
|
151 |
|
152 |
async def text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
|
|
153 |
conversation_json = self.extract_conversation(text)
|
154 |
conversation_text = "\n".join(
|
155 |
f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
|
156 |
)
|
157 |
+
audio_files, folder_name = await self.text_to_speech(conversation_json, voice_1, voice_2)
|
158 |
+
combined_audio = self.combine_audio_files(audio_files)
|
159 |
+
music_path = "assets/musica.mp3"
|
160 |
+
tags_paths = ["assets/tag.mp3", "assets/tag2.mp3"]
|
161 |
+
final_audio = self.add_background_music_and_tags(combined_audio, music_path, tags_paths)
|
162 |
+
final_output = os.path.join(folder_name, "combined_output_with_music.mp3")
|
163 |
+
final_audio.export(final_output, format="mp3")
|
164 |
+
for f in audio_files:
|
165 |
+
os.remove(f)
|
166 |
return final_output, conversation_text
|
167 |
|
168 |
async def raw_text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
|
169 |
+
conversation = {
|
170 |
+
"conversation": [
|
171 |
+
{"speaker": "Host", "text": text},
|
172 |
+
{"speaker": "Co-host", "text": "(Continuación del tema)"}
|
173 |
+
]
|
174 |
+
}
|
175 |
+
audio_files, folder_name = await self.text_to_speech(conversation, voice_1, voice_2)
|
176 |
+
combined_audio = self.combine_audio_files(audio_files)
|
177 |
+
music_path = "assets/musica.mp3"
|
178 |
+
tags_paths = ["assets/tag.mp3", "assets/tag2.mp3"]
|
179 |
+
final_audio = self.add_background_music_and_tags(combined_audio, music_path, tags_paths)
|
180 |
+
output_file = os.path.join(folder_name, "raw_podcast_with_music.mp3")
|
181 |
+
final_audio.export(output_file, format="mp3")
|
182 |
+
for f in audio_files:
|
183 |
+
os.remove(f)
|
184 |
+
return text, output_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|