utils.py 4.55 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
2
3
4
5
6
7
8
from fastapi import APIRouter, UploadFile, File, BackgroundTasks
from fastapi import Depends, HTTPException, status
from starlette.responses import StreamingResponse

from pydantic import BaseModel

import requests
import os
9
import aiohttp
Timothy J. Baek's avatar
Timothy J. Baek committed
10
import json
11
12
13
14


from utils.misc import calculate_sha256

Timothy J. Baek's avatar
Timothy J. Baek committed
15
16
17
18
19
20
21
22
23
24
from config import OLLAMA_API_BASE_URL


router = APIRouter()


class UploadBlobForm(BaseModel):
    filename: str


Timothy J. Baek's avatar
Timothy J. Baek committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from urllib.parse import urlparse


def parse_huggingface_url(hf_url):
    # Parse the URL
    parsed_url = urlparse(hf_url)

    # Get the path and split it into components
    path_components = parsed_url.path.split("/")

    # Extract the desired output
    user_repo = "/".join(path_components[1:3])
    model_file = path_components[-1]

    return [user_repo, model_file]


42
async def download_file_stream(url, file_path, chunk_size=1024 * 1024):
Timothy J. Baek's avatar
Timothy J. Baek committed
43
44
45
46
47
48
49
50
51
    done = False

    if os.path.exists(file_path):
        current_size = os.path.getsize(file_path)
    else:
        current_size = 0

    headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    timeout = aiohttp.ClientTimeout(total=60)  # Set the timeout

    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get(url, headers=headers) as response:
            total_size = int(response.headers.get("content-length", 0)) + current_size

            with open(file_path, "ab+") as file:
                async for data in response.content.iter_chunked(chunk_size):
                    current_size += len(data)
                    file.write(data)

                    done = current_size == total_size
                    progress = round((current_size / total_size) * 100, 2)
                    yield f'data: {{"progress": {progress}, "current": {current_size}, "total": {total_size}}}\n\n'

                if done:
                    file.seek(0)
                    hashed = calculate_sha256(file)
                    file.seek(0)
Timothy J. Baek's avatar
Timothy J. Baek committed
71

72
73
                    url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
                    response = requests.post(url, data=file)
Timothy J. Baek's avatar
Timothy J. Baek committed
74

75
76
77
78
79
80
                    if response.ok:
                        res = {
                            "done": done,
                            "blob": f"sha256:{hashed}",
                        }
                        os.remove(file_path)
Timothy J. Baek's avatar
Timothy J. Baek committed
81

82
83
84
                        yield f"data: {json.dumps(res)}\n\n"
                    else:
                        raise "Ollama: Could not create blob, Please try again."
Timothy J. Baek's avatar
Timothy J. Baek committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100


@router.get("/download")
async def download(
    url: str = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf",
):
    user_repo, model_file = parse_huggingface_url(url)

    os.makedirs("./uploads", exist_ok=True)
    file_path = os.path.join("./uploads", f"{model_file}")

    return StreamingResponse(
        download_file_stream(url, file_path), media_type="text/event-stream"
    )


Timothy J. Baek's avatar
Timothy J. Baek committed
101
102
103
104
105
@router.post("/upload")
async def upload(file: UploadFile = File(...)):
    os.makedirs("./uploads", exist_ok=True)
    file_path = os.path.join("./uploads", file.filename)

Timothy J. Baek's avatar
Timothy J. Baek committed
106
    async def file_write_stream():
Timothy J. Baek's avatar
Timothy J. Baek committed
107
108
109
110
111
112
        total = 0
        total_size = file.size
        chunk_size = 1024 * 1024

        done = False
        try:
Timothy J. Baek's avatar
Timothy J. Baek committed
113
            with open(file_path, "wb+") as f:
Timothy J. Baek's avatar
Timothy J. Baek committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
                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:
Timothy J. Baek's avatar
Timothy J. Baek committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
                    f.seek(0)
                    hashed = calculate_sha256(f)
                    f.seek(0)

                    url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
                    response = requests.post(url, data=f)

                    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."
Timothy J. Baek's avatar
Timothy J. Baek committed
147
148
149
150
151
152

        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")