utils.py 2.19 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
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
from fastapi import APIRouter, UploadFile, File, BackgroundTasks
from fastapi import Depends, HTTPException, status
from starlette.responses import StreamingResponse

from pydantic import BaseModel

from utils.misc import calculate_sha256
import requests


import os
import asyncio
import json
from config import OLLAMA_API_BASE_URL


router = APIRouter()


class UploadBlobForm(BaseModel):
    filename: str


@router.post("/upload")
async def upload(file: UploadFile = File(...)):
    os.makedirs("./uploads", exist_ok=True)
    file_path = os.path.join("./uploads", file.filename)

    def file_write_stream():
        total = 0
        total_size = file.size
        chunk_size = 1024 * 1024

        done = False
        try:
            with open(file_path, "wb") as f:
                while True:
                    chunk = file.file.read(chunk_size)
                    if not chunk:
                        break
                    f.write(chunk)
                    total += len(chunk)
                    done = total_size == total

                    res = {
                        "total": total_size,
                        "uploaded": total,
                    }

                    yield f"data: {json.dumps(res)}\n\n"

                if done:
                    with open(file_path, "rb") as f:
                        hashed = calculate_sha256(f)

                        f.seek(0)
                        file_data = f.read()

                        url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"

                        response = requests.post(url, data=file_data)

                        if response.ok:
                            res = {
                                "done": done,
                                "blob": f"sha256:{hashed}",
                            }
                            os.remove(file_path)

                            yield f"data: {json.dumps(res)}\n\n"
                        else:
                            raise "Ollama: Could not create blob, Please try again."

        except Exception as e:
            res = {"error": str(e)}
            yield f"data: {json.dumps(res)}\n\n"

    return StreamingResponse(file_write_stream(), media_type="text/event-stream")