forked from axolotlite/PiRL-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpirl_api.py
215 lines (187 loc) · 8.89 KB
/
pirl_api.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from fastapi import FastAPI
from pydantic import BaseModel
import base64
from fastapi.responses import FileResponse
from fastapi.param_functions import Path
import os
import cv2
import numpy
from starlette.responses import StreamingResponse
import json
from dotenv import load_dotenv
import uvicorn
from utils import create_directories
from db_handler import DBHandler
class Attendance(BaseModel):
user: str
userId: int
lessonId: int
token: str
classId: int
# date: date
class APIWrapper():
def __init__(self):
host = os.getenv('HOST')
port = os.getenv('PORT')
self.app = FastAPI()
config = uvicorn.Config(self.app, host=host, port=port, log_level="info")
self.server = uvicorn.Server(config)
available_directories = [
"material", # lecture material
"transcripts", # Ai based lecture transcript
"summaries", # Ai summerization of transcripts
"videos" # the recorded video
]
create_directories(available_directories)
self.db_handler = DBHandler()
# self.instance = ThreadedUvicorn(config)
def configure_routes(self):
# @self.app.get("/list-directory")
# async def list_directory():
# available_directories = {
# "material": [], # lecture material
# "transcripts": [], # Ai based lecture transcript
# "summaries": [], # Ai summerization of transcripts
# "videos": [] # the recorded video
# }
# files = []
# for directory in available_directories:
# try:
# available_directories[directory] ={"content":os.listdir("data/" + directory)}
# except FileNotFoundError:
# return {"message": "error: recreate directories"}
# return json.dumps(available_directories)
@self.app.get("/list-directory/material")
async def list_directory():
files = []
for file in os.listdir("data\material"):
try:
files.append(file)
# available_directories[directory] ={"content":os.listdir("data/" + directory)}
except FileNotFoundError:
return {"message": "error: recreate directories"}
print(files)
print(list(map(lambda file: file, files)))
return list(map(lambda file: file, files))
@self.app.get("/list-directory/summaries")
async def list_directory():
files = []
for file in os.listdir("data\summaries"):
try:
files.append(file)
# available_directories[directory] ={"content":os.listdir("data/" + directory)}
except FileNotFoundError:
return {"message": "error: recreate directories"}
print(files)
print(list(map(lambda file: file, files)))
return list(map(lambda file: file, files))
@self.app.get("/list-directory/transcripts")
async def list_directory():
files = []
for file in os.listdir("data/transcripts"):
try:
files.append(file)
# available_directories[directory] ={"content":os.listdir("data/" + directory)}
except FileNotFoundError:
return {"message": "error: recreate directories"}
print(files)
print(list(map(lambda file: file, files)))
return list(map(lambda file: file, files))
@self.app.get("/list-directory/videos")
async def list_directory():
files = []
for file in os.listdir("data/videos"):
try:
files.append(file)
# available_directories[directory] ={"content":os.listdir("data/" + directory)}
except FileNotFoundError:
return {"message": "error: recreate directories"}
print(files)
print(list(map(lambda file: file, files)))
return list(map(lambda file: file, files))
@self.app.post("/attend/")
async def attend(attendance: Attendance):
#attendence in db
exists = self.db_handler.add_student(attendance.userId,attendance.user)
recorded_before = self.db_handler.check_exist(attendance.userId, attendance.classId)
if(exists):
print("userid already exists recording attendence")
print("recorded_before: ",recorded_before)
if(not recorded_before):
print("adding new dummy records")
lesson_count = self.db_handler.get_last_lesson(attendance.classId) + 1
for idx in range(1,lesson_count):
print(f"record[{idx}] added")
self.db_handler.add_attendance(attendance.userId, attendance.classId,idx, False)
self.db_handler.set_attendance(attendance.userId, attendance.classId,attendance.lessonId, True)
print(attendance)
return {"message": f"{attendance.user} attendance for {attendance.lessonId} recorded"}
# @self.app.get("/download")
# def download_file(directory: str, file_name: str):
# file_path = "./data/" + directory + '/' + file_name
# if not os.path.exists(file_path):
# print(file_path)
# raise HTTPException(status_code=404, detail="File not found")
# def file_generator():
# with open(file_path, "rb") as file:
# yield from file
# return StreamingResponse(content=file_generator(), media_type="application/pdf")
@self.app.get('/material/{filename}')
async def download_file(filename: str = Path(...)):
directory = 'data/material' # Set the directory where the files are stored
print("hi i've been called material download")
# Validate the requested file against a whitelist if needed
# whitelist = ['file1.txt', 'file2.pdf']
# if filename not in whitelist:
# raise HTTPException(status_code=404, detail='File not found')
return FileResponse(f'{directory}/{filename}', filename=filename, media_type='application/octet-stream')
@self.app.get('/summaries/{filename}')
async def download_file(filename: str = Path(...)):
directory = 'data/summaries' # Set the directory where the files are stored
print("hi i've been called summaries download")
# Validate the requested file against a whitelist if needed
# whitelist = ['file1.txt', 'file2.pdf']
# if filename not in whitelist:
# raise HTTPException(status_code=404, detail='File not found')
return FileResponse(f'{directory}/{filename}', filename=filename, media_type='application/octet-stream')
@self.app.get('/transcripts/{filename}')
async def download_file(filename: str = Path(...)):
directory = 'data/transcripts' # Set the directory where the files are stored
print("hi i've been called transcripts download")
# Validate the requested file against a whitelist if needed
# whitelist = ['file1.txt', 'file2.pdf']
# if filename not in whitelist:
# raise HTTPException(status_code=404, detail='File not found')
return FileResponse(f'{directory}/{filename}', filename=filename, media_type='application/octet-stream')
@self.app.get('/videos/{filename}')
async def download_file(filename: str = Path(...)):
directory = 'data/videos' # Set the directory where the files are stored
print("hi i've been called videos download")
# Validate the requested file against a whitelist if needed
# whitelist = ['file1.txt', 'file2.pdf']
# if filename not in whitelist:
# raise HTTPException(status_code=404, detail='File not found')
return FileResponse(f'{directory}/{filename}', filename=filename, media_type='application/octet-stream')
@self.app.get("/OK")
def health_check():
return {"message": "alive and well","code":0}
# for testing purposes testing
@self.app.get("/stop")
def stop():
# self.instance.stop()
self.server.should_exit = True
print("exitting...")
def stop(self):
# self.instance.stop()
self.server.should_exit = True
print("exitting...")
def start(self):
self.configure_routes()
self.server.run()
if __name__ == "__main__":
load_dotenv()
test = APIWrapper()
test.start()
# if(port == None):
# port = 8000
# uvicorn.run(app, host="0.0.0.0", port=int(port))