Turbiling commited on
Commit
c1930d4
·
verified ·
1 Parent(s): bdd7e7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -758
app.py CHANGED
@@ -1,788 +1,108 @@
1
- """
2
- =================================================================================
3
- PROFESSIONAL VOICE TRANSCRIPTION & CONTENT GENERATION SYSTEM
4
- =================================================================================
5
- Developer: Najaf Ali Sharqi
6
- Description: Production-grade Gradio application for voice transcription (Urdu/English)
7
- and automated content generation with DOCX/PPTX export capabilities
8
- Compatible: Hugging Face Spaces (CPU environment) - Gradio 3.x+
9
- =================================================================================
10
- """
11
-
12
  import gradio as gr
13
  import os
14
  from groq import Groq
15
- from docx import Document
16
- from docx.shared import Pt, Inches, RGBColor
17
- from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
18
- from docx.oxml import OxmlElement
19
- from docx.oxml.ns import qn
20
- from pptx import Presentation
21
- from pptx.util import Inches as PptxInches, Pt as PptxPt
22
- from pptx.enum.text import PP_ALIGN
23
- from pptx.dml.color import RGBColor as PptxRGBColor
24
- from datetime import datetime
25
- import re
26
- import traceback
27
- import math
28
-
29
- # =================================================================================
30
- # CONFIGURATION & INITIALIZATION
31
- # =================================================================================
32
-
33
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
34
- if not GROQ_API_KEY:
35
- raise ValueError("❌ GROQ_API_KEY environment variable not set")
36
-
37
- client = Groq(api_key=GROQ_API_KEY)
38
-
39
- # Model configurations
40
- TRANSCRIPTION_MODEL = "whisper-large-v3-turbo"
41
- CHAT_MODEL = "llama-3.3-70b-versatile"
42
-
43
- # Audio chunk size (25 MB limit for Groq API)
44
- MAX_AUDIO_SIZE = 24 * 1024 * 1024 # 24 MB to be safe
45
-
46
- # =================================================================================
47
- # HELPER FUNCTIONS
48
- # =================================================================================
49
-
50
- def remove_emojis_and_special_chars(text):
51
- """Remove emojis and special characters from text"""
52
- # Remove emojis and special Unicode characters
53
- emoji_pattern = re.compile("["
54
- u"\U0001F600-\U0001F64F" # emoticons
55
- u"\U0001F300-\U0001F5FF" # symbols & pictographs
56
- u"\U0001F680-\U0001F6FF" # transport & map symbols
57
- u"\U0001F1E0-\U0001F1FF" # flags
58
- u"\U00002702-\U000027B0"
59
- u"\U000024C2-\U0001F251"
60
- u"\U0001F900-\U0001F9FF" # supplemental symbols
61
- u"\U0001FA00-\U0001FA6F"
62
- "]+", flags=re.UNICODE)
63
-
64
- text = emoji_pattern.sub(r'', text)
65
- # Keep Urdu, English, numbers, and basic punctuation
66
- text = re.sub(r'[^\w\s\-.,;:!?()\[\]{}\'"\/\n\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]', '', text)
67
- return text
68
-
69
-
70
- def add_page_numbers(section):
71
- """Add page numbers to document footer"""
72
- footer = section.footer
73
- footer_para = footer.paragraphs[0]
74
- footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
75
-
76
- # Create page number field
77
- run = footer_para.add_run()
78
- fldChar1 = OxmlElement('w:fldChar')
79
- fldChar1.set(qn('w:fldCharType'), 'begin')
80
-
81
- instrText = OxmlElement('w:instrText')
82
- instrText.set(qn('xml:space'), 'preserve')
83
- instrText.text = "PAGE"
84
-
85
- fldChar2 = OxmlElement('w:fldChar')
86
- fldChar2.set(qn('w:fldCharType'), 'end')
87
-
88
- run._r.append(fldChar1)
89
- run._r.append(instrText)
90
- run._r.append(fldChar2)
91
-
92
 
93
- def is_urdu_text(text):
94
- """Check if text contains Urdu characters"""
95
- urdu_pattern = re.compile(r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]')
96
- return bool(urdu_pattern.search(text))
97
 
98
- # =================================================================================
99
- # CORE TRANSCRIPTION FUNCTION WITH CHUNKING
100
- # =================================================================================
 
 
 
101
 
102
- def transcribe_audio_chunked(audio_path):
103
- """
104
- Transcribe audio file with chunking support for long recordings
105
- Supports Urdu and English speech recognition
106
- """
107
- if not audio_path:
108
- return None, "⚠️ No audio file provided"
109
-
110
- try:
111
- # Check file size
112
- file_size = os.path.getsize(audio_path)
113
-
114
- # If file is small enough, transcribe directly
115
- if file_size <= MAX_AUDIO_SIZE:
116
- return transcribe_single_audio(audio_path)
117
-
118
- # For large files, inform user about processing
119
- print(f"Large audio file detected ({file_size / (1024*1024):.2f} MB). Processing in chunks...")
120
-
121
- # Read entire audio file
122
- with open(audio_path, "rb") as audio_file:
123
- audio_data = audio_file.read()
124
-
125
- # Calculate number of chunks needed
126
- num_chunks = math.ceil(file_size / MAX_AUDIO_SIZE)
127
- chunk_size = len(audio_data) // num_chunks
128
-
129
- all_transcriptions = []
130
-
131
- # Process each chunk
132
- for i in range(num_chunks):
133
- start_idx = i * chunk_size
134
- end_idx = start_idx + chunk_size if i < num_chunks - 1 else len(audio_data)
135
- chunk_data = audio_data[start_idx:end_idx]
136
-
137
- print(f"Processing chunk {i+1}/{num_chunks}...")
138
-
139
- # Transcribe chunk
140
- transcription = client.audio.transcriptions.create(
141
- file=(f"chunk_{i}.mp3", chunk_data),
142
- model=TRANSCRIPTION_MODEL,
143
- temperature=0.0,
144
- response_format="verbose_json"
145
- )
146
-
147
- chunk_text = getattr(transcription, 'text', None) or transcription.get('text', '')
148
- chunk_text = chunk_text.strip() if chunk_text else ''
149
- if chunk_text:
150
- all_transcriptions.append(chunk_text)
151
-
152
- # Combine all chunks
153
- combined_text = " ".join(all_transcriptions)
154
-
155
- if not combined_text:
156
- return None, "❌ Transcription returned empty text"
157
-
158
- # Rewrite combined text for clarity
159
- rewrite_prompt = f"""Rewrite the following transcribed text with proper grammar, punctuation, and clarity.
160
- Maintain the original meaning and language (Urdu/English).
161
- If the text is in Urdu, use very short sentences. Break long sentences into smaller ones.
162
- Ensure the text flows naturally and coherently:
163
-
164
- {combined_text}"""
165
-
166
- completion = client.chat.completions.create(
167
- model=CHAT_MODEL,
168
- messages=[{"role": "user", "content": rewrite_prompt}],
169
- temperature=0.5,
170
- max_tokens=8192
171
  )
172
-
173
- rewritten_text = completion.choices[0].message.content.strip()
174
- return rewritten_text, f"✅ Transcription completed successfully ({num_chunks} chunks processed)"
175
-
176
- except Exception as e:
177
- error_msg = f"❌ Transcription Error: {str(e)}"
178
- print(f"Transcription error details: {traceback.format_exc()}")
179
- return None, error_msg
180
 
181
 
182
- def transcribe_single_audio(audio_path):
183
- """Transcribe a single audio file"""
184
- with open(audio_path, "rb") as audio_file:
185
- transcription = client.audio.transcriptions.create(
186
- file=(audio_path, audio_file.read()),
187
- model=TRANSCRIPTION_MODEL,
188
- temperature=0.0,
189
- response_format="verbose_json"
190
- )
191
-
192
- text = getattr(transcription, 'text', None) or transcription.get('text', '')
193
- text = text.strip() if text else ''
194
-
195
  if not text:
196
- return None, "❌ Transcription returned empty text"
197
-
198
- # Rewrite for clarity
199
- rewrite_prompt = f"""Rewrite the following transcribed text with proper grammar, punctuation, and clarity.
200
- Maintain the original meaning and language (Urdu/English).
201
- If the text is in Urdu, use very short sentences. Break long sentences into smaller ones:
202
-
203
- {text}"""
204
-
205
- completion = client.chat.completions.create(
206
- model=CHAT_MODEL,
207
- messages=[{"role": "user", "content": rewrite_prompt}],
208
- temperature=0.5,
209
- max_tokens=8192
210
- )
211
-
212
- rewritten_text = completion.choices[0].message.content.strip()
213
- return rewritten_text, "✅ Transcription completed successfully"
214
 
215
- # =================================================================================
216
- # CONTENT GENERATION ENGINE
217
- # =================================================================================
 
 
218
 
219
- def generate_content(text, content_type, language="English"):
220
  """
221
- Generate specific content type from transcribed text
222
- Strictly follows the selected language
223
- """
224
- if not text or text.strip() == "":
225
- return "❌ No transcribed text available. Please transcribe audio first."
226
-
227
- # Language-specific instructions
228
- lang_instruction = ""
229
- if language == "Urdu":
230
- lang_instruction = """CRITICAL: You MUST write the entire response in Urdu language ONLY.
231
- Do not use ANY English words or phrases except for technical terms that have no Urdu equivalent.
232
- Use very short sentences in Urdu. Break long sentences into smaller ones.
233
- Write naturally in Urdu without mixing any English."""
234
- else:
235
- lang_instruction = """CRITICAL: You MUST write the entire response in English language ONLY.
236
- Do not mix Urdu or any other language. Write everything in clear, proper English."""
237
-
238
- # Content generation prompts with strict language enforcement
239
- prompts = {
240
- "themes_subthemes": f"""{lang_instruction}
241
-
242
- Act as a qualitative researcher. Analyze the text and identify all major themes and their subthemes.
243
- Present in a clear hierarchical structure.
244
- Start directly with the themes and subthemes without any introductory text.
245
-
246
- Text to analyze:
247
- {text}""",
248
-
249
- "summary": f"""{lang_instruction}
250
-
251
- Create a comprehensive summary of the text. Include key points and main ideas.
252
- Write the summary directly without any introductory phrases.
253
-
254
- Text to summarize:
255
- {text}""",
256
-
257
- "study_notes": f"""{lang_instruction}
258
-
259
- Create detailed study notes from the text. Organize with clear headings and key concepts.
260
- Present the notes directly without any introductory text.
261
-
262
- Text:
263
- {text}""",
264
-
265
- "tutorial_beginners": f"""{lang_instruction}
266
-
267
- Create a step-by-step tutorial for absolute beginners based on this content.
268
- Use simple language and clear instructions.
269
- Start directly with the tutorial steps without introduction.
270
-
271
- Content:
272
- {text}""",
273
-
274
- "infographic_content": f"""{lang_instruction}
275
-
276
- Create infographic-style content from the text. Use short phrases and clear structure.
277
- NO EMOJIS. NO SPECIAL CHARACTERS. Use plain text only.
278
- Make it organized and easy to read.
279
-
280
- Text:
281
- {text}""",
282
-
283
- "social_facebook": f"""{lang_instruction}
284
-
285
- Create an engaging Facebook post from this content. Make it conversational and relatable.
286
- Include relevant hashtags.
287
- Write the post directly without any introductory phrases.
288
-
289
- Content:
290
- {text}""",
291
-
292
- "social_linkedin": f"""{lang_instruction}
293
-
294
- Create a professional LinkedIn post from this content. Make it insightful and career-focused.
295
- Include relevant hashtags.
296
- Write the post directly without any introductory phrases.
297
-
298
- Content:
299
- {text}""",
300
-
301
- "quiz_mcqs": f"""{lang_instruction}
302
-
303
- Generate 10 multiple-choice questions from this text. Each question should have 4 options.
304
- Mark the correct answer with an asterisk (*).
305
- Write questions directly without any introductory text.
306
 
307
- Text:
308
- {text}""",
309
-
310
- "quiz_truefalse": f"""{lang_instruction}
311
-
312
- Generate 10 True/False questions from this text.
313
- Mark correct answers.
314
- Write questions directly without any introductory text.
315
-
316
- Text:
317
- {text}""",
318
-
319
- "quiz_fillblanks": f"""{lang_instruction}
320
-
321
- Generate 10 fill-in-the-blank questions from this text.
322
- Provide correct answers separately.
323
- Write questions directly without any introductory text.
324
-
325
- Text:
326
- {text}""",
327
-
328
- "quiz_matching": f"""{lang_instruction}
329
-
330
- Create a matching exercise with 10 items in Column A and their matches in Column B.
331
- Provide the correct matches.
332
- Present directly without any introductory text.
333
-
334
- Text:
335
- {text}""",
336
-
337
- "quiz_short": f"""{lang_instruction}
338
-
339
- Generate 10 short-answer questions from this text with brief model answers.
340
- Write questions directly without any introductory text.
341
-
342
- Text:
343
- {text}""",
344
-
345
- "quiz_essay": f"""{lang_instruction}
346
-
347
- Generate 5 essay-type questions from this text with key points to cover.
348
- Write questions directly without any introductory text.
349
-
350
- Text:
351
- {text}""",
352
-
353
- "mindmap": f"""{lang_instruction}
354
-
355
- Create a text-based mind map structure from this content.
356
- Show central idea, main branches, and sub-branches clearly.
357
- Present directly without any introductory text.
358
-
359
- Content:
360
- {text}""",
361
-
362
- "meeting_minutes": f"""{lang_instruction}
363
-
364
- Create professional minutes of meeting from this text. Include:
365
- - Date and attendees
366
- - Agenda items
367
- - Decisions made
368
- - Action items
369
-
370
- Write directly without any introductory phrases.
371
-
372
- Text:
373
- {text}""",
374
-
375
- "translation": f"""Translate the following text to {language}.
376
- Maintain the original meaning and tone.
377
- Provide ONLY the translation without any introductory text.
378
 
379
- Text to translate:
380
- {text}""",
381
 
382
- "powerpoint": f"""{lang_instruction}
 
 
 
383
 
384
- Create PowerPoint slide content. For each slide, provide:
385
- - Slide title
386
- - 3-5 bullet points
387
- - Brief speaker notes
388
 
389
- Create 8-10 slides covering all key points.
390
- Format each slide clearly with "Slide X:" as the heading.
 
391
 
392
- Content:
393
- {text}"""
394
- }
395
-
396
- prompt = prompts.get(content_type, f"{lang_instruction}\n\nProcess this text:\n\n{text}")
397
-
398
- try:
399
- completion = client.chat.completions.create(
400
- model=CHAT_MODEL,
401
- messages=[{"role": "user", "content": prompt}],
402
- temperature=0.7,
403
- max_tokens=8192
404
  )
405
-
406
- result = completion.choices[0].message.content.strip()
407
-
408
- # Remove common introductory phrases if they slipped through
409
- intro_phrases = [
410
- "Here are", "Here is", "Here's", "Based on", "According to",
411
- "یہاں ہیں", "یہ ہے", "مندرجہ ذیل"
412
- ]
413
- for phrase in intro_phrases:
414
- if result.lower().startswith(phrase.lower()):
415
- # Find the first newline or colon and remove everything before it
416
- idx = result.find('\n')
417
- if idx > 0:
418
- result = result[idx+1:].strip()
419
- idx = result.find(':')
420
- if idx > 0 and idx < 100:
421
- result = result[idx+1:].strip()
422
-
423
- return result
424
-
425
- except Exception as e:
426
- error_msg = f"❌ Content Generation Error: {str(e)}"
427
- print(f"Content generation error: {traceback.format_exc()}")
428
- return error_msg
429
-
430
- # =================================================================================
431
- # DOCUMENT GENERATION FUNCTIONS
432
- # =================================================================================
433
 
434
- def create_docx(content, title, institution_name="", writer_name="", language="English"):
435
- """
436
- Create professionally formatted DOCX file with RTL support for Urdu
437
- """
438
- try:
439
- doc = Document()
440
-
441
- # Determine if content is in Urdu
442
- is_urdu = language == "Urdu" or is_urdu_text(content)
443
-
444
- # Set default font
445
- style = doc.styles['Normal']
446
- font = style.font
447
- font.name = 'Times New Roman'
448
- font.size = Pt(12)
449
-
450
- # Add institution name as header
451
- if institution_name:
452
- section = doc.sections[0]
453
- header = section.header
454
- header_para = header.paragraphs[0]
455
- header_para.text = institution_name.upper()
456
- header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
457
- header_para.runs[0].font.bold = True
458
- header_para.runs[0].font.size = Pt(14)
459
-
460
- # Add writer name and date
461
- if writer_name:
462
- writer_para = doc.add_paragraph()
463
- writer_run = writer_para.add_run(f"Writer: {writer_name}\n" if not is_urdu else f"مصنف: {writer_name}\n")
464
- writer_run.bold = True
465
- if is_urdu:
466
- writer_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
467
-
468
- date_para = doc.add_paragraph()
469
- date_text = f"Date: {datetime.now().strftime('%B %d, %Y')}\n" if not is_urdu else f"تاریخ: {datetime.now().strftime('%d/%m/%Y')}\n"
470
- date_run = date_para.add_run(date_text)
471
- date_run.bold = True
472
- if is_urdu:
473
- date_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
474
-
475
- # Add main title
476
- title_para = doc.add_paragraph()
477
- title_run = title_para.add_run(title)
478
- title_run.font.size = Pt(24)
479
- title_run.font.bold = True
480
- title_run.font.name = 'Times New Roman'
481
- title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
482
-
483
- doc.add_paragraph() # Spacing
484
-
485
- # Add content with formatting
486
- lines = content.split('\n')
487
- for line in lines:
488
- if line.strip():
489
- para = doc.add_paragraph(line)
490
- para.paragraph_format.line_spacing = 1.5
491
-
492
- # Set RTL for Urdu content
493
- if is_urdu or is_urdu_text(line):
494
- para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
495
- # Set paragraph direction to RTL
496
- pPr = para._element.get_or_add_pPr()
497
- bidi = OxmlElement('w:bidi')
498
- bidi.set(qn('w:val'), '1')
499
- pPr.append(bidi)
500
-
501
- # Apply heading styles based on content
502
- if line.startswith('##'):
503
- para.runs[0].font.size = Pt(18)
504
- para.runs[0].font.bold = True
505
- elif line.startswith('#'):
506
- para.runs[0].font.size = Pt(18)
507
- para.runs[0].font.bold = True
508
- elif line.isupper() and len(line.split()) < 8:
509
- para.runs[0].font.size = Pt(18)
510
- para.runs[0].font.bold = True
511
-
512
- # Add page numbers (numbers only)
513
- for section in doc.sections:
514
- add_page_numbers(section)
515
-
516
- # Set margins
517
- for section in doc.sections:
518
- section.top_margin = Inches(1)
519
- section.bottom_margin = Inches(1)
520
- section.left_margin = Inches(1)
521
- section.right_margin = Inches(1)
522
-
523
- # Save to file
524
- filename = f"{title.replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
525
- doc.save(filename)
526
- return filename
527
- except Exception as e:
528
- print(f"DOCX creation error: {traceback.format_exc()}")
529
- raise e
530
 
 
 
 
 
 
531
 
532
- def create_pptx(content, title, language="English"):
533
- """
534
- Create PowerPoint presentation with images, charts, and professional design
535
- """
536
- try:
537
- prs = Presentation()
538
- prs.slide_width = PptxInches(10)
539
- prs.slide_height = PptxInches(7.5)
540
-
541
- # Determine if content is in Urdu
542
- is_urdu = language == "Urdu" or is_urdu_text(content)
543
-
544
- # Title slide with colorful design
545
- title_slide_layout = prs.slide_layouts[0]
546
- slide = prs.slides.add_slide(title_slide_layout)
547
-
548
- # Title
549
- slide.shapes.title.text = title
550
- title_frame = slide.shapes.title.text_frame
551
- title_frame.paragraphs[0].font.size = PptxPt(44)
552
- title_frame.paragraphs[0].font.bold = True
553
- title_frame.paragraphs[0].font.color.rgb = PptxRGBColor(0, 51, 102)
554
-
555
- # Subtitle
556
- subtitle = slide.placeholders[1]
557
- subtitle_text = f"Generated on {datetime.now().strftime('%B %d, %Y')}"
558
- if is_urdu:
559
- subtitle_text = f"تیار کردہ: {datetime.now().strftime('%d/%m/%Y')}"
560
- subtitle.text = subtitle_text
561
-
562
- # Add session objectives slide
563
- objectives_layout = prs.slide_layouts[1]
564
- obj_slide = prs.slides.add_slide(objectives_layout)
565
- obj_slide.shapes.title.text = "Session Objectives" if not is_urdu else "سیشن کے مقاصد"
566
-
567
- obj_frame = obj_slide.shapes.placeholders[1].text_frame
568
- obj_frame.clear()
569
-
570
- objectives = [
571
- "Understand key concepts and main ideas",
572
- "Apply knowledge in practical scenarios",
573
- "Develop critical thinking skills"
574
  ]
575
-
576
- if is_urdu:
577
- objectives = [
578
- "اہم تصورات اور بنیادی خیالات کو سمجھنا",
579
- "عملی منظرناموں میں علم کا اطلاق کرنا",
580
- "تنقیدی سوچ کی مہارت پیدا کرنا"
581
- ]
582
-
583
- for obj_text in objectives:
584
- p = obj_frame.add_paragraph()
585
- p.text = obj_text
586
- p.font.size = PptxPt(20)
587
- p.level = 0
588
- if is_urdu:
589
- p.alignment = PP_ALIGN.RIGHT
590
-
591
- # Parse content into slides
592
- slides_content = []
593
- current_slide = {"title": "", "points": []}
594
-
595
- lines = content.split('\n')
596
- for line in lines:
597
- line = line.strip()
598
- if not line:
599
- continue
600
-
601
- # Detect slide titles
602
- if line.startswith('Slide') or line.startswith('**') or (line.isupper() and len(line.split()) < 10):
603
- if current_slide["title"]:
604
- slides_content.append(current_slide)
605
- current_slide = {"title": line.replace('**', '').replace('Slide', '').replace(':', '').strip(), "points": []}
606
- elif line.startswith('-') or line.startswith('•') or line.startswith('*'):
607
- current_slide["points"].append(line.lstrip('-•* '))
608
- elif current_slide["title"]:
609
- current_slide["points"].append(line)
610
-
611
- if current_slide["title"]:
612
- slides_content.append(current_slide)
613
-
614
- # Create content slides with colorful design
615
- colors = [
616
- PptxRGBColor(0, 51, 102), # Navy Blue
617
- PptxRGBColor(0, 102, 204), # Blue
618
- PptxRGBColor(0, 153, 76), # Green
619
- PptxRGBColor(204, 51, 0), # Red-Orange
620
- ]
621
-
622
- for idx, slide_data in enumerate(slides_content):
623
- bullet_slide_layout = prs.slide_layouts[1]
624
- slide = prs.slides.add_slide(bullet_slide_layout)
625
-
626
- # Colorful title
627
- slide.shapes.title.text = slide_data["title"]
628
- title_frame = slide.shapes.title.text_frame
629
- title_frame.paragraphs[0].font.size = PptxPt(32)
630
- title_frame.paragraphs[0].font.bold = True
631
- title_frame.paragraphs[0].font.color.rgb = colors[idx % len(colors)]
632
-
633
- text_frame = slide.shapes.placeholders[1].text_frame
634
- text_frame.clear()
635
-
636
- for point in slide_data["points"][:6]: # Max 6 points per slide
637
- p = text_frame.add_paragraph()
638
- p.text = point
639
- p.level = 0
640
- p.font.size = PptxPt(18)
641
- if is_urdu or is_urdu_text(point):
642
- p.alignment = PP_ALIGN.RIGHT
643
-
644
- # Add conclusion slide
645
- conclusion_layout = prs.slide_layouts[1]
646
- conclusion_slide = prs.slides.add_slide(conclusion_layout)
647
- conclusion_slide.shapes.title.text = "Conclusion" if not is_urdu else "نتیجہ"
648
-
649
- conc_frame = conclusion_slide.shapes.placeholders[1].text_frame
650
- conc_frame.clear()
651
-
652
- conclusion_text = [
653
- "Thank you for your attention",
654
- "Questions and Discussion",
655
- "Contact for further information"
656
- ]
657
-
658
- if is_urdu:
659
- conclusion_text = [
660
- "آپ کی توجہ کا شکریہ",
661
- "سوالات اور بحث",
662
- "مزید معلومات کے لیے رابطہ کریں"
663
- ]
664
-
665
- for text in conclusion_text:
666
- p = conc_frame.add_paragraph()
667
- p.text = text
668
- p.font.size = PptxPt(24)
669
- p.font.bold = True
670
- if is_urdu:
671
- p.alignment = PP_ALIGN.RIGHT
672
-
673
- # Save to file
674
- filename = f"{title.replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pptx"
675
- prs.save(filename)
676
- return filename
677
- except Exception as e:
678
- print(f"PPTX creation error: {traceback.format_exc()}")
679
- raise e
680
-
681
- # =================================================================================
682
- # GRADIO UI COMPONENTS
683
- # =================================================================================
684
-
685
- def clear_all():
686
- """Reset all fields"""
687
- return None, "", "🔄 Cleared all data", "", "", ""
688
-
689
- def process_transcription(audio):
690
- """Process audio transcription with chunking support"""
691
- if not audio:
692
- return "", "⚠️ No audio provided"
693
-
694
- text, status = transcribe_audio_chunked(audio)
695
- return text if text else "", status
696
-
697
- def generate_and_download(text, content_type, language, institution_name, writer_name):
698
- """Generate content and create downloadable DOCX"""
699
- if not text:
700
- return "❌ No transcribed text available", None, "⚠️ Please transcribe audio first"
701
-
702
- try:
703
- # Generate content
704
- content = generate_content(text, content_type, language)
705
-
706
- if isinstance(content, str) and content.startswith("❌"):
707
- return content, None, content
708
-
709
- # Create document
710
- title_map = {
711
- "themes_subthemes": "Themes and Subthemes Analysis" if language == "English" else "موضوعات اور ذیلی موضوعات کا تجزیہ",
712
- "summary": "Summary" if language == "English" else "خلاصہ",
713
- "study_notes": "Study Notes" if language == "English" else "مطالعاتی نوٹس",
714
- "tutorial_beginners": "Tutorial for Beginners" if language == "English" else "ابتدائی افراد کے لیے ٹیوٹوریل",
715
- "infographic_content": "Infographic Content" if language == "English" else "انفوگرافک مواد",
716
- "social_facebook": "Facebook Post" if language == "English" else "فیس بک پوسٹ",
717
- "social_linkedin": "LinkedIn Post" if language == "English" else "لنکڈان پوسٹ",
718
- "quiz_mcqs": "Multiple Choice Questions" if language == "English" else "کثیر الانتخابی سوالات",
719
- "quiz_truefalse": "True False Questions" if language == "English" else "درست غلط سوالات",
720
- "quiz_fillblanks": "Fill in the Blanks" if language == "English" else "خالی جگہ پر کریں",
721
- "quiz_matching": "Matching Exercise" if language == "English" else "ملاپ کی مشق",
722
- "quiz_short": "Short Answer Questions" if language == "English" else "مختصر جوابی سوالات",
723
- "quiz_essay": "Essay Questions" if language == "English" else "مضمون کے سوالات",
724
- "mindmap": "Mind Map" if language == "English" else "ذہنی نقشہ",
725
- "meeting_minutes": "Minutes of Meeting" if language == "English" else "اجلاس کی کارروائی",
726
- "translation": f"Translation to {language}" if language == "English" else f"{language} میں ترجمہ"
727
- }
728
-
729
- title = title_map.get(content_type, "Generated Content")
730
-
731
- # Remove emojis and special characters (for all content types now)
732
- content = remove_emojis_and_special_chars(content)
733
-
734
- filename = create_docx(content, title, institution_name, writer_name, language)
735
-
736
- return content, filename, "✅ Content generated and document created"
737
-
738
- except Exception as e:
739
- error_msg = f"❌ Error: {str(e)}"
740
- print(f"Generate and download error: {traceback.format_exc()}")
741
- return error_msg, None, error_msg
742
-
743
- def generate_pptx_only(text, language, institution_name, writer_name):
744
- """Generate PowerPoint presentation"""
745
- if not text:
746
- return None, "❌ No transcribed text available"
747
-
748
- try:
749
- content = generate_content(text, "powerpoint", language)
750
-
751
- if isinstance(content, str) and content.startswith("❌"):
752
- return None, content
753
-
754
- ppt_title = "Presentation" if language == "English" else "پیشکش"
755
- filename = create_pptx(content, ppt_title, language)
756
-
757
- return filename, "✅ PowerPoint presentation created"
758
-
759
- except Exception as e:
760
- error_msg = f"❌ Error: {str(e)}"
761
- print(f"PowerPoint generation error: {traceback.format_exc()}")
762
- return None, error_msg
763
-
764
- # =================================================================================
765
- # GRADIO APPLICATION
766
- # =================================================================================
767
 
768
- with gr.Blocks() as app:
769
- # ===== HEADER =====
770
- gr.Markdown("""
771
- # 🎙️ Professional Voice Transcription & Content Generation System
772
- ### Transform your audio into professional documents, presentations, and educational content
773
- **Supports:** Urdu & English | **Features:** 15+ Content Types | **Export:** DOCX & PPTX
774
 
775
- ---
 
 
 
 
776
 
777
- ### 📚 How to Use for Educational Purposes:
778
 
779
- 1. **Record or Upload:** Upload your lecture, seminar, or educational discussion audio. The system handles long recordings automatically by processing them in chunks.
780
- 2. **Review Transcription:** Once transcribed, review the text for accuracy. You can copy and edit if needed before generating content.
781
- 3. **Generate Educational Materials:** Select your desired content type (study notes, quiz questions, summaries) and language preference. The system will create professional documents ready for classroom use or student distribution.
782
- """)
783
 
784
- # (NOTE) Add more UI components (inputs, buttons, outputs) below as needed.
785
 
786
- # Launch the app when executed directly
787
- if __name__ == "__main__":
788
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import os
3
  from groq import Groq
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ groq_api_key = os.getenv("GROQ_API_KEY")
6
+ client = Groq(api_key=groq_api_key)
 
 
7
 
8
+ # -------------------------------
9
+ # TRANSCRIBE FUNCTION
10
+ # -------------------------------
11
+ def transcribe(audio_file, language):
12
+ if audio_file is None:
13
+ return "❌ Please upload or record audio."
14
 
15
+ with open(audio_file, "rb") as f:
16
+ transcription = client.audio.transcriptions.create(
17
+ file=(audio_file, f.read()),
18
+ model="whisper-large-v3-turbo",
19
+ response_format="text"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  )
21
+ return transcription
 
 
 
 
 
 
 
22
 
23
 
24
+ # -------------------------------
25
+ # CONTENT GENERATION FUNCTION
26
+ # -------------------------------
27
+ def generate_content(action, text, lang_choice):
 
 
 
 
 
 
 
 
 
28
  if not text:
29
+ return "❌ Please transcribe audio first."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ prompt = f"""
32
+ Act as an expert educator.
33
+ Action: {action}
34
+ Language: {lang_choice}
35
+ Input Text: {text}
36
 
37
+ Generate the best possible output.
38
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ response = client.chat.completions.create(
41
+ model="llama-3.1-8b-instant",
42
+ messages=[{"role": "user", "content": prompt}]
43
+ )
44
+ return response.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
 
 
46
 
47
+ # -------------------------------
48
+ # GRADIO UI
49
+ # -------------------------------
50
+ def ui():
51
 
52
+ with gr.Blocks(theme="soft") as app:
53
+ gr.Markdown("## 🎤 GENAI Voice Transcription & Content Creator (Urdu + English)")
 
 
54
 
55
+ with gr.Row():
56
+ audio_input = gr.Audio(source="upload", type="filepath", label="🎧 Upload Audio")
57
+ audio_record = gr.Audio(source="microphone", type="filepath", label="🎙️ Record Audio")
58
 
59
+ language_dropdown = gr.Dropdown(
60
+ ["Urdu", "English"],
61
+ value="English",
62
+ label="Select Transcription Language"
 
 
 
 
 
 
 
 
63
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ transcribe_btn = gr.Button("🔍 Transcribe Audio")
66
+ transcription_output = gr.Textbox(label="Transcribed Text", lines=10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ transcribe_btn.click(
69
+ fn=transcribe,
70
+ inputs=[audio_input, language_dropdown],
71
+ outputs=[transcription_output]
72
+ )
73
 
74
+ gr.Markdown("---")
75
+ gr.Markdown("### 📚 Generate Content from Transcription")
76
+
77
+ # 10 Action Buttons
78
+ ACTIONS = [
79
+ "Summary",
80
+ "Tutorial",
81
+ "Themes & Subthemes",
82
+ "PowerPoint Slide Content",
83
+ "Facebook Post",
84
+ "LinkedIn Post",
85
+ "Translation",
86
+ "Infographic Content",
87
+ "Quiz Questions (MCQs + T/F + Fill Blanks + Match + Short + Essay)",
88
+ "Mind Map"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ for action in ACTIONS:
92
+ with gr.Row():
93
+ lang = gr.Dropdown(["Urdu", "English"], value="English", label=f"{action} Language")
94
+ btn = gr.Button(f"✨ Generate: {action}")
95
+ output = gr.Textbox(label=f"{action} Output", lines=8)
 
96
 
97
+ btn.click(
98
+ fn=generate_content,
99
+ inputs=[gr.Text(action), transcription_output, lang],
100
+ outputs=[output]
101
+ )
102
 
103
+ return app
104
 
 
 
 
 
105
 
106
+ app = ui()
107
 
108
+ app.launch()