neimp commited on
Commit
6bf3c14
·
verified ·
1 Parent(s): c8e08fe

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +134 -0
  2. requirements.txt +5 -0
  3. speech_recognition.py +30 -0
  4. yandex_summarization.py +46 -0
app.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from time import sleep
3
+
4
+ import gradio as gr
5
+ from moviepy.editor import VideoFileClip
6
+ from pydub import AudioSegment
7
+ from tqdm import trange
8
+
9
+ from speech_recognition import get_speech_recognition_pipeline
10
+ from yandex_summarization import yandex_summary
11
+
12
+ speech_recognition_pipeline = get_speech_recognition_pipeline()
13
+
14
+
15
+ def extract_audio_chunks(video_file: str, chunk_length_ms: int = 60 * 1000):
16
+ """
17
+ Функция, которая извлекает кусочки аудио из входного видеофайла.
18
+
19
+ :param video_file: Путь к входному видеофайлу.
20
+ :param chunk_length_ms: Длина каждого кусочка в миллисекундах (по умолчанию 60 секунд).
21
+ :return: Генератор, который выдаёт кусочки аудио.
22
+ """
23
+ # Загрузка видеофайла и извлечение аудио дорожки
24
+ video = VideoFileClip(video_file)
25
+ audio = video.audio
26
+
27
+ # Создаём новый объект AudioSegment, при помощи которого будем перемещаться по аудио дорожке
28
+ audio_buffer = "temp_audio.wav"
29
+ audio.write_audiofile(audio_buffer, codec="pcm_s16le", nbytes=2, fps=44100)
30
+ audio_segment = AudioSegment.from_file(audio_buffer, format="wav")
31
+
32
+ for i in trange(
33
+ 0,
34
+ len(audio_segment),
35
+ chunk_length_ms,
36
+ desc="Processing audio chunks",
37
+ ):
38
+ chunk = audio_segment[i : i + chunk_length_ms]
39
+ yield chunk
40
+
41
+ # Delete the temporary file
42
+ os.remove(audio_buffer)
43
+
44
+
45
+ def transcribe_video(video_file: str) -> list[str]:
46
+ """
47
+ Функция транскрибации видеофайла в список текстов.
48
+
49
+ :param video_file: Путь к входному видеофайлу.
50
+ :return: Список текстов.
51
+ """
52
+ transcriptions = []
53
+
54
+ for chunk in extract_audio_chunks(video_file):
55
+ # Save the audio chunk to a temporary file
56
+ temp_file = "temp_chunk.wav"
57
+ chunk.export(temp_file, format="wav")
58
+
59
+ # Транскрибация куска аудио
60
+ transcription = speech_recognition_pipeline(
61
+ temp_file, generate_kwargs={"language": "russian"}
62
+ )
63
+ transcriptions.append(transcription["text"])
64
+
65
+ # Удаление временного файла
66
+ os.remove(temp_file)
67
+
68
+ return transcriptions
69
+
70
+
71
+ def batch_collector(transcription_list: list[str], batch_size: int = 3) -> list[str]:
72
+ """
73
+ Функция, снижающая размерность массивов текстов путём укрупнения элементов.
74
+
75
+ :param transcription_list: Список переведённых текстов.
76
+ :param batch_size: Размер батча (по умолчанию 3).
77
+ :return: Генератор списка текстов.
78
+ """
79
+ for i in trange(
80
+ len(transcription_list) // batch_size + 1,
81
+ desc="Processing text batches",
82
+ ):
83
+ start_at = i * batch_size
84
+ end_at = (i + 1) * batch_size
85
+ yield " ".join(transcription_list[start_at:end_at])
86
+
87
+
88
+ def get_yandex_summary_text(long_text: str):
89
+ """
90
+ Функция суммаризации текста при помощи Yandex GPT.
91
+
92
+ :param long_text: Длинный текст, для которого необходимо получить суммаризацию.
93
+ :return: Суммаризированный текст или None, если суммаризация не удалась.
94
+ """
95
+ iam_token = os.environ["YANDEX_IAM_TOKEN"]
96
+ folder_id = os.environ["YANDEX_FOLDER_ID"]
97
+ result = yandex_summary(long_text, iam_token, folder_id)
98
+ if result and "result" in result:
99
+ message = result["result"]["alternatives"][0]["message"]["text"]
100
+ if not message.startswith("Статья не подходит для выполнения задачи"):
101
+ return message
102
+
103
+ return None
104
+
105
+
106
+ def convert_video_to_summary(video_file):
107
+ """
108
+ Функция, которая конвертирует видеофайл в протокол собрания
109
+ с помощью YandexGPT и локальной модели распознавания речи.
110
+
111
+ :param video_file: Путь к входному видеофайлу.
112
+ :return: Протокол собрания.
113
+ """
114
+ transcription_list = transcribe_video(video_file)
115
+ summary_list = []
116
+
117
+ for batch_text in batch_collector(transcription_list):
118
+ summary = get_yandex_summary_text(batch_text)
119
+ if summary is not None:
120
+ summary_list.append(summary)
121
+
122
+ # Ограничиваем частоту обращений к YandexGPT
123
+ sleep(1)
124
+
125
+ return "\n".join(summary_list)
126
+
127
+
128
+ interface = gr.Interface(
129
+ fn=convert_video_to_summary,
130
+ inputs=[gr.Video(label="Видео совещания")],
131
+ outputs=[gr.Textbox(label="Протокол собрания", lines=30)],
132
+ )
133
+
134
+ interface.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ accelerate
2
+ torch
3
+ moviepy
4
+ pydub
5
+ tqdm
speech_recognition.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
3
+
4
+
5
+ def get_speech_recognition_pipeline(model_id: str = "openai/whisper-large-v3"):
6
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
7
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
8
+
9
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
10
+ model_id,
11
+ torch_dtype=torch_dtype,
12
+ low_cpu_mem_usage=True,
13
+ use_safetensors=True,
14
+ )
15
+ model.to(device)
16
+
17
+ processor = AutoProcessor.from_pretrained(model_id)
18
+
19
+ return pipeline(
20
+ "automatic-speech-recognition",
21
+ model=model,
22
+ tokenizer=processor.tokenizer,
23
+ feature_extractor=processor.feature_extractor,
24
+ max_new_tokens=128,
25
+ chunk_length_s=30,
26
+ batch_size=16,
27
+ return_timestamps=True,
28
+ torch_dtype=torch_dtype,
29
+ device=device,
30
+ )
yandex_summarization.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+
4
+ def yandex_summary(
5
+ text,
6
+ iam_token: str,
7
+ folder_id: str,
8
+ temperature: float = 0.5,
9
+ max_tokens: int = 2000,
10
+ endpoint: str = "https://llm.api.cloud.yandex.net/foundationModels/v1/completion",
11
+ ):
12
+ """
13
+ Функция используется для сокращения большого объема текста с помощью API Яндекса.
14
+
15
+ :param text: Текст, который необходимо сократить.
16
+ :param iam_token: Токен IAM, который используется для аутентификации в API Яндекса.
17
+ :param folder_id: ИД папки, содержащей модель Яндекса.
18
+ :param temperature: Температура, используемая для генерации текста.
19
+ :param max_tokens: Максимальное количество токенов, которые необходимо генерировать.
20
+ :param endpoint: Эндпоинт API Яндекса.
21
+ :return: Объект JSON, содержащий сокращение.
22
+ """
23
+ payload = {
24
+ "modelUri": f"gpt://{folder_id}/summarization",
25
+ "messages": [{"role": "user", "text": text}],
26
+ "folderId": f"{folder_id}",
27
+ "completionOptions": {
28
+ "maxTokens": max_tokens,
29
+ "temperature": temperature,
30
+ "stream": False,
31
+ },
32
+ }
33
+
34
+ response = requests.post(
35
+ endpoint,
36
+ json=payload,
37
+ headers={
38
+ "Authorization": f"Bearer {iam_token}",
39
+ "x-folder-id": folder_id,
40
+ "Content-Type": "application/json",
41
+ },
42
+ )
43
+ if response.status_code != 200:
44
+ raise RuntimeError(response.text)
45
+
46
+ return response.json()