-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
103 lines (76 loc) · 2.75 KB
/
main.py
File metadata and controls
103 lines (76 loc) · 2.75 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
from fastapi import FastAPI
from os import path
from datetime import timedelta
from queue import Queue
from pathlib import Path
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
from threading import Thread
import logging
import whisper
model = whisper.load_model("base")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class BaseSchema(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True,
from_attributes=True,
)
class SonarrSeries(BaseSchema):
id: int
title: str
path: str # folder path of the series
class SonarrEpisodeFile(BaseSchema):
id: int
relative_path: str
path: str
size: int
scene_name: str
class SonarrImportHook(BaseSchema):
series: SonarrSeries
episode_file: SonarrEpisodeFile
def get_imported_file_path(self) -> Path:
return Path(self.series.path).joinpath(self.episode_file.relative_path)
app = FastAPI()
task_queue = Queue()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/sonarr_webhook")
async def transcribe_tv(hook: SonarrImportHook):
file_path = hook.get_imported_file_path()
task_queue.put(file_path)
logger.info("Added to queue: %s", file_path)
return {"status": "success"}
def transcribe():
while True:
video_path = task_queue.get()
logger.info("Loading audio: %s", video_path)
audio = whisper.load_audio(video_path)
logger.info("Transcribing video: %s", video_path)
result = model.transcribe(audio)
segments = result["segments"]
video_dir = video_path.parent
video_name = video_path.stem
# jellyfin requires the subs to be <video_name>.srt
# this will also not collide with bazaar as bazaar will download subs with .<language>.srt (i.e. .en.srt)
# - however, ensure that bazarr's Single Language Option is disabled
subtitle_file = f"{video_name}.srt"
subtitle_path = video_dir.joinpath(subtitle_file)
logger.info("Writing to subtitle file: %s", subtitle_path)
# Write to subtitle file
with open(subtitle_path, "w", encoding="utf-8") as srtFile:
for segment in segments:
startTime = (
str(0) + str(timedelta(seconds=int(segment["start"]))) + ",000"
)
endTime = str(0) + str(timedelta(seconds=int(segment["end"]))) + ",000"
text = segment["text"]
subtitle_segment = (
f"{segment['id'] + 1}\n{startTime} --> {endTime}\n{ text }\n\n"
)
srtFile.write(subtitle_segment)
thread = Thread(target=transcribe)
# run the thread
thread.start()