File size: 8,385 Bytes
5fe16b1
15d0727
5fe16b1
 
 
 
 
 
 
 
 
71a491a
5fe16b1
 
 
 
 
 
 
 
eb823dc
 
5fe16b1
 
 
 
eb823dc
 
 
 
 
5fe16b1
 
 
 
71a491a
 
 
 
 
 
 
 
5fe16b1
 
71a491a
 
 
 
 
 
 
 
 
eb823dc
71a491a
 
 
 
 
eb823dc
71a491a
 
eb823dc
71a491a
 
 
 
eb823dc
71a491a
 
 
 
eb823dc
71a491a
 
 
eb823dc
71a491a
5fe16b1
 
eb823dc
5fe16b1
eb823dc
71a491a
 
eb823dc
71a491a
eb823dc
71a491a
 
 
eb823dc
71a491a
eb823dc
 
 
71a491a
 
5fe16b1
 
71a491a
 
 
 
eb823dc
5fe16b1
 
 
 
eb823dc
885ea0a
5fe16b1
 
eb823dc
5fe16b1
 
 
eb823dc
 
 
 
 
 
5fe16b1
 
71a491a
 
eb823dc
71a491a
 
 
eb823dc
 
 
71a491a
eb823dc
 
 
71a491a
 
5fe16b1
41484d1
5fe16b1
eb823dc
5fe16b1
 
71a491a
eb823dc
5fe16b1
71a491a
 
 
5fe16b1
eb823dc
 
 
 
 
 
 
41484d1
 
eb823dc
41484d1
71a491a
 
 
eb823dc
 
 
 
 
 
bf07215
 
eb823dc
71a491a
 
 
 
 
 
eb823dc
 
71a491a
 
eb823dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from dataclasses import dataclass
from typing import List, Tuple, Dict
import os
import httpx
import json
from openai import OpenAI
import edge_tts
import tempfile
from pydub import AudioSegment
import base64
from pathlib import Path
import time

@dataclass
class ConversationConfig:
    max_words: int = 3000
    prefix_url: str = "https://r.jina.ai/"
    model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"

class URLToAudioConverter:
    BASE_OUTPUT_DIR = "outputs"

    def __init__(self, config: ConversationConfig, llm_api_key: str):
        self.config = config
        self.llm_client = OpenAI(api_key=llm_api_key, base_url="https://api.together.xyz/v1")
        self.llm_out = None
        self._ensure_base_output_dir()

    def _ensure_base_output_dir(self):
        if not os.path.exists(self.BASE_OUTPUT_DIR):
            os.makedirs(self.BASE_OUTPUT_DIR, exist_ok=True)

    def fetch_text(self, url: str) -> str:
        if not url:
            raise ValueError("URL cannot be empty")

        full_url = f"{self.config.prefix_url}{url}"
        try:
            response = httpx.get(full_url, timeout=60.0)
            response.raise_for_status()
            return response.text
        except httpx.HTTPError as e:
            raise RuntimeError(f"Failed to fetch URL: {e}")

    def extract_conversation(self, text: str) -> Dict:
        if not text:
            raise ValueError("Input text cannot be empty")

        try:
            prompt = (
                f"{text}\nConvert the provided text into a short informative podcast conversation "
                f"between two experts. Return ONLY a JSON object with the following structure:\n"
                '{"conversation": [{"speaker": "Speaker1", "text": "..."}, {"speaker": "Speaker2", "text": "..."}]}'
            )

            chat_completion = self.llm_client.chat.completions.create(
                messages=[{"role": "user", "content": prompt}],
                model=self.config.model_name,
                response_format={"type": "json_object"}
            )

            response_content = chat_completion.choices[0].message.content
            json_str = response_content.strip()

            if not json_str.startswith('{'):
                start = json_str.find('{')
                if start != -1:
                    json_str = json_str[start:]

            if not json_str.endswith('}'):
                end = json_str.rfind('}')
                if end != -1:
                    json_str = json_str[:end+1]

            return json.loads(json_str)
        except Exception as e:
            print(f"Error en extract_conversation: {str(e)}")
            print(f"Respuesta del modelo: {response_content}")
            raise RuntimeError(f"Failed to extract conversation: {str(e)}")

    async def text_to_speech(self, conversation_json: Dict, voice_1: str, voice_2: str) -> Tuple[List[str], str]:
        output_dir = Path(self._create_output_directory())
        filenames = []

        try:
            for i, turn in enumerate(conversation_json["conversation"]):
                filename = output_dir / f"output_{i}.mp3"
                voice = voice_1 if i % 2 == 0 else voice_2

                tmp_path, error = await self._generate_audio(turn["text"], voice)
                if error:
                    raise RuntimeError(f"Text-to-speech failed: {error}")

                os.rename(tmp_path, filename)
                filenames.append(str(filename))

            return filenames, str(output_dir)
        except Exception as e:
            raise RuntimeError(f"Failed to convert text to speech: {e}")

    async def _generate_audio(self, text: str, voice: str, rate: int = 0, pitch: int = 0) -> Tuple[str, str]:
        if not text.strip():
            return None, "Text cannot be empty"
        if not voice:
            return None, "Voice cannot be empty"

        voice_short_name = voice.split(" - ")[0]
        rate_str = f"{rate:+d}%"
        pitch_str = f"{pitch:+d}Hz"
        communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)

        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
            tmp_path = tmp_file.name
            await communicate.save(tmp_path)

        return tmp_path, None

    def _create_output_directory(self) -> str:
        # Crear carpeta única dentro de outputs/
        random_bytes = os.urandom(8)
        folder_name = base64.urlsafe_b64encode(random_bytes).decode("utf-8").rstrip("=")
        full_path = os.path.join(self.BASE_OUTPUT_DIR, f"podcast_{folder_name}")
        os.makedirs(full_path, exist_ok=True)
        return full_path

    def combine_audio_files(self, filenames: List[str], output_file: str) -> None:
        if not filenames:
            raise ValueError("No input files provided")

        try:
            combined = AudioSegment.empty()
            for filename in filenames:
                audio_segment = AudioSegment.from_file(filename, format="mp3")
                combined += audio_segment

            combined.export(output_file, format="mp3")

            # NO eliminar archivos aquí. Solo en limpieza periódica.

        except Exception as e:
            raise RuntimeError(f"Failed to combine audio files: {e}")

    async def url_to_audio(self, url: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
        text = self.fetch_text(url)

        words = text.split()
        if len(words) > self.config.max_words:
            text = " ".join(words[:self.config.max_words])

        conversation_json = self.extract_conversation(text)
        conversation_text = "\n".join(
            f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
        )
        self.llm_out = conversation_json
        audio_files, folder_name = await self.text_to_speech(
            conversation_json, voice_1, voice_2
        )

        final_output = os.path.join(folder_name, "combined_output.mp3")
        self.combine_audio_files(audio_files, final_output)
        return final_output, conversation_text

    async def text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
        """Procesamiento normal con LLM"""
        conversation_json = self.extract_conversation(text)
        conversation_text = "\n".join(
            f"{turn['speaker']}: {turn['text']}" for turn in conversation_json["conversation"]
        )
        audio_files, folder_name = await self.text_to_speech(
            conversation_json, voice_1, voice_2
        )
        final_output = os.path.join(folder_name, "combined_output.mp3")
        self.combine_audio_files(audio_files, final_output)
        return final_output, conversation_text

    async def raw_text_to_audio(self, text: str, voice_1: str, voice_2: str) -> Tuple[str, str]:
        """Modo sin LLM (texto directo)"""
        conversation = {
            "conversation": [
                {"speaker": "Host", "text": text},
                {"speaker": "Co-host", "text": "(Continuación del tema)"}
            ]
        }
        audio_files, folder_name = await self.text_to_speech(conversation, voice_1, voice_2)
        output_file = os.path.join(folder_name, "raw_podcast.mp3")
        self.combine_audio_files(audio_files, output_file)
        return text, output_file

    def clean_old_files(self, max_age_seconds=86400):
        """
        Borra carpetas y archivos en BASE_OUTPUT_DIR que tengan más de max_age_seconds (por defecto 24h)
        """
        if not os.path.exists(self.BASE_OUTPUT_DIR):
            return
        now = time.time()
        for folder in os.listdir(self.BASE_OUTPUT_DIR):
            folder_path = os.path.join(self.BASE_OUTPUT_DIR, folder)
            if os.path.isdir(folder_path):
                try:
                    mtime = os.path.getmtime(folder_path)
                    if now - mtime > max_age_seconds:
                        # Borramos carpeta completa
                        for root, dirs, files in os.walk(folder_path, topdown=False):
                            for name in files:
                                os.remove(os.path.join(root, name))
                            for name in dirs:
                                os.rmdir(os.path.join(root, name))
                        os.rmdir(folder_path)
                except Exception:
                    pass