-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
200 lines (159 loc) · 6.47 KB
/
app.py
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import base64
import io
import logging
import random
import requests
import uvicorn
from fastapi import FastAPI, Form, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import psycopg2
# from utils import upload_audio
import os
import base64
from fastapi import FastAPI, HTTPException
from dotenv import load_dotenv
from httpx import AsyncClient
import httpx
import uuid
from audio_diarization import speakers_count
load_dotenv()
DYTE_API_KEY = os.getenv("DYTE_API_KEY")
DYTE_ORG_ID = os.getenv("DYTE_ORG_ID")
API_HASH = base64.b64encode(f"{DYTE_ORG_ID}:{DYTE_API_KEY}".encode('utf-8')).decode('utf-8')
timeout = httpx.Timeout(10.0, read=None)
DYTE_API = AsyncClient(base_url='https://api.cluster.dyte.in/v2', headers={'Authorization': f"Basic {API_HASH}"}, timeout=timeout)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
fh = logging.FileHandler("app.log")
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
class ProctorPayload(BaseModel):
meeting_id: str
admin_id: str
class AdminProp(BaseModel):
meeting_id: str
admin_id: str
class Meeting(BaseModel):
title: str
class Participant(BaseModel):
name: str
preset_name: str
meeting_id: str
origins = [
# allow all
"*",
]
app = FastAPI()
# enable cors
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"], # allow all
allow_headers=["*"], # allow all
)
def connect_to_db():
conn = psycopg2.connect(
dbname=os.getenv('DB_USER'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
host=os.getenv('DB_HOST'),
port=5432
)
return conn
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/is_admin")
async def is_admin(admin: AdminProp):
conn = connect_to_db()
cur = conn.cursor()
cur.execute("SELECT count(1) FROM meeting_host_info WHERE meeting_id = %s AND admin_id = %s", (admin.meeting_id, admin.admin_id,))
count = cur.fetchone()[0]
if(count > 0):
return { "admin": True }
else:
return { "admin": False }
@app.post("/multiple_voices_list")
async def multiple_faces_list(meeting: ProctorPayload):
conn = connect_to_db()
cur = conn.cursor()
cur.execute("SELECT count(1) FROM meeting_host_info WHERE meeting_id = %s AND admin_id = %s", (meeting.meeting_id, meeting.admin_id,))
count = cur.fetchone()[0]
if(count > 0):
cur.execute("CREATE TABLE IF NOT EXISTS meeting_audio_proc_details (ts TIMESTAMP, meeting_id VARCHAR(255), participant_id VARCHAR(255), audio_url VARCHAR(255), verdict VARCHAR(255))")
cur.execute("SELECT * FROM meeting_audio_proc_details WHERE meeting_id = %s ORDER BY ts DESC", (meeting.meeting_id,))
rows = cur.fetchall()
conn.commit()
cur.close()
conn.close()
return rows
else:
conn.commit()
cur.close()
conn.close()
raise HTTPException(status_code=401, detail="Participant dose not has admin role")
@app.post("/multiple_voices")
async def multiple_voices(file: UploadFile = File(...), meeting_id: str = Form(...), participant_id: str = Form(...), participant_name: str = Form(...)):
contents = file.file.read()
filename = file.filename.split('.')[0] + str(random.randint(1, 100)) + '.mp3'
with open(filename, 'wb') as f:
f.write(contents)
file.file.close()
conn = connect_to_db()
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS meeting_audio_proc_details (ts TIMESTAMP, meeting_id VARCHAR(255), participant_id VARCHAR(255), audio_url VARCHAR(255), verdict VARCHAR(255))")
try:
count = speakers_count(filename)
except Exception as e:
logger.error(e)
if count > 1:
logger.info(
f"Detected different voices for participant {participant_id}"
)
verdict = f"Participant Name: {participant_name} <> Anomaly: Different Voices Detected <> Participant ID: {participant_id}"
cur.execute("SELECT count(1) FROM meeting_audio_proc_details WHERE meeting_id=%s AND participant_id=%s AND ts >= (current_timestamp - INTERVAL '10 minutes')", (meeting_id, participant_id))
count = cur.fetchone()[0]
if count == 0:
upload_resp = 'https://web.site/some_value' #await upload_image(img_data)
cur.execute("INSERT INTO meeting_audio_proc_details (ts, meeting_id, participant_id, audio_url, verdict) VALUES (current_timestamp, %s, %s, %s, %s)",
(meeting_id, participant_id, upload_resp, verdict)
)
conn.commit()
cur.close()
conn.close()
if count == 0:
return { "id": participant_id, "different_voices_detected": True, "url": upload_resp }
return { "id": participant_id, "different_voices_detected": True, "url": "not uploaded" }
return {"id": participant_id, "different_voices_detected": False}
@app.post("/meetings")
async def create_meeting(meeting: Meeting):
response = await DYTE_API.post('/meetings', json=meeting.dict())
if response.status_code >= 300:
raise HTTPException(status_code=response.status_code, detail=response.text)
admin_id = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=32))
resp_json = response.json()
resp_json['admin_id'] = admin_id
meeting_id = resp_json['data']['id']
conn = connect_to_db()
cur = conn.cursor()
cur.execute("INSERT INTO meeting_host_info (ts, meeting_id, admin_id) VALUES (CURRENT_TIMESTAMP, %s, %s)", (meeting_id, admin_id))
conn.commit()
cur.close()
conn.close()
return resp_json
@app.post("/meetings/{meetingId}/participants")
async def add_participant(meetingId: str, participant: Participant):
client_specific_id = f"react-samples::{participant.name.replace(' ', '-')}-{str(uuid.uuid4())[0:7]}"
payload = participant.dict()
payload.update({"client_specific_id": client_specific_id})
del payload['meeting_id']
resp = await DYTE_API.post(f'/meetings/{meetingId}/participants', json=payload)
if resp.status_code > 200:
raise HTTPException(status_code=resp.status_code, detail=resp.text)
return resp.text
if __name__ == "__main__":
uvicorn.run("app:app", host="localhost", port=8000, log_level="debug", reload=True)