#! /usr/bin/env python3 # vim:fenc=utf-8 # # Copyright © 2023 icoon # """ first argument is the pdf file name play the mp3 with mpv :) """ import sys import asyncio import edge_tts from pypdf import PdfReader TEXT = "" VOICE = "en-GB-SoniaNeural" #VOICE = "de-CH-LeniNeural" INPUT_PDF_FILE = sys.argv[1:][0] OUTPUT_AUDIO_FILE = INPUT_PDF_FILE.replace(".pdf",".mp3") OUTPUT_TEXT_FILE = INPUT_PDF_FILE.replace(".pdf",".txt") WEBVTT_FILE = INPUT_PDF_FILE.replace(".pdf",".vtt") def reflow(text): holdover = "" for line in text.splitlines(): if line.endswith("-"): lin, _, e = line.rpartition(" ") else: lin, e = line, "" yield f"{holdover}{lin}" holdover = e[:-1] def rPdf(fileName): print(fileName) file = open(OUTPUT_TEXT_FILE,"w") reader = PdfReader(fileName) text = "" for page in reader.pages: line = page.extract_text() + "\n" # we need the /n ro reflow the text correctely text += line text = "\n".join(reflow(text)) # remove the hyphenation and connect the word file.write(text) file.close() text=text.replace("\n","") # remove all /n for a better speech experience return text async def amain() -> None: """Main function""" communicate = edge_tts.Communicate(TEXT, VOICE) submaker = edge_tts.SubMaker() with open(OUTPUT_AUDIO_FILE, "wb") as file: async for chunk in communicate.stream(): if chunk["type"] == "audio": file.write(chunk["data"]) elif chunk["type"] == "WordBoundary": print(f"WordBoundary: {chunk}") submaker.create_sub((chunk["offset"], chunk["duration"]), chunk["text"]) with open(WEBVTT_FILE, "w", encoding="utf-8") as file: file.write(submaker.generate_subs()) if __name__ == "__main__": loop = asyncio.get_event_loop_policy().get_event_loop() try: print("reading...") TEXT = rPdf(INPUT_PDF_FILE) print("parsing") loop.run_until_complete(amain()) finally: loop.close()