cli.py 4.51 KB
Newer Older
Matteo's avatar
update    
Matteo committed
1
2
import argparse
import os
Matteo's avatar
update    
Matteo committed
3
import sys
Matteo's avatar
update    
Matteo committed
4
from rich.console import Console
Matteo's avatar
update  
Matteo committed
5
6
import segment_finder as sf

Matteo's avatar
update    
Matteo committed
7
from mpai_cae_arp.types.irregularity import IrregularityFile
Matteo's avatar
update    
Matteo committed
8
9
10
11
from mpai_cae_arp.files import File, FileType
from mpai_cae_arp.io import prettify, Style


Matteo's avatar
update    
Matteo committed
12
def get_args() -> tuple[str | None, str | None]:
Matteo's avatar
update    
Matteo committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog="audio-analyzer",
            formatter_class=argparse.RawDescriptionHelpFormatter,
            description=f"A tool that implements {prettify('MPAI CAE-ARP Audio Analyser', styles=[Style.BOLD])} Technical Specification.",
            epilog="For support, please contact Matteo Spanio <dev2@audioinnova.com>.\n"
                "This software is licensed under the GNU General Public License v3.0."
        )
        parser.add_argument("--working-directory", "-w", help="The path were the AIW will find and save the files")
        parser.add_argument("--files-name", "-f", help=f"The name of the files to be analyzed {prettify('without extension', styles=[Style.UNDERLINE])}")
        args = parser.parse_args()
        return args.working_directory, args.files_name
    else:
        return os.getenv("WORKING_DIRECTORY"), os.getenv("FILES_NAME")
Matteo's avatar
update    
Matteo committed
27

Matteo's avatar
update    
Matteo committed
28
29
30


def exit_with_error(error_message: str, console) -> None:
Matteo's avatar
update    
Matteo committed
31
    console.print(f"[red bold]Error: {error_message}")
Matteo's avatar
update    
Matteo committed
32
33
34
    quit(os.EX_USAGE)


Matteo's avatar
update    
Matteo committed
35
def main() -> None:
Matteo's avatar
update    
Matteo committed
36
    console = Console()
Matteo's avatar
update    
Matteo committed
37
    console.print("[bold]Welcome to ARP Audio Analyser!")
Matteo's avatar
update    
Matteo committed
38

Matteo's avatar
update    
Matteo committed
39
40
41
42
43
44
    working_directory, files_name = get_args()
    if any(map(lambda x: x is None, [working_directory, files_name])):
        exit_with_error("{}\n{}".format(
            "Working directory or files name not specified!",
            "Try -h/--help to know more about Audio Analyser usage"), console)

Matteo's avatar
update    
Matteo committed
45
    os.makedirs(os.path.join(working_directory, "temp", files_name))
Matteo's avatar
update    
Matteo committed
46
47
48
49
    
    with console.status("[purple]Reading input files", spinner="dots"):
        audio_src = os.path.join(working_directory, "PreservationAudioFile", f"{files_name}.wav")
        video_src = os.path.join(working_directory, "PreservationAudioVisualFile", f"{files_name}.mov")
Matteo's avatar
update    
Matteo committed
50
51
52
53
54
55
56
57

        audio_exists = os.path.exists(audio_src)
        video_exists = os.path.exists(video_src)

        match audio_exists, video_exists:
            case True, True:
                console.print("[green]Input files found!")
            case False, True:
Matteo's avatar
update    
Matteo committed
58
                exit_with_error("Audio file not found! :loud_sound:", console)
Matteo's avatar
update    
Matteo committed
59
            case True, False:
Matteo's avatar
update    
Matteo committed
60
                exit_with_error("Video file not found! :vhs:", console)
Matteo's avatar
update    
Matteo committed
61
            case False, False:
Matteo's avatar
update    
Matteo committed
62
                exit_with_error("Input files not found! :t-rex:", console)
Matteo's avatar
update    
Matteo committed
63
64

    # create irregularity file 1
Matteo's avatar
update    
Matteo committed
65
    with console.status("[purple]Creating irregularity file 1", spinner="dots"):
Matteo's avatar
update    
Matteo committed
66
        irreg1 = sf.create_irreg_file(audio_src, video_src)
Matteo's avatar
update    
Matteo committed
67
        console.log(f"Found {len(irreg1.irregularities)} irregularities from Audio source")
Matteo's avatar
update    
Matteo committed
68
        File(f"{working_directory}/temp/{files_name}/IrregularityFile1.json", FileType.JSON).write_content(irreg1.to_json())
Matteo's avatar
update    
Matteo committed
69
        console.log("[geen]Irregularity file 1 created")
Matteo's avatar
update    
Matteo committed
70
71

    # create irregularity file 2
Matteo's avatar
update    
Matteo committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    with console.status("[purple]Creating irregularity file 2", spinner="dots"):
        video_irreg_1 = {
            "Irregularities": [
                {
                    "TimeLabel": "00:03:00.000",
                    "Source": "v",
                    "IrregularityID": "09a0b0c0-d0e0-f000-0000-000000000000"
                },
                {
                    "TimeLabel": "00:03:01.000",
                    "Source": "v",
                    "IrregularityID": "09a0b0c0-d0e0-f000-0000-000000000001"
                }
            ],
            "Offset": 170
            }
        console.log("Video irregularity file 1 found")
Matteo's avatar
update    
Matteo committed
89
        irreg2 = sf.merge_irreg_files(irreg1, IrregularityFile.from_json(video_irreg_1))
Matteo's avatar
update    
Matteo committed
90
        console.log("[geen]Irregularity file 2 created")
Matteo's avatar
update    
Matteo committed
91

Matteo's avatar
update    
Matteo committed
92
    with console.status("[cyan]Extracting audio irregularities", spinner="dots"):
Matteo's avatar
update    
Matteo committed
93
94
        irreg2= sf.extract_audio_irregularities(audio_src, irreg2, working_directory + "/temp/" + files_name)
        File(f"{working_directory}/temp/{files_name}/IrregularityFile2.json", FileType.JSON).write_content(irreg2.to_json())
Matteo's avatar
update    
Matteo committed
95
        console.log("[green]Audio irregularities extracted")
Matteo's avatar
update    
Matteo committed
96
97

    # classify audio irregularities
Matteo's avatar
update    
Matteo committed
98
99
    with console.status("[cyan bold]Classifying audio irregularities", spinner="monkey"):
        sf.classify_audio_irregularities(working_directory)
Matteo's avatar
update    
Matteo committed
100

Matteo's avatar
update    
Matteo committed
101
102
    console.print("[green bold]Success! :tada:")
    quit(os.EX_OK)
Matteo's avatar
update    
Matteo committed
103
104


Matteo's avatar
update  
Matteo committed
105
if __name__ == "__main__":
Matteo's avatar
update    
Matteo committed
106
    main()