bori0824 commited on
Commit
c6796a4
·
verified ·
1 Parent(s): 00c8fbb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from TTS.api import TTS
3
+ import fitz # PyMuPDF for PDF text extraction
4
+ from tempfile import NamedTemporaryFile
5
+ import os
6
+
7
+ # Initialize TTS models
8
+ TTS_MODELS = {
9
+ "American - Male": "tts_models/en/ljspeech/tacotron2-DDC",
10
+ "American - Female": "tts_models/en/ljspeech/tacotron2-DDC",
11
+ }
12
+
13
+ def extract_text_from_pdf(pdf_path, page_selection=None):
14
+ """Extract specific pages from a PDF."""
15
+ pdf_document = fitz.open(pdf_path)
16
+ text = ""
17
+ total_pages = len(pdf_document)
18
+
19
+ # Parse the page_selection input (e.g., "1,3-5")
20
+ pages_to_read = []
21
+ if page_selection:
22
+ for part in page_selection.split(","):
23
+ if "-" in part:
24
+ start, end = map(int, part.split("-"))
25
+ pages_to_read.extend(range(start - 1, end)) # Convert to 0-indexed
26
+ else:
27
+ pages_to_read.append(int(part) - 1) # Convert to 0-indexed
28
+ else:
29
+ pages_to_read = list(range(total_pages)) # Default: all pages
30
+
31
+ # Ensure valid page selection
32
+ pages_to_read = [p for p in pages_to_read if 0 <= p < total_pages]
33
+
34
+ # Extract text from selected pages
35
+ for page_num in pages_to_read:
36
+ page = pdf_document[page_num]
37
+ page_text = page.get_text()
38
+ text += f"\n--- Page {page_num + 1} ---\n{page_text}" # Add page info
39
+
40
+ if not text.strip():
41
+ return "Error: No text found on the selected pages. They might contain images only."
42
+ return text
43
+
44
+ def generate_audio(text, accent_gender, speed):
45
+ """Generate audio from text using selected accent, gender, and speed."""
46
+ model_name = TTS_MODELS[accent_gender]
47
+ tts = TTS(model_name=model_name)
48
+
49
+ # Generate audio and save as WAV
50
+ with NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
51
+ tts.tts_to_file(text=text, file_path=temp_audio.name)
52
+
53
+ # Save as MP3
54
+ output_mp3_path = temp_audio.name.replace(".wav", ".mp3")
55
+ os.rename(temp_audio.name, output_mp3_path) # Rename WAV to MP3
56
+ return output_mp3_path
57
+
58
+ def process_input(input_text, uploaded_file, page_selection, accent_gender, speed):
59
+ """Process input (text or file) and generate audio."""
60
+ try:
61
+ if not input_text and not uploaded_file:
62
+ return "Please provide input text or upload a file.", None
63
+
64
+ # Extract text from uploaded file
65
+ if uploaded_file:
66
+ file_extension = uploaded_file.name.split('.')[-1].lower()
67
+ with NamedTemporaryFile(delete=False) as temp_file:
68
+ temp_file.write(uploaded_file.read())
69
+ temp_file_path = temp_file.name
70
+
71
+ if file_extension == "pdf":
72
+ text = extract_text_from_pdf(temp_file_path, page_selection)
73
+ else:
74
+ return "Error: Only PDF file support for page selection.", None
75
+
76
+ os.remove(temp_file_path)
77
+ else:
78
+ text = input_text
79
+
80
+ # Generate audio
81
+ mp3_path = generate_audio(text, accent_gender, float(speed))
82
+ return "Audio generated successfully!", mp3_path
83
+
84
+ except Exception as e:
85
+ import traceback
86
+ error_message = f"Error: {str(e)}\n{traceback.format_exc()}"
87
+ print(error_message)
88
+ return error_message, None
89
+
90
+ # Gradio interface
91
+ interface = gr.Interface(
92
+ fn=process_input,
93
+ inputs=[
94
+ gr.Textbox(label="Enter Text", placeholder="Type or paste text here...", lines=5),
95
+ gr.File(label="Upload File (.pdf only for page selection)", file_types=[".pdf"]),
96
+ gr.Textbox(label="Page Selection (e.g., '1,3-5' or leave blank for all pages)", placeholder="Pages to read"),
97
+ gr.Dropdown(label="Accent & Gender", choices=list(TTS_MODELS.keys()), value="American - Male"),
98
+ 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),
99
+ ],
100
+ outputs=[
101
+ gr.Textbox(label="Result"),
102
+ gr.Audio(label="Generated Audio"),
103
+ ],
104
+ title="Text-to-Speech (TTS) Application",
105
+ 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."
106
+ )
107
+
108
+ # Launch the app
109
+ interface.launch()