Sabbah13 commited on
Commit
ee531be
1 Parent(s): 20630f6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -0
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import base64
3
+ import json
4
+ import streamlit as st
5
+ from speechlib import Transcriptor
6
+
7
+ def transcribe_audio(file, log_folder, language, modelSize, ACCESS_TOKEN, voices_folder, quantization):
8
+ transcriptor = Transcriptor(file, log_folder, language, modelSize, ACCESS_TOKEN, voices_folder, quantization)
9
+ return transcriptor.whisper()
10
+
11
+ def transform_transcript(transcript):
12
+ result = []
13
+ for segment in transcript:
14
+ start_time, end_time, text, speaker = segment
15
+ result.append(f"{speaker} ({start_time:.1f} : {end_time:.1f}) : {text}")
16
+ return '\n'.join(result)
17
+
18
+ st.title('Audio Transcription App')
19
+
20
+ ACCESS_TOKEN = st.secrets["HF_TOKEN"]
21
+
22
+ uploaded_file = st.file_uploader("Загрузите аудиофайл", type=["mp4", "wav", "m4a"])
23
+
24
+ if uploaded_file is not None:
25
+ file_extension = uploaded_file.name.split(".")[-1] # Получаем расширение файла
26
+ temp_file_path = f"temp_file.{file_extension}" # Создаем временное имя файла с правильным расширением
27
+
28
+ with open(temp_file_path, "wb") as f:
29
+ f.write(uploaded_file.getbuffer())
30
+
31
+ log_folder = "logs"
32
+ language = "ru"
33
+ modelSize = "large"
34
+ voices_folder = ""
35
+ quantization = False
36
+
37
+ with st.spinner('Транскрибируем...'):
38
+ result = transcribe_audio(temp_file_path, log_folder, language, modelSize, ACCESS_TOKEN, voices_folder, quantization)
39
+
40
+ st.write("Результат транскрибации:")
41
+ transcript = transform_transcript(result)
42
+ st.text(transcript)
43
+
44
+ with st.spinner('Резюмируем...'):
45
+ username = st.secrets["GIGA_USERNAME"]
46
+ password = st.secrets["GIGA_SECRET"]
47
+
48
+ # Получаем строку с базовой авторизацией в формате Base64
49
+ auth_str = f'{username}:{password}'
50
+ auth_bytes = auth_str.encode('utf-8')
51
+ auth_base64 = base64.b64encode(auth_bytes).decode('utf-8')
52
+ url = 'https://ngw.devices.sberbank.ru:9443/api/v2/oauth'
53
+
54
+ headers = {
55
+ 'Authorization': f'Basic {auth_base64}', # вставляем базовую авторизацию
56
+ 'RqUID': '6f0b1291-c7f3-43c6-bb2e-9f3efb2dc98f',
57
+ 'Content-Type': 'application/x-www-form-urlencoded',
58
+ 'Accept': 'application/json'
59
+ }
60
+
61
+ data = {
62
+ 'scope': 'GIGACHAT_API_PERS'
63
+ }
64
+
65
+ response = requests.post(url, headers=headers, data=data, verify=False)
66
+ access_token = response.json()['access_token']
67
+ print('Got access token')
68
+
69
+ url_completion = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions"
70
+
71
+ data_copm = json.dumps({
72
+ "model": "GigaChat",
73
+ "messages": [
74
+ {
75
+ "role": "user",
76
+ "content": "Напиши резюме транскрибации звонка, текст которого приложен в ниже. Выдели самостоятельно цель встречи, потом описать ключевые моменты всей встречи. Потом выделить отдельные темы звонка и выделить ключевые моменты в них. Напиши итоги того, о чем договорились говорящие, если такое возможно выделить из текста. Транскрибация: " + transcript
77
+ }
78
+ ],
79
+ "stream": False,
80
+ "max_tokens": 1024,
81
+ })
82
+
83
+ headers_comp = {
84
+ 'Content-Type': 'application/json',
85
+ 'Accept': 'application/json',
86
+ 'Authorization': 'Bearer ' + access_token
87
+ }
88
+
89
+ response = requests.post(url_completion, headers=headers_comp, data=data_copm, verify=False)
90
+ response_data = response.json()
91
+ answer_from_llm = response_data['choices'][0]['message']['content']
92
+
93
+ st.write("Результат резюмирования:")
94
+ st.text(answer_from_llm)