File size: 1,881 Bytes
b8b16cf
 
02f8934
b8b16cf
 
02f8934
b8b16cf
02f8934
b8b16cf
 
02f8934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8b16cf
 
 
02f8934
b8b16cf
 
02f8934
 
 
 
 
b8b16cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02f8934
b8b16cf
 
 
02f8934
 
b8b16cf
 
 
 
 
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
import gradio as gr
from gtts import gTTS
import pdfplumber
import os

def extract_text_from_pdf(pdf_file):
    """
    Extract text from a PDF file using pdfplumber.
    
    Args:
        pdf_file: Uploaded PDF file.
    
    Returns:
        str: Extracted text from the PDF.
    """
    try:
        with pdfplumber.open(pdf_file) as pdf:
            text = ""
            for page in pdf.pages:
                text += page.extract_text() or ""
        return text if text else "No text could be extracted from the PDF."
    except Exception as e:
        return f"Error extracting text: {str(e)}"

def text_to_speech(pdf_file, lang="en"):
    """
    Convert text from a PDF to speech using gTTS and return the audio file path.
    
    Args:
        pdf_file: Uploaded PDF file.
        lang (str): Language code (default is 'en' for English).
    
    Returns:
        str: Path to the generated audio file or error message.
    """
    try:
        # Extract text from PDF
        text = extract_text_from_pdf(pdf_file)
        if "Error" in text:
            return text
        
        # Create gTTS object
        tts = gTTS(text=text, lang=lang, slow=False)
        
        # Save the audio file
        output_file = "output.mp3"
        tts.save(output_file)
        
        return output_file
    
    except Exception as e:
        return f"An error occurred: {str(e)}"

# Define Gradio interface
demo = gr.Interface(
    fn=text_to_speech,
    inputs=[
        gr.File(label="Upload a PDF file", file_types=[".pdf"]),
        gr.Dropdown(choices=["en", "es", "fr"], label="Select Language", value="en")
    ],
    outputs=gr.Audio(label="Generated Speech"),
    title="PDF to Speech with gTTS",
    description="Upload a PDF file, select a language, and generate speech from the extracted text."
)

# Launch the app
if __name__ == "__main__":
    demo.launch()