Cristobal299 commited on
Commit
ec0f4cb
·
verified ·
1 Parent(s): 4bc4474

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +253 -0
app.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import json
4
+ import tempfile
5
+ import datetime
6
+ import requests
7
+ from pathlib import Path
8
+
9
+ import gradio as gr
10
+ from PyPDF2 import PdfReader
11
+ from pydub import AudioSegment
12
+
13
+ from gradio_theme_fenix import apply_fenix_theme, FENIX_CSS, fenix_header, fenix_footer
14
+
15
+ # ----------------------------------------------------------------------
16
+ # Configuration (read from environment)
17
+ # ----------------------------------------------------------------------
18
+ ELEVENLABS_API_KEY = os.environ.get("ELEVENLABS_API_KEY")
19
+ ELEVENLABS_VOICE_ID = os.environ.get("ELEVENLABS_VOICE_ID") # voice for "Álvaro España"
20
+ MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
21
+ HISTORY_FILE = Path("history.json")
22
+ MAX_HISTORY = 5
23
+
24
+ # ----------------------------------------------------------------------
25
+ # Helper functions
26
+ # ----------------------------------------------------------------------
27
+ def load_history():
28
+ if HISTORY_FILE.exists():
29
+ try:
30
+ with open(HISTORY_FILE, "r", encoding="utf-8") as f:
31
+ return json.load(f)
32
+ except Exception:
33
+ return []
34
+ return []
35
+
36
+ def save_history(entry):
37
+ history = load_history()
38
+ history.insert(0, entry) # newest first
39
+ history = history[:MAX_HISTORY]
40
+ with open(HISTORY_FILE, "w", encoding="utf-8") as f:
41
+ json.dump(history, f, ensure_ascii=False, indent=2)
42
+
43
+ def extract_text_from_pdf(pdf_path: str, progress=gr.Progress()):
44
+ """
45
+ Extracts text from a PDF file preserving reading order.
46
+ """
47
+ progress(0, desc="Opening PDF")
48
+ try:
49
+ reader = PdfReader(pdf_path)
50
+ text_pages = []
51
+ total_pages = len(reader.pages)
52
+ for i, page in enumerate(reader.pages):
53
+ text_pages.append(page.extract_text() or "")
54
+ progress((i + 1) / total_pages, desc=f"Extracting page {i+1}/{total_pages}")
55
+ full_text = "\n".join(text_pages).strip()
56
+ return full_text
57
+ except Exception as e:
58
+ raise RuntimeError(f"Error extracting PDF: {str(e)}")
59
+
60
+ def call_elevenlabs_tts(text: str, tone: str, speed: float, progress=gr.Progress()):
61
+ """
62
+ Calls ElevenLabs TTS API to generate MP3 audio.
63
+ """
64
+ if not ELEVENLABS_API_KEY or not ELEVENLABS_VOICE_ID:
65
+ raise RuntimeError("ElevenLabs API key or voice ID not configured.")
66
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVENLABS_VOICE_ID}"
67
+ headers = {
68
+ "xi-api-key": ELEVENLABS_API_KEY,
69
+ "Content-Type": "application/json"
70
+ }
71
+
72
+ # Voice settings: adjust pitch and stability for "sagrado" tone
73
+ voice_settings = {
74
+ "stability": 0.75,
75
+ "similarity_boost": 0.75,
76
+ "speed": speed
77
+ }
78
+ if tone == "sagrado":
79
+ voice_settings.update({
80
+ "stability": 0.9,
81
+ "similarity_boost": 0.9,
82
+ "pitch": 1.2 # higher pitch for sacred tone
83
+ })
84
+
85
+ payload = {
86
+ "text": text,
87
+ "voice_settings": voice_settings,
88
+ "model_id": "eleven_multilingual_v2"
89
+ }
90
+
91
+ # Retry logic (max 2 retries)
92
+ for attempt in range(2):
93
+ try:
94
+ progress(0.2, desc="Sending request to TTS")
95
+ response = requests.post(url, headers=headers, json=payload, timeout=30)
96
+ if response.status_code == 200:
97
+ progress(0.8, desc="Receiving audio")
98
+ return response.content
99
+ else:
100
+ raise RuntimeError(f"TTS API error {response.status_code}: {response.text}")
101
+ except Exception as e:
102
+ if attempt == 1:
103
+ raise RuntimeError(f"TTS request failed after retries: {str(e)}")
104
+ # wait a moment before retry
105
+ progress(0.5, desc=f"Retry {attempt+1}/2")
106
+ raise RuntimeError("Unexpected flow in TTS generation.")
107
+
108
+ def generate_audio(pdf_file, tone, speed, progress=gr.Progress()):
109
+ """
110
+ Main pipeline: extract text -> generate audio -> save MP3 -> update history.
111
+ Returns path to MP3 file and a dict for history display.
112
+ """
113
+ if pdf_file is None:
114
+ raise gr.Error("Please upload a PDF file.")
115
+ if pdf_file.size > MAX_FILE_SIZE:
116
+ raise gr.Error("File exceeds maximum size of 10 MB.")
117
+
118
+ # Save uploaded PDF to a temporary file
119
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
120
+ tmp_pdf.write(pdf_file.read())
121
+ pdf_path = tmp_pdf.name
122
+
123
+ # Step 1: Extract text
124
+ progress(0.0, desc="Extracting text")
125
+ text = extract_text_from_pdf(pdf_path, progress=progress)
126
+ if not text:
127
+ raise gr.Error("No readable text found in the PDF.")
128
+
129
+ # Step 2: Generate audio via ElevenLabs
130
+ progress(0.3, desc="Generating audio")
131
+ audio_bytes = call_elevenlabs_tts(text, tone, speed, progress=progress)
132
+
133
+ # Step 3: Save MP3 to temporary file
134
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_mp3:
135
+ tmp_mp3.write(audio_bytes)
136
+ mp3_path = tmp_mp3.name
137
+
138
+ # Step 4: Gather metadata for history
139
+ file_name = Path(pdf_file.name).name
140
+ duration_sec = AudioSegment.from_file(mp3_path).duration_seconds
141
+ entry = {
142
+ "filename": file_name,
143
+ "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
144
+ "duration": f"{duration_sec:.1f}s",
145
+ "audio_path": mp3_path
146
+ }
147
+ save_history(entry)
148
+
149
+ # Clean up PDF temp file
150
+ try:
151
+ os.remove(pdf_path)
152
+ except Exception:
153
+ pass
154
+
155
+ return mp3_path, entry
156
+
157
+ def load_history_for_ui():
158
+ """
159
+ Returns a list of rows for the history Dataframe.
160
+ """
161
+ history = load_history()
162
+ rows = [
163
+ [h["filename"], h["date"], h["duration"]]
164
+ for h in history
165
+ ]
166
+ return rows
167
+
168
+ def play_from_history(index):
169
+ """
170
+ Returns the audio file path for the selected history entry.
171
+ """
172
+ history = load_history()
173
+ if 0 <= index < len(history):
174
+ return history[index]["audio_path"]
175
+ raise gr.Error("Invalid history selection.")
176
+
177
+ # ----------------------------------------------------------------------
178
+ # Gradio Interface
179
+ # ----------------------------------------------------------------------
180
+ with gr.Blocks(css=FENIX_CSS, theme=apply_fenix_theme(), title="PDF Voice Reader") as demo:
181
+ fenix_header("PDF Voice Reader", "Convert PDF to audio with sacred tone")
182
+
183
+ with gr.Row():
184
+ # Left column: main workflow
185
+ with gr.Column(scale=3):
186
+ pdf_input = gr.File(label="PDF file", file_types=[".pdf"], type="file")
187
+ tone_radio = gr.Radio(
188
+ choices=["normal", "sagrado"],
189
+ label="Select tone",
190
+ value="normal"
191
+ )
192
+ speed_slider = gr.Slider(
193
+ minimum=0.75,
194
+ maximum=1.25,
195
+ step=0.25,
196
+ label="Reading speed",
197
+ value=1.0
198
+ )
199
+ generate_btn = gr.Button("Generar Audio", variant="primary")
200
+ audio_output = gr.Audio(label="Audio result", type="filepath")
201
+ download_btn = gr.File(label="Descargar MP3", visible=False)
202
+
203
+ # Progress bar (hidden until used)
204
+ progress_bar = gr.ProgressBar(visible=False)
205
+
206
+ # Callback chain
207
+ def on_generate(pdf_file, tone, speed):
208
+ progress_bar.visible = True
209
+ mp3_path, entry = generate_audio(pdf_file, tone, speed, progress=progress_bar)
210
+ download_btn.visible = True
211
+ download_btn.update(value=mp3_path, label="Descargar MP3")
212
+ return mp3_path, entry
213
+
214
+ generate_btn.click(
215
+ fn=on_generate,
216
+ inputs=[pdf_input, tone_radio, speed_slider],
217
+ outputs=[audio_output, None],
218
+ api_name=False
219
+ )
220
+
221
+ # Right column: history
222
+ with gr.Column(scale=2):
223
+ gr.Markdown("## Historial (últimos 5 PDFs)")
224
+ history_df = gr.Dataframe(
225
+ headers=["Archivo", "Fecha", "Duración"],
226
+ datatype=["str", "str", "str"],
227
+ row_count=MAX_HISTORY,
228
+ column_count=3,
229
+ interactive=False,
230
+ label="Historial"
231
+ )
232
+ play_btn = gr.Button("Reproducir seleccionado")
233
+ history_audio = gr.Audio(label="Audio del historial", type="filepath")
234
+
235
+ # Load history initially
236
+ history_df.load(fn=load_history_for_ui)
237
+
238
+ def on_play(selected):
239
+ if selected is None or len(selected) == 0:
240
+ raise gr.Error("Seleccione una fila del historial.")
241
+ # selected is a list of row indices; take first
242
+ idx = selected[0]
243
+ return play_from_history(idx)
244
+
245
+ play_btn.click(
246
+ fn=on_play,
247
+ inputs=[history_df.select],
248
+ outputs=history_audio
249
+ )
250
+
251
+ fenix_footer()
252
+
253
+ demo.launch()