Update app.py
Browse files
app.py
CHANGED
@@ -1,195 +1,118 @@
|
|
1 |
-
# =============================================================
|
2 |
-
# Hugging Face Space – Lecture → Multilingual Podcast Generator
|
3 |
-
# =============================================================
|
4 |
-
#
|
5 |
-
#
|
6 |
-
#
|
7 |
-
#
|
8 |
-
# -----------------------------------------------------------------
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
import
|
17 |
-
import
|
18 |
-
import
|
19 |
-
import
|
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 |
-
dialogue = response.text.strip()
|
120 |
-
except Exception as e:
|
121 |
-
dialogue = f"Error generating dialogue in {lang}: {e}"
|
122 |
-
return dialogue
|
123 |
-
|
124 |
-
|
125 |
-
def tts_for_dialogue(lang: str, text: str) -> Tuple[str, str]:
|
126 |
-
"""Convert text to speech via HF TTS; returns (filepath, mime)."""
|
127 |
-
language_code = LANG_CONFIG[lang]["tts_lang"]
|
128 |
-
tmpdir = tempfile.gettempdir()
|
129 |
-
filename = os.path.join(tmpdir, f"{lang}_{uuid.uuid4().hex}.wav")
|
130 |
-
try:
|
131 |
-
# xtts_v2 accepts a `language` forward param
|
132 |
-
speech = tts_pipeline(text, forward_params={"language": language_code})
|
133 |
-
sf.write(filename, speech["audio"], speech["sampling_rate"])
|
134 |
-
return filename, "audio/wav"
|
135 |
-
except Exception as e:
|
136 |
-
# Return dummy text file explaining error
|
137 |
-
errfile = os.path.join(tmpdir, f"err_{uuid.uuid4().hex}.txt")
|
138 |
-
with open(errfile, "w", encoding="utf-8") as fh:
|
139 |
-
fh.write(f"TTS error for {lang}: {e}\n")
|
140 |
-
return errfile, "text/plain"
|
141 |
-
|
142 |
-
|
143 |
-
def pipeline_runner(pdf_file) -> Dict[str, Tuple[str, str]]:
|
144 |
-
"""Full pipeline returning a dict: language → (file_path, mime)."""
|
145 |
-
if pdf_file is None:
|
146 |
-
raise gr.Error("Please upload a PDF lecture first.")
|
147 |
-
lecture_text = extract_text(pdf_file)
|
148 |
-
|
149 |
-
audio_outputs = {}
|
150 |
-
for lang in LANG_CONFIG.keys():
|
151 |
-
dialogue = generate_dialogue(lecture_text, lang)
|
152 |
-
path, mime = tts_for_dialogue(lang, dialogue)
|
153 |
-
audio_outputs[lang] = (path, mime)
|
154 |
-
return audio_outputs
|
155 |
-
|
156 |
-
|
157 |
-
# ------------------------ Gradio UI --------------------------------
|
158 |
-
|
159 |
-
with gr.Blocks(title="Multilingual Lecture Podcast (LLM + HF‑TTS)") as demo:
|
160 |
-
gr.Markdown(
|
161 |
-
"""# 📚🎙️ Lecture → Podcast
|
162 |
-
Upload a lecture PDF and receive a two‑host audio podcast generated **directly** in five languages using Qwen for text and XTTS‑v2 for speech.
|
163 |
-
"""
|
164 |
-
)
|
165 |
-
with gr.Row():
|
166 |
-
inp = gr.File(label="Lecture PDF", file_types=[".pdf"])
|
167 |
-
btn = gr.Button("Generate Podcast")
|
168 |
-
with gr.Group():
|
169 |
-
audio_components = [
|
170 |
-
gr.Audio(label=lang, interactive=False, type="filepath")
|
171 |
-
for lang in LANG_CONFIG.keys()
|
172 |
-
]
|
173 |
-
|
174 |
-
|
175 |
-
def gradio_wrapper(pdf_file):
|
176 |
-
results = pipeline_runner(pdf_file)
|
177 |
-
return [results[lang][0] for lang in LANG_CONFIG.keys()]
|
178 |
-
|
179 |
-
|
180 |
-
btn.click(gradio_wrapper, inputs=inp, outputs=audio_components)
|
181 |
-
|
182 |
-
if __name__ == "__main__":
|
183 |
-
demo.launch()
|
184 |
-
|
185 |
-
# ---------------------------------------------------------------
|
186 |
-
# requirements.txt (commit as separate file in the Space root)
|
187 |
-
# ---------------------------------------------------------------
|
188 |
-
# gradio>=4.28.0
|
189 |
-
# PyPDF2>=3.0.1
|
190 |
-
# nltk>=3.8.1
|
191 |
-
# transformers>=4.39.0
|
192 |
-
# torch>=2.1.2
|
193 |
-
# soundfile>=0.12.1
|
194 |
-
# llama-index>=0.11.47
|
195 |
-
# huggingface-hub>=0.23.0
|
|
|
1 |
+
# =============================================================
|
2 |
+
# Hugging Face Space – Lecture → Multilingual Podcast Generator
|
3 |
+
# =============================================================
|
4 |
+
# Uses SmolAgents HfApiModel for text generation and HF audio
|
5 |
+
# pipeline for speech. Generates two‑host dialogues in five
|
6 |
+
# languages (English, Bangla, Chinese, Urdu, Nepali) directly
|
7 |
+
# from a PDF lecture upload.
|
8 |
+
# -----------------------------------------------------------------
|
9 |
+
|
10 |
+
import os
|
11 |
+
import tempfile
|
12 |
+
import uuid
|
13 |
+
import textwrap
|
14 |
+
from typing import List, Dict
|
15 |
+
|
16 |
+
import gradio as gr
|
17 |
+
from PyPDF2 import PdfReader
|
18 |
+
from transformers import pipeline # for audio generation (e.g., xtts)
|
19 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
20 |
+
|
21 |
+
# ------------------------------------------------------------------
|
22 |
+
# LLM configuration (SmolAgents wrapper for HF Inference API)
|
23 |
+
# ------------------------------------------------------------------
|
24 |
+
llm = HfApiModel(
|
25 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # 34B parameter instruct model
|
26 |
+
max_tokens=2096,
|
27 |
+
temperature=0.5,
|
28 |
+
custom_role_conversions=None,
|
29 |
+
)
|
30 |
+
|
31 |
+
# ------------------------------------------------------------------
|
32 |
+
# Audio model (multilingual text ➜ speech); choose an open xtts‑v2
|
33 |
+
# model that supports our languages. Switch model id if you prefer.
|
34 |
+
# ------------------------------------------------------------------
|
35 |
+
audio_pipe = pipeline(
|
36 |
+
"text-to-audio",
|
37 |
+
model="suno/xtts_v2",
|
38 |
+
framework="pt",
|
39 |
+
)
|
40 |
+
|
41 |
+
LANG_INFO: Dict[str, Dict[str, str]] = {
|
42 |
+
"en": {"name": "English", "speaker": "hostA"},
|
43 |
+
"bn": {"name": "Bangla", "speaker": "hostB"},
|
44 |
+
"zh": {"name": "Chinese", "speaker": "hostC"},
|
45 |
+
"ur": {"name": "Urdu", "speaker": "hostD"},
|
46 |
+
"ne": {"name": "Nepali", "speaker": "hostE"},
|
47 |
+
}
|
48 |
+
|
49 |
+
PROMPT_TEMPLATE = textwrap.dedent(
|
50 |
+
"""
|
51 |
+
You are producing a lively two‑host educational podcast in {lang_name}.
|
52 |
+
Summarize the following lecture content into a dialogue of about 1200 words.
|
53 |
+
Use an engaging style: hosts ask each other questions, clarify ideas, add
|
54 |
+
simple analogies, and conclude with a short recap. Keep technical accuracy.
|
55 |
+
|
56 |
+
### Lecture Content
|
57 |
+
{content}
|
58 |
+
"""
|
59 |
+
)
|
60 |
+
|
61 |
+
# ------------------------------------------------------------------
|
62 |
+
# Utility: extract & truncate PDF text to fit LLM token budget
|
63 |
+
# ------------------------------------------------------------------
|
64 |
+
|
65 |
+
def extract_pdf_text(pdf_file) -> str:
|
66 |
+
reader = PdfReader(pdf_file)
|
67 |
+
raw = "\n".join(p.extract_text() or "" for p in reader.pages)
|
68 |
+
return raw
|
69 |
+
|
70 |
+
TOKEN_LIMIT = 6000 # conservative words (≈ tokens) for prompt+response
|
71 |
+
|
72 |
+
|
73 |
+
def truncate_text(text: str, limit: int = TOKEN_LIMIT) -> str:
|
74 |
+
words = text.split()
|
75 |
+
return " ".join(words[:limit])
|
76 |
+
|
77 |
+
# ------------------------------------------------------------------
|
78 |
+
# Main generation function
|
79 |
+
# ------------------------------------------------------------------
|
80 |
+
|
81 |
+
def generate_podcast(pdf: gr.File) -> List[gr.Audio]:
|
82 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
83 |
+
lecture_text = truncate_text(extract_pdf_text(pdf.name))
|
84 |
+
audio_outputs = []
|
85 |
+
for lang_code, info in LANG_INFO.items():
|
86 |
+
prompt = PROMPT_TEMPLATE.format(lang_name=info["name"], content=lecture_text)
|
87 |
+
# --- Generate dialogue ---
|
88 |
+
dialogue = llm(prompt)
|
89 |
+
|
90 |
+
# Save text for transparency/debug
|
91 |
+
text_path = os.path.join(tmpdir, f"podcast_{lang_code}.txt")
|
92 |
+
with open(text_path, "w", encoding="utf-8") as f:
|
93 |
+
f.write(dialogue)
|
94 |
+
|
95 |
+
# --- TTS ---
|
96 |
+
audio = audio_pipe(dialogue, forward_params={"language": lang_code})
|
97 |
+
wav_path = os.path.join(tmpdir, f"podcast_{lang_code}.wav")
|
98 |
+
audio["audio"].export(wav_path, format="wav")
|
99 |
+
audio_outputs.append((wav_path, None)) # Gradio Audio expects (file, label)
|
100 |
+
|
101 |
+
return audio_outputs
|
102 |
+
|
103 |
+
# ------------------------------------------------------------------
|
104 |
+
# Gradio Interface
|
105 |
+
# ------------------------------------------------------------------
|
106 |
+
|
107 |
+
audio_components = [gr.Audio(label=f"{info['name']} Podcast", type="filepath") for info in LANG_INFO.values()]
|
108 |
+
|
109 |
+
iface = gr.Interface(
|
110 |
+
fn=generate_podcast,
|
111 |
+
inputs=gr.File(label="Upload Lecture PDF", file_types=[".pdf"]),
|
112 |
+
outputs=audio_components,
|
113 |
+
title="Lecture → Multilingual Podcast Generator",
|
114 |
+
description="Upload a lecture PDF and get a two‑host audio podcast in English, Bangla, Chinese, Urdu, and Nepali."
|
115 |
+
)
|
116 |
+
|
117 |
+
if __name__ == "__main__":
|
118 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|