|
from fastapi import APIRouter, File, UploadFile, Request, WebSocket, WebSocketDisconnect |
|
from fastapi.responses import HTMLResponse, RedirectResponse |
|
from fastapi.templating import Jinja2Templates |
|
from app.modules.embedding import process_and_store_file |
|
import shutil |
|
import os |
|
import uuid |
|
import asyncio |
|
|
|
router = APIRouter() |
|
|
|
|
|
UPLOAD_DIRECTORY = "./uploaded_files" |
|
if not os.path.exists(UPLOAD_DIRECTORY): |
|
os.makedirs(UPLOAD_DIRECTORY, exist_ok=True) |
|
os.chmod(UPLOAD_DIRECTORY, 0o777) |
|
|
|
|
|
templates = Jinja2Templates(directory="app/templates") |
|
|
|
|
|
connections = {} |
|
|
|
@router.get("/", response_class=HTMLResponse) |
|
async def main(request: Request): |
|
return templates.TemplateResponse("upload.html", {"request": request}) |
|
|
|
@router.post("/uploadfile/{user_id}/") |
|
async def upload_file(user_id: str, file: UploadFile = File(...)): |
|
|
|
unique_filename = f"{uuid.uuid4()}_{file.filename}" |
|
file_location = os.path.join(UPLOAD_DIRECTORY, unique_filename) |
|
|
|
|
|
try: |
|
with open(file_location, "wb") as buffer: |
|
shutil.copyfileobj(file.file, buffer) |
|
print(f"File saved at {file_location}") |
|
except Exception as e: |
|
return {"error": f"ํ์ผ ์ ์ฅ ์ค๋ฅ: {e}"} |
|
|
|
|
|
asyncio.create_task(process_and_store_file(file_location, user_id, connections.get(user_id), UPLOAD_DIRECTORY)) |
|
|
|
return {"info": f"File '{file.filename}' uploaded successfully."} |
|
|
|
@router.websocket("/ws/{user_id}") |
|
async def websocket_endpoint(websocket: WebSocket, user_id: str): |
|
await websocket.accept() |
|
connections[user_id] = websocket |
|
try: |
|
while True: |
|
data = await websocket.receive_text() |
|
print(f"Received from {user_id}: {data}") |
|
except WebSocketDisconnect: |
|
print(f"User {user_id} disconnected") |
|
del connections[user_id] |
|
except Exception as e: |
|
print(f"Error with user {user_id}: {e}") |
|
del connections[user_id] |
|
|