File size: 2,162 Bytes
ff72db3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")

# WebSocket ์—ฐ๊ฒฐ ๊ด€๋ฆฌ
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  # 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]  # ์—ฐ๊ฒฐ ์ œ๊ฑฐ