bori0824 commited on
Commit
0547a3f
·
verified ·
1 Parent(s): de4a5bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -42
app.py CHANGED
@@ -1,39 +1,46 @@
1
  import gradio as gr
2
  from TTS.api import TTS
3
  import fitz # PyMuPDF for PDF text extraction
4
- from docx import Document
5
  from pydub import AudioSegment
6
  import tempfile
7
  import os
8
 
9
- # Initialize TTS models with accents and genders
10
  TTS_MODELS = {
11
  "American - Male": "tts_models/en/ljspeech/tacotron2-DDC",
12
  "American - Female": "tts_models/en/ljspeech/tacotron2-DDC",
13
- "British - Male": "tts_models/en-gb/apopeye/tacotron2-DDC",
14
- "British - Female": "tts_models/en-gb/marlowe/tacotron2-DDC",
15
- "Australian - Male": "tts_models/en-au/cameron/tacotron2-DDC",
16
- "Australian - Female": "tts_models/en-au/aussie/tacotron2-DDC",
17
- "Canadian - Male": "tts_models/en-ca/maple/tacotron2-DDC",
18
- "Canadian - Female": "tts_models/en-ca/snow/tacotron2-DDC"
19
  }
20
 
21
- def extract_text_from_file(file_path, file_extension):
22
- """Extract text from a .txt, .pdf, or .docx file."""
23
- if file_extension == "txt":
24
- with open(file_path, 'r', encoding='utf-8') as f:
25
- return f.read()
26
- elif file_extension == "pdf":
27
- pdf_document = fitz.open(file_path)
28
- text = ""
29
- for page in pdf_document:
30
- text += page.get_text()
31
- return text
32
- elif file_extension == "docx":
33
- doc = Document(file_path)
34
- return "\n".join(paragraph.text for paragraph in doc.paragraphs)
 
35
  else:
36
- raise ValueError("Unsupported file type. Please upload a .txt, .pdf, or .docx file.")
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  def generate_audio(text, accent_gender, speed):
39
  """Generate audio from text using selected accent, gender, and speed."""
@@ -51,35 +58,45 @@ def generate_audio(text, accent_gender, speed):
51
  audio.export(output_mp3_path, format="mp3")
52
  return output_mp3_path
53
 
54
- def process_input(input_text, uploaded_file, accent_gender, speed):
55
  """Process input (text or file) and generate audio."""
56
- if not input_text and not uploaded_file:
57
- return "Please provide input text or upload a file.", None
58
-
59
- # Extract text from file if uploaded
60
- if uploaded_file:
61
- file_extension = uploaded_file.name.split('.')[-1].lower()
62
- with tempfile.NamedTemporaryFile(delete=False) as temp_file:
63
- temp_file.write(uploaded_file.read())
64
- temp_file_path = temp_file.name
65
- text = extract_text_from_file(temp_file_path, file_extension)
66
- os.remove(temp_file_path)
67
- else:
68
- text = input_text
69
-
70
- # Generate audio
71
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  mp3_path = generate_audio(text, accent_gender, float(speed))
73
  return "Audio generated successfully!", mp3_path
 
74
  except Exception as e:
75
- return f"Error: {str(e)}", None
 
 
 
76
 
77
  # Gradio interface
78
  interface = gr.Interface(
79
  fn=process_input,
80
  inputs=[
81
  gr.Textbox(label="Enter Text", placeholder="Type or paste text here...", lines=5),
82
- gr.File(label="Upload File (.txt, .pdf, .docx)", file_types=[".txt", ".pdf", ".docx"]),
 
83
  gr.Dropdown(label="Accent & Gender", choices=list(TTS_MODELS.keys()), value="American - Male"),
84
  gr.Slider(label="Speed (e.g., 1.0 = Normal, 0.75 = Slower, 1.25 = Faster)", minimum=0.5, maximum=2.0, value=1.0, step=0.1),
85
  ],
@@ -88,7 +105,7 @@ interface = gr.Interface(
88
  gr.Audio(label="Generated Audio"),
89
  ],
90
  title="Text-to-Speech (TTS) Application",
91
- description="Upload a text, PDF, or Word file or enter text directly. Customize accent, gender, and speed. Download the generated audio as MP3."
92
  )
93
 
94
  # Launch the app
 
1
  import gradio as gr
2
  from TTS.api import TTS
3
  import fitz # PyMuPDF for PDF text extraction
 
4
  from pydub import AudioSegment
5
  import tempfile
6
  import os
7
 
8
+ # Initialize TTS models
9
  TTS_MODELS = {
10
  "American - Male": "tts_models/en/ljspeech/tacotron2-DDC",
11
  "American - Female": "tts_models/en/ljspeech/tacotron2-DDC",
 
 
 
 
 
 
12
  }
13
 
14
+ def extract_text_from_pdf(pdf_path, page_selection=None):
15
+ """Extract specific pages from a PDF."""
16
+ pdf_document = fitz.open(pdf_path)
17
+ text = ""
18
+ total_pages = len(pdf_document)
19
+
20
+ # Parse the page_selection input (e.g., "1,3-5")
21
+ pages_to_read = []
22
+ if page_selection:
23
+ for part in page_selection.split(","):
24
+ if "-" in part:
25
+ start, end = map(int, part.split("-"))
26
+ pages_to_read.extend(range(start - 1, end)) # Convert to 0-indexed
27
+ else:
28
+ pages_to_read.append(int(part) - 1) # Convert to 0-indexed
29
  else:
30
+ pages_to_read = list(range(total_pages)) # Default: all pages
31
+
32
+ # Ensure valid page selection
33
+ pages_to_read = [p for p in pages_to_read if 0 <= p < total_pages]
34
+
35
+ # Extract text from selected pages
36
+ for page_num in pages_to_read:
37
+ page = pdf_document[page_num]
38
+ page_text = page.get_text()
39
+ text += f"\n--- Page {page_num + 1} ---\n{page_text}" # Add page info
40
+
41
+ if not text.strip():
42
+ return "Error: No text found on the selected pages. They might contain images only."
43
+ return text
44
 
45
  def generate_audio(text, accent_gender, speed):
46
  """Generate audio from text using selected accent, gender, and speed."""
 
58
  audio.export(output_mp3_path, format="mp3")
59
  return output_mp3_path
60
 
61
+ def process_input(input_text, uploaded_file, page_selection, accent_gender, speed):
62
  """Process input (text or file) and generate audio."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  try:
64
+ if not input_text and not uploaded_file:
65
+ return "Please provide input text or upload a file.", None
66
+
67
+ # Extract text from uploaded file
68
+ if uploaded_file:
69
+ file_extension = uploaded_file.name.split('.')[-1].lower()
70
+ with tempfile.NamedTemporaryFile(delete=False) as temp_file:
71
+ temp_file.write(uploaded_file.read())
72
+ temp_file_path = temp_file.name
73
+
74
+ if file_extension == "pdf":
75
+ text = extract_text_from_pdf(temp_file_path, page_selection)
76
+ else:
77
+ return "Error: Only PDF file support for page selection.", None
78
+
79
+ os.remove(temp_file_path)
80
+ else:
81
+ text = input_text
82
+
83
+ # Generate audio
84
  mp3_path = generate_audio(text, accent_gender, float(speed))
85
  return "Audio generated successfully!", mp3_path
86
+
87
  except Exception as e:
88
+ import traceback
89
+ error_message = f"Error: {str(e)}\n{traceback.format_exc()}"
90
+ print(error_message)
91
+ return error_message, None
92
 
93
  # Gradio interface
94
  interface = gr.Interface(
95
  fn=process_input,
96
  inputs=[
97
  gr.Textbox(label="Enter Text", placeholder="Type or paste text here...", lines=5),
98
+ gr.File(label="Upload File (.pdf only for page selection)", file_types=[".pdf"]),
99
+ gr.Textbox(label="Page Selection (e.g., '1,3-5' or leave blank for all pages)", placeholder="Pages to read"),
100
  gr.Dropdown(label="Accent & Gender", choices=list(TTS_MODELS.keys()), value="American - Male"),
101
  gr.Slider(label="Speed (e.g., 1.0 = Normal, 0.75 = Slower, 1.25 = Faster)", minimum=0.5, maximum=2.0, value=1.0, step=0.1),
102
  ],
 
105
  gr.Audio(label="Generated Audio"),
106
  ],
107
  title="Text-to-Speech (TTS) Application",
108
+ description="Upload a PDF file or enter text directly. Specify pages to extract text from, customize accent, gender, and speed. Download the generated audio as MP3."
109
  )
110
 
111
  # Launch the app