File size: 1,662 Bytes
b403268
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from pathlib import Path
from logger import logging
from typing import Optional
import whisper
import config


def get_video_from_yt(video_url : str, save_file_dir : str, video_name : str="yt_audio") -> Optional[Path]:
    """
    Download YouTube video as an audio file in .wav . Returns the path of the 
    downloaded file as string
    """

    logging.info(f"Attempting youtube video download : \nURL : {video_url}")

    try :
        # create directory if not exists
        os.makedirs(save_file_dir, exist_ok=True)

        filepath = f"{save_file_dir}/{video_name}"

        # download the file
        os.system(f'yt-dlp --quiet -o {filepath} -x --audio-format "wav" {video_url}')
        
        logging.info(f"Download successful. \nAudio file path : {filepath}")

        return f"{filepath}.wav"
    except Exception as e:
        logging.info("Download unsuccessful.")
        logging.exception(e)
        return None


def get_text_from_audio(audio_path : str) -> Optional[str]:
    """
    Extracts text from audio file. 
    """

    logging.info(f"Attempting to extract text from : {audio_path}")

    try :
        model = whisper.load_model(name='base', download_root=config.MODEL_DIR)
        results = model.transcribe(audio_path)

        logging.info("Extraction successful.")
        return results['text']
    except Exception as e:
        logging.info("Extraction failed.")
        logging.exception(e)
        return None



#URL = "https://www.youtube.com/watch?v=iO5LjrQaN9s"
#save_file_dir = "audio_files"
#video_path  = get_video_from_yt(URL, save_file_dir)
#if video_path:
#   print(get_text_from_audio(video_path))