gnosticdev commited on
Commit
eb823dc
·
verified ·
1 Parent(s): 71a491a

Update conver.py

Browse files
Files changed (1) hide show
  1. conver.py +79 -35
conver.py CHANGED
@@ -1,7 +1,6 @@
1
  from dataclasses import dataclass
2
  from typing import List, Tuple, Dict
3
  import os
4
- import re
5
  import httpx
6
  import json
7
  from openai import OpenAI
@@ -19,10 +18,17 @@ class ConversationConfig:
19
  model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
20
 
21
  class URLToAudioConverter:
 
 
22
  def __init__(self, config: ConversationConfig, llm_api_key: str):
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
 
27
  def fetch_text(self, url: str) -> str:
28
  if not url:
@@ -46,44 +52,49 @@ class URLToAudioConverter:
46
  f"between two experts. Return ONLY a JSON object with the following structure:\n"
47
  '{"conversation": [{"speaker": "Speaker1", "text": "..."}, {"speaker": "Speaker2", "text": "..."}]}'
48
  )
49
-
50
  chat_completion = self.llm_client.chat.completions.create(
51
  messages=[{"role": "user", "content": prompt}],
52
  model=self.config.model_name,
53
  response_format={"type": "json_object"}
54
  )
55
-
56
  response_content = chat_completion.choices[0].message.content
57
  json_str = response_content.strip()
58
-
59
  if not json_str.startswith('{'):
60
  start = json_str.find('{')
61
  if start != -1:
62
  json_str = json_str[start:]
63
-
64
  if not json_str.endswith('}'):
65
  end = json_str.rfind('}')
66
  if end != -1:
67
  json_str = json_str[:end+1]
68
-
69
  return json.loads(json_str)
70
  except Exception as e:
71
  print(f"Error en extract_conversation: {str(e)}")
 
72
  raise RuntimeError(f"Failed to extract conversation: {str(e)}")
73
 
74
  async def text_to_speech(self, conversation_json: Dict, voice_1: str, voice_2: str) -> Tuple[List[str], str]:
75
- output_dir = self._create_output_directory()
76
  filenames = []
 
77
  try:
78
  for i, turn in enumerate(conversation_json["conversation"]):
79
- filename = os.path.join(output_dir, f"output_{i}.mp3")
80
  voice = voice_1 if i % 2 == 0 else voice_2
 
81
  tmp_path, error = await self._generate_audio(turn["text"], voice)
82
  if error:
83
  raise RuntimeError(f"Text-to-speech failed: {error}")
 
84
  os.rename(tmp_path, filename)
85
- filenames.append(filename)
86
- return filenames, output_dir
 
87
  except Exception as e:
88
  raise RuntimeError(f"Failed to convert text to speech: {e}")
89
 
@@ -92,75 +103,108 @@ class URLToAudioConverter:
92
  return None, "Text cannot be empty"
93
  if not voice:
94
  return None, "Voice cannot be empty"
 
95
  voice_short_name = voice.split(" - ")[0]
96
  rate_str = f"{rate:+d}%"
97
  pitch_str = f"{pitch:+d}Hz"
98
  communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
 
99
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
100
  tmp_path = tmp_file.name
101
  await communicate.save(tmp_path)
 
102
  return tmp_path, None
103
 
104
  def _create_output_directory(self) -> str:
105
- os.makedirs("outputs", exist_ok=True)
106
- return "outputs"
107
-
108
- def clean_old_files(self, directory: str = "outputs", max_age_seconds: int = 86400):
109
- now = time.time()
110
- for filename in os.listdir(directory):
111
- file_path = os.path.join(directory, filename)
112
- if file_path.endswith(".mp3"):
113
- file_age = now - os.path.getmtime(file_path)
114
- if file_age > max_age_seconds:
115
- os.remove(file_path)
116
 
117
  def combine_audio_files(self, filenames: List[str], output_file: str) -> None:
118
  if not filenames:
119
  raise ValueError("No input files provided")
 
120
  try:
121
  combined = AudioSegment.empty()
122
  for filename in filenames:
123
- combined += AudioSegment.from_file(filename, format="mp3")
 
 
124
  combined.export(output_file, format="mp3")
 
 
 
125
  except Exception as e:
126
  raise RuntimeError(f"Failed to combine audio files: {e}")
127
 
128
  async def url_to_audio(self, url: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
129
- self.clean_old_files()
130
  text = self.fetch_text(url)
 
131
  words = text.split()
132
  if len(words) > self.config.max_words:
133
  text = " ".join(words[:self.config.max_words])
 
134
  conversation_json = self.extract_conversation(text)
135
  conversation_text = "\n".join(
136
  f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
137
  )
138
  self.llm_out = conversation_json
139
- audio_files, output_dir = await self.text_to_speech(conversation_json, voice_1, voice_2)
140
- output_file = os.path.join(output_dir, f"combined_{int(time.time())}.mp3")
141
- self.combine_audio_files(audio_files, output_file)
142
- return output_file, conversation_text
 
 
 
143
 
144
  async def text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
145
- self.clean_old_files()
146
  conversation_json = self.extract_conversation(text)
147
  conversation_text = "\n".join(
148
  f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
149
  )
150
- audio_files, output_dir = await self.text_to_speech(conversation_json, voice_1, voice_2)
151
- output_file = os.path.join(output_dir, f"combined_{int(time.time())}.mp3")
152
- self.combine_audio_files(audio_files, output_file)
153
- return output_file, conversation_text
 
 
154
 
155
  async def raw_text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
156
- self.clean_old_files()
157
  conversation = {
158
  "conversation": [
159
  {"speaker": "Host", "text": text},
160
  {"speaker": "Co-host", "text": "(Continuación del tema)"}
161
  ]
162
  }
163
- audio_files, output_dir = await self.text_to_speech(conversation, voice_1, voice_2)
164
- output_file = os.path.join(output_dir, f"raw_podcast_{int(time.time())}.mp3")
165
  self.combine_audio_files(audio_files, output_file)
166
  return text, output_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
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:
 
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)}")
78
+ print(f"Respuesta del modelo: {response_content}")
79
  raise RuntimeError(f"Failed to extract conversation: {str(e)}")
80
 
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}")
100
 
 
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").rstrip("=")
122
+ full_path = os.path.join(self.BASE_OUTPUT_DIR, f"podcast_{folder_name}")
123
+ os.makedirs(full_path, exist_ok=True)
124
+ return full_path
 
 
 
 
 
125
 
126
  def combine_audio_files(self, filenames: List[str], output_file: str) -> None:
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
+ conversation_json, voice_1, voice_2
157
+ )
158
+
159
+ final_output = os.path.join(folder_name, "combined_output.mp3")
160
+ self.combine_audio_files(audio_files, final_output)
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
+ conversation_json, voice_1, voice_2
171
+ )
172
+ final_output = os.path.join(folder_name, "combined_output.mp3")
173
+ self.combine_audio_files(audio_files, final_output)
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
+ """Modo sin LLM (texto directo)"""
178
  conversation = {
179
  "conversation": [
180
  {"speaker": "Host", "text": text},
181
  {"speaker": "Co-host", "text": "(Continuación del tema)"}
182
  ]
183
  }
184
+ audio_files, folder_name = await self.text_to_speech(conversation, voice_1, voice_2)
185
+ output_file = os.path.join(folder_name, "raw_podcast.mp3")
186
  self.combine_audio_files(audio_files, output_file)
187
  return text, output_file
188
+
189
+ def clean_old_files(self, max_age_seconds=86400):
190
+ """
191
+ Borra carpetas y archivos en BASE_OUTPUT_DIR que tengan más de max_age_seconds (por defecto 24h)
192
+ """
193
+ if not os.path.exists(self.BASE_OUTPUT_DIR):
194
+ return
195
+ now = time.time()
196
+ for folder in os.listdir(self.BASE_OUTPUT_DIR):
197
+ folder_path = os.path.join(self.BASE_OUTPUT_DIR, folder)
198
+ if os.path.isdir(folder_path):
199
+ try:
200
+ mtime = os.path.getmtime(folder_path)
201
+ if now - mtime > max_age_seconds:
202
+ # Borramos carpeta completa
203
+ for root, dirs, files in os.walk(folder_path, topdown=False):
204
+ for name in files:
205
+ os.remove(os.path.join(root, name))
206
+ for name in dirs:
207
+ os.rmdir(os.path.join(root, name))
208
+ os.rmdir(folder_path)
209
+ except Exception:
210
+ pass