AIPeterWorld commited on
Commit
11d45e4
1 Parent(s): f97faf9

Upload 19 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ h2ogpt.mp3 filter=lfs diff=lfs merge=lfs -text
37
+ h2ogpt.pdf filter=lfs diff=lfs merge=lfs -text
38
+ InformeGobiernoSpain.mp3 filter=lfs diff=lfs merge=lfs -text
39
+ ManualPatrimonio2023_es_es.mp3 filter=lfs diff=lfs merge=lfs -text
40
+ McKinsey_en.mp3 filter=lfs diff=lfs merge=lfs -text
41
+ MckinseyTrends2024.pdf filter=lfs diff=lfs merge=lfs -text
42
+ RealEstateOutlookMS.mp3 filter=lfs diff=lfs merge=lfs -text
43
+ RealEstateOutlookMS.pdf filter=lfs diff=lfs merge=lfs -text
Example_InformeGobiernoSpain.pdf ADDED
Binary file (158 kB). View file
 
Example_InformeGobiernoSpain.png ADDED
Example_ManualPatrimonio2023_es_es.pdf ADDED
Binary file (935 kB). View file
 
Example_ManualPatrimonio2023_es_es.png ADDED
Example_MckinseyTrends2024.png ADDED
Example_RealEstateOutlookMS.png ADDED
Example_h2ogpt.png ADDED
InformeGobiernoSpain.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1b2a09960381316ba2013eed6e7d74f4236e0c1da76a4261fa4b22b2de7faac
3
+ size 5083485
LICENSE.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Pedro Sánchez Alvarez ([email protected])
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ManualPatrimonio2023_es_es.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60fdabfba921bfb9ca3799ca357e92cbd620111cf9c34c649f8ba4cf43f4f9f8
3
+ size 3965997
McKinsey_en.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3febf5e956dfd49f352221c94567c2164322ecf3298941b0789adef8243984e9
3
+ size 4944453
MckinseyTrends2024.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07f358c91017001b254f0cd9d5f4bbcd9f80bc043d20c3afa72ec1d35b8634fe
3
+ size 8249334
README.md CHANGED
@@ -1,13 +1,18 @@
1
  ---
2
- title: Doc To Dialogue
3
- emoji: 🦀
4
- colorFrom: gray
5
- colorTo: pink
6
  sdk: gradio
7
  sdk_version: 4.41.0
8
  app_file: app.py
9
- pinned: false
10
  license: mit
 
 
 
11
  ---
 
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  ---
2
+ title: Doc To Interview Generator
3
+ emoji: 👀
4
+ colorFrom: yellow
5
+ colorTo: red
6
  sdk: gradio
7
  sdk_version: 4.41.0
8
  app_file: app.py
9
+ pinned: true
10
  license: mit
11
+ short_description: Transform a report or document into an interview/discussion
12
+ thumbnail: >-
13
+ https://cdn-uploads.huggingface.co/production/uploads/6485bbe375505dffa34d1aed/OdXvGT8yvrzl_kTbv7OBy.jpeg
14
  ---
15
+ ## License
16
 
17
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE.txt) file for details.
18
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
RealEstateOutlookMS.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b65dd2993715d8baf416c62c212093525b9b18511e02546503c9ff52b78ecfba
3
+ size 3415029
RealEstateOutlookMS.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d32e2fa8910070413529b874de6208570a80e94a98ff3e311d91c458d5c8847f
3
+ size 1066082
app (1).py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2024 Pedro Sánchez Alvarez ([email protected])
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+ #
7
+ # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+ #
9
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
11
+ import logging
12
+ import asyncio # Usar asyncio para operaciones asincrónicas
13
+ from datetime import datetime
14
+ import time
15
+ import json
16
+ import base64
17
+ import io
18
+ import re
19
+ import pandas as pd
20
+ from pathlib import Path
21
+ from pydub import AudioSegment
22
+ import openai
23
+ import google.generativeai as genai
24
+ import gradio as gr
25
+ import os
26
+ from tempfile import NamedTemporaryFile, TemporaryDirectory
27
+ from concurrent.futures import ThreadPoolExecutor
28
+ import aiofiles # Importar aiofiles para I/O asincrónico
29
+
30
+ # Configuración de claves API desde variables de entorno
31
+ openai.api_key = os.getenv('OPENAI_API_KEY')
32
+ genai.configure(api_key=os.getenv('GENAI_API_KEY'))
33
+
34
+ # Configuración de constantes globales
35
+ GENERATION_CONFIG = {
36
+ "temperature": 0.2,
37
+ "top_p": 0.95,
38
+ "top_k": 64,
39
+ "max_output_tokens": 8000,
40
+ "response_mime_type": "application/json",
41
+ }
42
+ MODEL_NAME = "gemini-1.5-flash"
43
+
44
+ # Configurar el logger
45
+ logging.basicConfig(
46
+ level=logging.INFO,
47
+ format='%(asctime)s - %(levelname)s - %(message)s'
48
+ )
49
+
50
+ def upload_to_gemini(path, mime_type=None):
51
+ """Sube el archivo dado a Gemini."""
52
+ file = genai.upload_file(path, mime_type=mime_type)
53
+ logging.info(f"Archivo '{file.display_name}' subido como: {file.uri}")
54
+ return file
55
+
56
+ async def wait_for_files_active(files, sleep_interval=5):
57
+ """Espera a que los archivos dados estén activos."""
58
+ logging.info("Esperando a que los archivos sean procesados...")
59
+ tasks = [check_file_status(file.name, sleep_interval) for file in files]
60
+ await asyncio.gather(*tasks)
61
+
62
+ async def check_file_status(name, sleep_interval):
63
+ """Comprueba el estado de un archivo y espera hasta que esté activo."""
64
+ file = genai.get_file(name)
65
+ while file.state.name == "PROCESSING":
66
+ await asyncio.sleep(sleep_interval)
67
+ file = genai.get_file(name)
68
+ if file.state.name != "ACTIVE":
69
+ raise Exception(f"El archivo {file.name} falló al procesarse")
70
+ logging.info(f"Archivo {file.name} está listo")
71
+
72
+ def process_json_response(response_text):
73
+ try:
74
+ return json.loads(response_text)
75
+ except json.JSONDecodeError:
76
+ return None
77
+
78
+ def get_chat_response(files, language):
79
+ model = genai.GenerativeModel(
80
+ model_name=MODEL_NAME,
81
+ generation_config=GENERATION_CONFIG,
82
+ )
83
+
84
+ chat_session = model.start_chat(
85
+ history=[
86
+ {
87
+ "role": "user",
88
+ "parts": [
89
+ files[0],
90
+ ],
91
+ },
92
+ ]
93
+ )
94
+
95
+ prompt = generate_prompt(language)
96
+ data = None
97
+ for attempt in range(2):
98
+ response = chat_session.send_message(prompt)
99
+ data = process_json_response(response.text)
100
+ if data is not None:
101
+ break
102
+ logging.warning("Error al procesar el JSON, reintentando...")
103
+
104
+ if data is None:
105
+ raise Exception("Error al procesar el JSON después de dos intentos.")
106
+
107
+ return data
108
+
109
+ def generate_prompt(language):
110
+ language = language.lower()
111
+ if language == "english":
112
+ return (
113
+ "Generate an in-depth and coherent interview in dialogue format between an interviewer (male) and a speaker (female) that accurately reflects the key aspects, "
114
+ "insights, and nuances of the provided document. The interview should include a brief introduction by the interviewer, followed by a series of thoughtful questions "
115
+ "and detailed responses, and conclude with a concise summary or conclusion by the interviewer. The output should be a single structured JSON array, where each element "
116
+ "is a JSON object with two fields: 'Speaker' for identifying the person speaking, and 'Content' for capturing their dialogue. Ensure the entire dialogue is contained "
117
+ "within this array, with each dialogue entry as an individual JSON object for clarity and easy parsing."
118
+ )
119
+ else:
120
+ return (
121
+ "Genera una entrevista en profundidad y coherente en formato de diálogo entre un entrevistador (hombre) y una ponente (mujer) que refleje con precisión los aspectos clave, "
122
+ "ideas y matices del documento proporcionado. La entrevista debe incluir una breve introducción por parte del entrevistador, seguida de una serie de preguntas reflexivas "
123
+ "y respuestas detalladas, y concluir con un resumen o conclusión concisa por parte del entrevistador. El resultado debe ser una única matriz JSON estructurada, donde cada "
124
+ "elemento sea un objeto JSON con dos campos: 'Speaker' para identificar a la persona que habla, y 'Content' para capturar su diálogo. Asegúrate de que todo el diálogo "
125
+ "esté contenido dentro de esta matriz, con cada entrada de diálogo como un objeto JSON individual para mayor claridad y facilidad de análisis."
126
+ )
127
+
128
+ async def generate_and_combine_audio_files(df_interview, output_dir, base_name):
129
+ voices = ["echo", "nova"]
130
+ combined = AudioSegment.empty()
131
+
132
+ with ThreadPoolExecutor() as executor:
133
+ tasks = []
134
+
135
+ for index, row in df_interview.iterrows():
136
+ tasks.append(executor.submit(generate_audio, index, row, voices, output_dir))
137
+
138
+ for task in tasks:
139
+ speech_file_path = await asyncio.wrap_future(task) # Corregido el uso para envolver el futuro
140
+ audio = AudioSegment.from_file(speech_file_path)
141
+ combined += audio
142
+
143
+ combined_file_path = output_dir / f"{base_name}.mp3"
144
+ combined.export(combined_file_path, format="mp3", bitrate="128k")
145
+ logging.info(f"Archivo de audio combinado guardado en {combined_file_path}")
146
+
147
+ return combined_file_path
148
+
149
+ def generate_audio(index, row, voices, output_dir):
150
+ texto = row['Content']
151
+ speech_file_path = output_dir / f"speech_{index + 1}.mp3"
152
+ voice = voices[index % len(voices)]
153
+
154
+ response = openai.audio.speech.create(
155
+ model="tts-1",
156
+ voice=voice,
157
+ response_format="mp3",
158
+ speed=1,
159
+ input=texto
160
+ )
161
+
162
+ with open(speech_file_path, 'wb') as f:
163
+ f.write(response.content)
164
+
165
+ return speech_file_path
166
+
167
+ async def main_async(pdf_file, language):
168
+ with TemporaryDirectory() as temp_dir:
169
+ temp_dir_path = Path(temp_dir)
170
+
171
+ # Guardar el contenido del archivo PDF en el directorio temporal
172
+ temp_pdf_path = temp_dir_path / "input.pdf"
173
+ pdf_content = pdf_file.read() if not isinstance(pdf_file, (str, Path)) else open(pdf_file, 'rb').read()
174
+
175
+ async with aiofiles.open(temp_pdf_path, 'wb') as f:
176
+ await f.write(pdf_content)
177
+
178
+ files = [upload_to_gemini(temp_pdf_path)]
179
+ await wait_for_files_active(files)
180
+
181
+ data = get_chat_response(files, language)
182
+
183
+ # Crear un DataFrame y guardarlo como CSV en el directorio temporal
184
+ df_interview = pd.DataFrame(data)
185
+ csv_file_path = temp_dir_path / "interview.csv"
186
+ df_interview.to_csv(csv_file_path, index=False)
187
+
188
+ # Generar y combinar archivos de audio en el directorio temporal
189
+ audio_output_dir = temp_dir_path / "audio_files"
190
+ audio_output_dir.mkdir(parents=True, exist_ok=True)
191
+ base_name = "combined_interview"
192
+ combined_audio_path = await generate_and_combine_audio_files(df_interview, audio_output_dir, base_name)
193
+
194
+ # Leer el archivo de audio combinado
195
+ async with aiofiles.open(combined_audio_path, 'rb') as f:
196
+ audio_content = await f.read()
197
+
198
+ return audio_content
199
+
200
+ def gradio_interface(pdf_file, language):
201
+ try:
202
+ # Llamada a la función principal que procesa el archivo y genera el audio
203
+ audio_content = asyncio.run(main_async(pdf_file, language))
204
+
205
+ # Guardar el contenido de audio directamente como MP3
206
+ with NamedTemporaryFile(delete=False, suffix='.mp3') as temp_audio:
207
+ temp_audio.write(audio_content)
208
+
209
+ return temp_audio.name
210
+ except Exception as e:
211
+ # Loguear el error para diagnóstico
212
+ logging.error(f"Error en el procesamiento: {str(e)}")
213
+
214
+ # Retornar un mensaje claro a la interfaz de usuario
215
+ return f"Error en el procesamiento: {str(e)}"
216
+
217
+ # Ejemplos preconfigurados para la sección Examples
218
+ example_data = [
219
+ {
220
+ "report_name": "<a href='https://huggingface.co/spaces/peter020202/Doc-To-Interview-Generator/blob/main/Example/MckinseyTrends2024.pdf'>Mckinsey Trends 2024 <br><br>[Report in English - Interview in English]</a>",
221
+ "image": "Example/MckinseyTrends2024.png",
222
+ "interview": "Example/McKinsey_en.mp3",
223
+ "report_pdf": "Example/MckinseyTrends2024.pdf",
224
+ },
225
+ {
226
+ "report_name": "<a href='https://huggingface.co/spaces/peter020202/Doc-To-Interview-Generator/blob/main/Example/h2ogpt.pdf'>h2oGPT: Democratizing Large Language Models <br><br>[Report in English - Interview in Spanish]</a>",
227
+ "image": "Example/h2ogpt.png",
228
+ "interview": "Example/h2ogpt.mp3",
229
+ "report_pdf": "Example/h2ogpt.pdf",
230
+ },
231
+ {
232
+ "report_name": "<a href='https://huggingface.co/spaces/peter020202/Doc-To-Interview-Generator/blob/main/Example/RealEstateOutlookMS.pdf'>Real Estate Outlook 2024 Morgan Stanley <br><br>[Report in English - Interview in English]</a>",
233
+ "image": "Example/RealEstateOutlookMS.png",
234
+ "interview": "Example/RealEstateOutlookMS.mp3",
235
+ "report_pdf": "Example/RealEstateOutlookMS.pdf",
236
+ },
237
+ {
238
+ "report_name": "<a href='https://huggingface.co/spaces/peter020202/Doc-To-Interview-Generator/blob/main/Example/ManualPatrimonio2023_es_es.pdf'>Manual de declaración de la Renta en España 2023 <br><br>[Report in Spanish - Interview in Spanish]</a>",
239
+ "image": "Example/ManualPatrimonio2023_es_es.png",
240
+ "interview": "Example/ManualPatrimonio2023_es_es.mp3",
241
+ "report_pdf": "Example/ManualPatrimonio2023_es_es.pdf",
242
+ },
243
+ ]
244
+
245
+ # Crear la interfaz
246
+
247
+ # Estilo CSS para centrar el contenido y limitar la altura de las filas
248
+ css = """
249
+ #title, #description {
250
+ text-align: center;
251
+ margin: auto;
252
+ width: 60%; /* Ajusta el ancho para móviles */
253
+ }
254
+ .example-row {
255
+ display: flex;
256
+ flex-direction: row; /* Coloca los elementos en fila */
257
+ align-items: center; /* Centra los elementos verticalmente */
258
+ justify-content: center; /* Centra los elementos horizontalmente */
259
+ margin-bottom: 20px; /* Espacio entre filas */
260
+ }
261
+ .example-row img {
262
+ width: 80%; /* Ajusta el ancho de la imagen */
263
+ max-width: 150px; /* Limita el ancho máximo */
264
+ margin-right: 10px; /* Espacio a la derecha de la imagen */
265
+ }
266
+ .example-row audio {
267
+ width: 60%; /* Ajusta el ancho del audio */
268
+ max-width: 150px; /* Limita el ancho máximo */
269
+ }
270
+ """
271
+
272
+ with gr.Blocks(css=css) as demo:
273
+ # Centrar el título y la descripción con CSS
274
+ gr.Markdown("# Doc-To-Interview Generator", elem_id="title")
275
+ gr.Markdown(
276
+ "Turn your documents—whether market or research reports, user guides, manuals, or others—into an engaging interview or discussion where the most relevant insights are summarized. Just upload a PDF and let us generate the final audio for you.<br><br>If you have any questions or encounter any issues, don't hesitate to contact me directly [here](https://www.linkedin.com/in/psanchezal/).",
277
+ elem_id="description"
278
+ )
279
+ gr.Markdown("<hr>") # Línea separadora en HTML
280
+
281
+ # Contenido principal con filas y columnas
282
+ with gr.Row():
283
+ with gr.Column():
284
+ pdf_input = gr.File(file_types=[".pdf"], label="Upload your PDF file")
285
+ language_input = gr.Dropdown(choices=["English", "Spanish"], label="Select the language for the interview", value="English")
286
+ generate_button = gr.Button("Generate Interview")
287
+
288
+ with gr.Column():
289
+ audio_output = gr.Audio(type="filepath", label="Audio-Generated Interview")
290
+
291
+ generate_button.click(gradio_interface, inputs=[pdf_input, language_input], outputs=audio_output)
292
+
293
+ gr.Markdown("<hr>") # Línea separadora en HTML
294
+ gr.Markdown("<hr>") # Línea separadora en HTML
295
+
296
+ gr.Markdown("## Examples") # Título de la sección de ejemplos
297
+
298
+ for example in example_data:
299
+ with gr.Row(elem_classes="example-row"):
300
+ gr.Markdown(f"**{example['report_name']}**")
301
+ gr.Image(value=example["image"], label="Image")
302
+ gr.Audio(value=example["interview"], label="Interview")
303
+
304
+ # Ejecutar la interfaz
305
+ demo.launch(share=True)
h2ogpt.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efbbaa21c1381aa5b61cbd7b3dc95413a5219e8ac97fbbbda754ca4bbc8c5e7f
3
+ size 3457029
h2ogpt.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aab1e002a4345aee87f224f13e9e8732a4adfa46f3f60bbe21641937935e5ecc
3
+ size 1019467
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ google-generativeai
3
+ gradio>=3.16.0
4
+ pandas
5
+ pydub
6
+ soundfile