gnosticdev commited on
Commit
2fb6f64
·
verified ·
1 Parent(s): add50a1

Update conver.py

Browse files
Files changed (1) hide show
  1. conver.py +13 -14
conver.py CHANGED
@@ -69,25 +69,27 @@ class URLToAudioConverter:
69
  f"Devuelve SOLO un objeto JSON: "
70
  f'{{"conversation": [{{"speaker": "Anfitrión1", "text": "..."}}, {{"speaker": "Anfitrión2", "text": "..."}}]}}'
71
  )
72
- print(f"Texto de entrada: {text[:200]}...")
73
  response = self.llm_client.chat.completions.create(
74
  messages=[{"role": "user", "content": prompt}],
75
  model=self.config.model_name,
76
  response_format={"type": "json_object"}
77
  )
78
  response_content = response.choices[0].message.content
79
- print(f"Respuesta cruda del modelo: {response_content[:500]}...")
80
-
81
  # Extract valid JSON using regex
82
  json_match = re.search(r'\{.*\}', response_content, re.DOTALL)
83
- if json_match:
84
- json_str = json_match.group(0)
85
- else:
86
  raise ValueError("No valid JSON object found in response")
87
-
88
- dialogue = json.loads(json_str)
 
 
 
 
 
89
  if not dialogue.get("conversation"):
90
- print("Error: No valid conversation generated.")
91
  return dialogue
92
  except Exception as e:
93
  raise RuntimeError(f"Failed to parse dialogue: {str(e)}")
@@ -101,7 +103,6 @@ class URLToAudioConverter:
101
  for i, turn in enumerate(conversation_json["conversation"]):
102
  filename = output_dir / f"segment_{i}.mp3"
103
  voice = voice_1 if turn["speaker"] == "Anfitrión1" else voice_2
104
- print(f"Generando audio para {turn['speaker']}: {turn['text'][:50]}... con voz {voice}")
105
  tmp_path = await self._generate_audio(turn["text"], voice)
106
  os.rename(tmp_path, filename)
107
  filenames.append(str(filename))
@@ -144,12 +145,10 @@ class URLToAudioConverter:
144
  tags_paths: List[str],
145
  custom_music_path: str = None
146
  ) -> AudioSegment:
147
- # Use predefined paths if no custom path is provided
148
  music_file = custom_music_path if custom_music_path and os.path.exists(custom_music_path) else self.MUSICA_FONDO
149
  tag_outro_file = self.TAG1
150
  tag_trans_file = self.TAG2
151
 
152
- # Check if files exist
153
  if not os.path.exists(music_file):
154
  raise FileNotFoundError(f"Music file not found: {music_file}")
155
  if not os.path.exists(tag_outro_file):
@@ -201,8 +200,8 @@ class URLToAudioConverter:
201
  combined = self.combine_audio_files(audio_files)
202
  final_audio = self.add_background_music_and_tags(
203
  combined,
204
- self.MUSICA_FONDO, # Use instance variable
205
- [self.TAG1, self.TAG2], # Use instance variables
206
  custom_music_path
207
  )
208
  output_path = os.path.join(folder_name, "podcast_final.mp3")
 
69
  f"Devuelve SOLO un objeto JSON: "
70
  f'{{"conversation": [{{"speaker": "Anfitrión1", "text": "..."}}, {{"speaker": "Anfitrión2", "text": "..."}}]}}'
71
  )
 
72
  response = self.llm_client.chat.completions.create(
73
  messages=[{"role": "user", "content": prompt}],
74
  model=self.config.model_name,
75
  response_format={"type": "json_object"}
76
  )
77
  response_content = response.choices[0].message.content
78
+ # Clean response to ensure valid JSON
79
+ response_content = response_content.strip()
80
  # Extract valid JSON using regex
81
  json_match = re.search(r'\{.*\}', response_content, re.DOTALL)
82
+ if not json_match:
 
 
83
  raise ValueError("No valid JSON object found in response")
84
+ json_str = json_match.group(0)
85
+ # Replace any problematic characters
86
+ json_str = json_str.replace('\n', '').replace('\r', '')
87
+ try:
88
+ dialogue = json.loads(json_str)
89
+ except json.JSONDecodeError as e:
90
+ raise ValueError(f"JSON parsing failed: {str(e)}")
91
  if not dialogue.get("conversation"):
92
+ raise ValueError("No valid conversation generated")
93
  return dialogue
94
  except Exception as e:
95
  raise RuntimeError(f"Failed to parse dialogue: {str(e)}")
 
103
  for i, turn in enumerate(conversation_json["conversation"]):
104
  filename = output_dir / f"segment_{i}.mp3"
105
  voice = voice_1 if turn["speaker"] == "Anfitrión1" else voice_2
 
106
  tmp_path = await self._generate_audio(turn["text"], voice)
107
  os.rename(tmp_path, filename)
108
  filenames.append(str(filename))
 
145
  tags_paths: List[str],
146
  custom_music_path: str = None
147
  ) -> AudioSegment:
 
148
  music_file = custom_music_path if custom_music_path and os.path.exists(custom_music_path) else self.MUSICA_FONDO
149
  tag_outro_file = self.TAG1
150
  tag_trans_file = self.TAG2
151
 
 
152
  if not os.path.exists(music_file):
153
  raise FileNotFoundError(f"Music file not found: {music_file}")
154
  if not os.path.exists(tag_outro_file):
 
200
  combined = self.combine_audio_files(audio_files)
201
  final_audio = self.add_background_music_and_tags(
202
  combined,
203
+ self.MUSICA_FONDO,
204
+ [self.TAG1, self.TAG2],
205
  custom_music_path
206
  )
207
  output_path = os.path.join(folder_name, "podcast_final.mp3")