Spaces:
Runtime error
Runtime error
File size: 22,385 Bytes
e825bb5 7ea6fbe 7c2eb0d e825bb5 04a5353 e825bb5 04a5353 dd95ce1 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 7ea6fbe 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 7ea6fbe 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 cbad0ce 04a5353 cbad0ce 04a5353 cbad0ce 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 7ea6fbe e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 04a5353 e825bb5 7ea6fbe 04a5353 | 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | import os
import subprocess
import wave
from typing import Optional, Tuple
import tempfile
import gradio as gr
from google import genai
from google.genai import types
# ------------------------------------------------------------
# Configuration
# ------------------------------------------------------------
# Supported input audio formats
SUPPORTED_AUDIO_EXTS = {".wav", ".mp3", ".m4a"}
# Default models (can be overridden via environment variables if desired)
DEFAULT_TEXT_MODEL = os.getenv("GEMINI_TEXT_MODEL", "gemini-2.5-flash")
DEFAULT_TTS_MODEL = os.getenv("GEMINI_TTS_MODEL", "gemini-2.5-flash-preview-tts")
# Default system prompt used to steer Gemini for meeting-notes behavior.
DEFAULT_SYSTEM_PROMPT = (
"""Here are instructions from the user outlining your goals and how you should respond:
You are a tool designed to assist users by enhancing the efficiency and effectiveness of their meeting notes output. You specialize in three primary functions:
Structuring Notes
Objective: Transform unorganized, rough draft notes into a structured, easy-to-navigate document.
Process: Employ NLP and text analysis algorithms to identify key themes, decisions, action items, and insights from the rough notes. Then, organize these elements according to the predefined template that highlights the meeting's objectives, key points, decisions made, action items, and so on.
Synthesizing Transcripts
Objective: Convert lengthy, verbatim meeting transcripts into concise, coherent summaries.
Process: Use advanced summarization techniques to extract the essence of discussions, focusing on outcomes, decisions, and action points. Integration of sentiment analysis could further highlight discussions' tone and areas of agreement or contention.
Develop Downloadable Microsoft Word Documents
Objective: Provide users with a convenient, editable format for the structured notes and synthesized summaries.
Process: After structuring or synthesizing the content, format the output into a Microsoft Word document.
Here is a breakdown of your operational flow:
Initiation: Each session with the Meeting Notes Assistant begins when a consultant initiates interaction by selecting the "Let's Begin" conversation starter prompt.
Upon activation, you will print the following text:
"Welcome! Ready to streamline your meeting notes? Here's how I can help:
1. Organize Draft Notes: For structured, coherent notes.
2. Combine Notes: Merge notes from multiple sources into one document.
3. Summarize Transcripts: Get concise summaries of your meetings.
Just reply with 1, 2, or 3 to choose. Let's get started!"
If the user selects 1 (Organize Draft Notes), then the tool responds with:
"Great choice! Let's tidy up those draft notes. To get started, please paste your notes below or upload the file. I'll help structure them for clarity and coherence."
Upon receiving the notes, you will structure the output with the following content. Do not use every piece of this, read the notes and make a decision on the best elements to add. Never use all of them:
Meeting Title: [Automatically extracted or prompted for if unclear.]
Date: [Automatically extracted or prompted for.]
Attendees: [List of participants, extracted from notes or prompted for.]
Objective of Meeting: [Objective summarized from the notes or prompted for clarification.]
Summary: [Key points structured in a bulleted list.]
Decisions Made: [Decisions and rationale, highlighted for easy reference.]
Key Action Items: [Tasks listed with assignees and deadlines, clearly outlined.]
Insights and Learnings: [Any notable insights gleaned from the meeting.]
Next Steps: [Detailed actions and responsibilities, clearly outlined for follow-up.]
Formatted Notes: [The structured output, presented in a professional, concise format on no more than one page, focusing on clarity, coherence, and actionable insights.]
You will always print the following question at the end of your note synthesis: "Would you like for me to generate a downloadable Word document of your notes?"
If the user says anything affirmative like "yes", then use Code Interpretor to generate a downloadable Word document of the content.
If the user says anything like "no", then respond with this: "Great! Can I help you with any other notes? Here's how I can help:
1. Organize Draft Notes: For structured, coherent notes.
2. Combine Notes: Merge notes from multiple sources into one document.
3. Summarize Transcripts: Get concise summaries of your meetings.
Just reply with 1, 2, or 3 to choose!"
If the user selects 2 (Combine and Synthesize Notes), then the tool responds with:
"Perfect! Let's merge and synthesize your notes from multiple sources. Please paste the notes below or upload the files, and I'll create a unified, coherent document."
After the user submits their notes, the tool processes and formats the output as follows:
Meeting Title: [Consolidated from provided notes or prompted for if unclear.]
Date(s): [Consolidated dates or prompted for if not provided.]
Attendees: [Compiled list of all participants mentioned across sources.]
Objective of Meeting: [Unified objective synthesized from the various notes, or prompted for clarification.]
Summary: [A synthesized bulleted list of key points from all sources.]
Decisions Made: [A comprehensive list of decisions made, including any rationale that was noted.]
Key Action Items: [All tasks mentioned across sources, listed with assigned individuals and deadlines.]
Insights and Learnings: [Notable insights drawn from the synthesis of all notes.]
Next Steps: [Consolidated list of detailed actions and responsibilities from all sources.]
Recommendations: [Suggestions for next steps or considerations, based on the synthesized information.]
You will always print the following question at the end of your note synthesis: "Would you like for me to generate a downloadable Word document of your notes?"
If the user says anything affirmative like "yes", then use Code Interpretor to generate a downloadable Word document of the content.
If the user says anything like "no", then respond with this: "Great! Can I help you with any other notes? Here's how I can help:
1. Organize Draft Notes: For structured, coherent notes.
2. Combine Notes: Merge notes from multiple sources into one document.
3. Summarize Transcripts: Get concise summaries of your meetings.
Just reply with 1, 2, or 3 to choose!"
If the user selects 3 (Summarize a Meeting Transcript), then the tool responds with:
"Excellent, let's summarize your meeting transcript. Please upload the transcript file or paste it into the chat window, and I'll distill it into a concise summary, capturing all critical points and actionable insights."
The tool then processes the transcript and structures the output as follows:
Meeting Title: [Title extracted or prompted for if unclear.]
Date: [Date extracted or prompted for.]
Attendees: [List of participants, extracted or prompted for clarification.]
Objective of Meeting: [Goal, synthesized from the transcript.]
Summary: [Bulleted list of key points, crafted to be short and professional.]
Decisions Made: [Key decisions made during the meeting, including any rationale provided.]
Key Action Items: [Tasks assigned, with assignees and deadlines clearly listed.]
Insights and Learnings: [Notable insights gathered from the discussion.]
Challenges Discussed: [Specific challenges addressed, providing context to decisions and actions.]
Participant Contributions: [Highlights of significant contributions from attendees, recognizing valuable input.]
Next Steps: [Detailed actions and responsibilities, outlined for clarity and accountability.]
Recommendations: [Strategic suggestions based on the meeting's content, aimed to add value and perspective for planning.]
You will always print the following question at the end of your note synthesis: "Would you like for me to generate a downloadable Word document of your notes?"
If the user says anything affirmative like "yes", then use Code Interpretor to generate a downloadable Word document of the content.
If the user says anything like "no", then respond with this: "Great! Can I help you with any other notes? Here's how I can help:
1. Organize Draft Notes: For structured, coherent notes.
2. Combine Notes: Merge notes from multiple sources into one document.
3. Summarize Transcripts: Get concise summaries of your meetings.
Just reply with 1, 2, or 3 to choose!"
You will maintain consistency and apply this approach every time. This approach ensures notes are concise, and actionable, maintaining a professional tone throughout. Your recommendations are provided to enhance strategic outcomes and decision-making processes, always tailored to the context of the discussion."""
)
# ------------------------------------------------------------
# Utility functions
# ------------------------------------------------------------
def wave_file(
filename: str,
pcm: bytes,
channels: int = 1,
rate: int = 24000,
sample_width: int = 2,
) -> None:
"""
Save raw PCM data as a WAV file.
Mirrors the helper used in the official Gemini TTS examples.
"""
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
wf.writeframes(pcm)
def normalize_audio_file(audio_path: str) -> str:
"""
Ensure the audio file is in a Gemini-supported format.
- .wav and .mp3 are passed through.
- .m4a is converted to 16 kHz WAV via ffmpeg (must be installed).
"""
ext = os.path.splitext(audio_path)[1].lower()
if ext in {".wav", ".mp3"}:
return audio_path
if ext == ".m4a":
converted_path = audio_path + ".converted.wav"
try:
subprocess.run(
[
"ffmpeg",
"-y",
"-i",
audio_path,
"-acodec",
"pcm_s16le",
"-ar",
"16000",
converted_path,
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except FileNotFoundError:
raise RuntimeError(
"ffmpeg is required to convert .m4a files.\n"
"Install ffmpeg or convert the file to .wav/.mp3 manually."
)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"ffmpeg failed while converting {audio_path}: {e}")
return converted_path
raise RuntimeError(
f"Unsupported audio extension '{ext}'. "
f"Supported: {', '.join(sorted(SUPPORTED_AUDIO_EXTS))}"
)
def generate_text_with_optional_audio(
client: genai.Client,
model: str,
prompt: str,
system_prompt: Optional[str] = None,
audio_path: Optional[str] = None,
) -> str:
"""
Call Gemini with a text prompt and an optional audio file.
Uses the modern google-genai Client and models.generate_content API.
Returns the model's text response.
"""
contents: list = [prompt]
if audio_path:
normalized = normalize_audio_file(audio_path)
uploaded_file = client.files.upload(file=normalized)
contents.append(uploaded_file)
effective_system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT
response = client.models.generate_content(
model=model,
contents=contents,
config=types.GenerateContentConfig(
system_instruction=effective_system_prompt,
),
)
return response.text or ""
def tts_from_text(
client: genai.Client,
text: str,
model: str = DEFAULT_TTS_MODEL,
voice_name: str = "Kore",
) -> str:
"""
Convert text to speech using Gemini native TTS (2.5 Flash TTS).
Uses the official speech-generation pattern with response_modalities=['AUDIO']
and SpeechConfig / VoiceConfig.
Returns the path to a temporary WAV file that Gradio can play.
"""
response = client.models.generate_content(
model=model,
contents=text,
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice_name
)
)
),
),
)
# Inline audio data is returned as raw PCM bytes that we wrap into a .wav file.
pcm_data = response.candidates[0].content.parts[0].inline_data.data
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
wave_file(tmp.name, pcm_data)
return tmp.name
# ------------------------------------------------------------
# Core meeting-notes processing
# ------------------------------------------------------------
def process_meeting_notes(
operation_type: str,
text_input: str,
audio_input: Optional[str],
enable_tts: bool,
api_key: str,
progress=gr.Progress(),
) -> Tuple[str, Optional[str]]:
"""
Main processing function for meeting notes.
Returns (text_output, audio_output_path).
"""
# Determine effective API key: prefer user entry, fall back to env var.
effective_api_key = (api_key or "").strip() or os.getenv("GEMINI_API_KEY")
if not effective_api_key:
return (
"β Error: Please provide your Gemini API key (textbox) "
"or set GEMINI_API_KEY in the environment.",
None,
)
if not text_input and not audio_input:
return "β Error: Please provide either text input or an audio file.", None
try:
# Initialize Gemini client
progress(0.1, desc="Initializing Gemini client...")
client = genai.Client(api_key=effective_api_key)
# Prepare prompt based on operation type
progress(0.2, desc="Preparing prompt...")
if operation_type == "Organize Draft Notes":
if text_input:
prompt = f"Please organize these draft notes:\n\n{text_input}"
else:
prompt = (
"Please listen carefully to this meeting recording and generate "
"organized draft notes following the system instructions."
)
elif operation_type == "Combine Notes":
if text_input:
prompt = (
"Please combine and synthesize the following multi-source notes "
"into one unified, coherent meeting document:\n\n"
f"{text_input}"
)
else:
prompt = (
"Please combine and synthesize the notes implied by this audio "
"input into one coherent document following the system instructions."
)
else: # "Summarize Transcripts"
if text_input:
prompt = (
"Please summarize the following meeting transcript into concise, "
"actionable notes:\n\n" f"{text_input}"
)
else:
prompt = (
"Please summarize the meeting transcript contained in this audio "
"file into concise, actionable notes."
)
# Generate text response
progress(0.4, desc="Processing with Gemini...")
text_response = generate_text_with_optional_audio(
client=client,
model=DEFAULT_TEXT_MODEL,
prompt=prompt,
system_prompt=DEFAULT_SYSTEM_PROMPT,
audio_path=audio_input,
)
progress(0.7, desc="Text processing complete!")
# Generate TTS if enabled
audio_output: Optional[str] = None
if enable_tts:
progress(0.8, desc="Generating audio output (TTS)...")
try:
audio_output = tts_from_text(
client=client,
text=text_response,
model=DEFAULT_TTS_MODEL,
voice_name="Kore",
)
progress(1.0, desc="Audio generation complete!")
except Exception as tts_error:
progress(1.0, desc="Processing complete (TTS error)")
return (
text_response
+ "\n\nβ οΈ Note: TTS generation failed with:\n"
+ str(tts_error),
None,
)
else:
progress(1.0, desc="Processing complete!")
return text_response, audio_output
except Exception as e:
return f"β Error while processing: {str(e)}", None
# ------------------------------------------------------------
# Gradio UI
# ------------------------------------------------------------
with gr.Blocks(title="Meeting Notes Assistant", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# π Meeting Notes Assistant
Transform your meeting notes with AI-powered organization, synthesis, and summarization.
**Features:**
- π Organize Draft Notes
- π Combine Multiple Notes
- π Summarize Transcripts
- π€ Audio Input Support (WAV, MP3, M4A)
- π Text-to-Speech Output (Gemini 2.5 TTS)
"""
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### βοΈ Configuration")
api_key_input = gr.Textbox(
label="Gemini API Key (optional)",
placeholder="Enter your Gemini API key, or leave blank to use GEMINI_API_KEY env var",
type="password",
)
gr.Markdown(
"π Get your API key from Google AI Studio and optionally store it "
"as the GEMINI_API_KEY environment variable on this Space."
)
operation_type = gr.Radio(
choices=[
"Organize Draft Notes",
"Combine Notes",
"Summarize Transcripts",
],
label="Operation Type",
value="Organize Draft Notes",
)
gr.Markdown(
"βΉοΈ Choose how you want the assistant to process your input: "
"organize messy notes, merge multiple notes, or summarize transcripts."
)
enable_tts = gr.Checkbox(
label="Enable Text-to-Speech Output",
value=False,
)
gr.Markdown(
"π§ When enabled, the assistant will also generate a spoken version "
"of the processed notes using Gemini TTS."
)
with gr.Column(scale=2):
gr.Markdown("### π₯ Input")
text_input = gr.Textbox(
label="Text Input",
placeholder="Paste your meeting notes, transcript, or text here...",
lines=10,
)
gr.Markdown(
"βοΈ Enter any text-based notes or transcripts here. "
"You can also leave this empty and only upload audio."
)
audio_input = gr.Audio(
label="Audio Input (Optional)",
type="filepath",
)
gr.Markdown(
"ποΈ Upload a WAV, MP3, or M4A file. M4A will be converted "
"to WAV automatically (requires ffmpeg in the environment)."
)
process_btn = gr.Button("π Process Notes", variant="primary")
gr.Markdown("### π€ Output")
with gr.Row():
with gr.Column():
text_output = gr.Textbox(
label="Processed Notes",
lines=15,
show_copy_button=True,
)
gr.Markdown(
"β
Your organized, combined, or summarized notes will appear here. "
"You can copy them with the button in the top-right corner."
)
with gr.Column():
audio_output = gr.Audio(
label="Audio Output",
type="filepath",
)
gr.Markdown(
"π If Text-to-Speech is enabled and succeeds, the generated audio "
"will appear here for playback or download."
)
# Example inputs
gr.Markdown("### π‘ Examples")
gr.Examples(
examples=[
[
"Organize Draft Notes",
"Meeting with John about Q4 planning. Discussed budget allocation. "
"Need to finalize numbers by Friday. Action items: Sarah to review "
"projections, Mike to update spreadsheet.",
None,
False,
],
[
"Summarize Transcripts",
"John: We need to discuss the Q4 budget. Sarah: I think we should "
"allocate more to marketing. Mike: I agree, but we need to be careful "
"with spending. John: Let's review the numbers and decide by Friday.",
None,
False,
],
],
inputs=[operation_type, text_input, audio_input, enable_tts],
)
# Connect the process button
process_btn.click(
fn=process_meeting_notes,
inputs=[operation_type, text_input, audio_input, enable_tts, api_key_input],
outputs=[text_output, audio_output],
)
gr.Markdown(
"""
---
### π How to Use
1. **Enter your Gemini API Key** in the box, or configure `GEMINI_API_KEY` in the environment.
2. **Select operation type**: Organize, Combine, or Summarize.
3. **Provide input**: Enter text and/or upload audio.
4. **Optional**: Enable TTS for audio output.
5. **Click βProcess Notesβ** and wait for results.
### π Getting Your API Key
Visit Google AI Studio to get your free Gemini API key.
"""
)
if __name__ == "__main__":
# Enable queuing so that gr.Progress works correctly in Spaces and other deployments.
demo.queue().launch()
|