pensiev 0.25.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- memos/__init__.py +6 -0
- memos/cmds/__init__.py +0 -0
- memos/cmds/library.py +1289 -0
- memos/cmds/plugin.py +96 -0
- memos/commands.py +865 -0
- memos/config.py +225 -0
- memos/crud.py +605 -0
- memos/databases/__init__.py +0 -0
- memos/databases/initializers.py +481 -0
- memos/dataset_extractor_for_florence.py +165 -0
- memos/dataset_extractor_for_internvl2.py +192 -0
- memos/default_config.yaml +88 -0
- memos/embedding.py +129 -0
- memos/frame_extractor.py +53 -0
- memos/logging_config.py +35 -0
- memos/main.py +104 -0
- memos/migrations/alembic/README +1 -0
- memos/migrations/alembic/__pycache__/env.cpython-310.pyc +0 -0
- memos/migrations/alembic/env.py +108 -0
- memos/migrations/alembic/script.py.mako +30 -0
- memos/migrations/alembic/versions/00904ac8c6fc_add_indexes_to_entitymodel.py +63 -0
- memos/migrations/alembic/versions/04acdaf75664_add_indices_to_entitytags_and_metadata.py +86 -0
- memos/migrations/alembic/versions/12504c5b1d3c_add_extra_columns_for_embedding.py +67 -0
- memos/migrations/alembic/versions/31a1ad0e10b3_add_entity_plugin_status.py +71 -0
- memos/migrations/alembic/versions/__pycache__/00904ac8c6fc_add_indexes_to_entitymodel.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/04acdaf75664_add_indices_to_entitytags_and_metadata.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/12504c5b1d3c_add_extra_columns_for_embedding.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/20f5ecab014d_add_entity_plugin_status.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/31a1ad0e10b3_add_entity_plugin_status.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/4fcb062c5128_add_extra_columns_for_embedding.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/d10c55fbb7d2_add_index_for_entity_file_type_group_.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/__pycache__/f8f158182416_add_active_app_index.cpython-310.pyc +0 -0
- memos/migrations/alembic/versions/d10c55fbb7d2_add_index_for_entity_file_type_group_.py +44 -0
- memos/migrations/alembic/versions/f8f158182416_add_active_app_index.py +75 -0
- memos/migrations/alembic.ini +116 -0
- memos/migrations.py +19 -0
- memos/models.py +199 -0
- memos/plugins/__init__.py +0 -0
- memos/plugins/ocr/__init__.py +0 -0
- memos/plugins/ocr/main.py +251 -0
- memos/plugins/ocr/models/ch_PP-OCRv4_det_infer.onnx +0 -0
- memos/plugins/ocr/models/ch_PP-OCRv4_rec_infer.onnx +0 -0
- memos/plugins/ocr/models/ch_ppocr_mobile_v2.0_cls_train.onnx +0 -0
- memos/plugins/ocr/ppocr-gpu.yaml +43 -0
- memos/plugins/ocr/ppocr.yaml +44 -0
- memos/plugins/ocr/server.py +227 -0
- memos/plugins/ocr/temp_ppocr.yaml +42 -0
- memos/plugins/vlm/__init__.py +0 -0
- memos/plugins/vlm/main.py +251 -0
- memos/prepare_dataset.py +107 -0
- memos/process_webp.py +55 -0
- memos/read_metadata.py +32 -0
- memos/record.py +358 -0
- memos/schemas.py +289 -0
- memos/search.py +1198 -0
- memos/server.py +883 -0
- memos/shotsum.py +105 -0
- memos/shotsum_with_ocr.py +145 -0
- memos/simple_tokenizer/dict/README.md +31 -0
- memos/simple_tokenizer/dict/hmm_model.utf8 +34 -0
- memos/simple_tokenizer/dict/idf.utf8 +258826 -0
- memos/simple_tokenizer/dict/jieba.dict.utf8 +348982 -0
- memos/simple_tokenizer/dict/pos_dict/char_state_tab.utf8 +6653 -0
- memos/simple_tokenizer/dict/pos_dict/prob_emit.utf8 +166 -0
- memos/simple_tokenizer/dict/pos_dict/prob_start.utf8 +259 -0
- memos/simple_tokenizer/dict/pos_dict/prob_trans.utf8 +5222 -0
- memos/simple_tokenizer/dict/stop_words.utf8 +1534 -0
- memos/simple_tokenizer/dict/user.dict.utf8 +4 -0
- memos/simple_tokenizer/linux/libsimple.so +0 -0
- memos/simple_tokenizer/macos/libsimple.dylib +0 -0
- memos/simple_tokenizer/windows/simple.dll +0 -0
- memos/static/_app/immutable/assets/0.e250c031.css +1 -0
- memos/static/_app/immutable/assets/_layout.e7937cfe.css +1 -0
- memos/static/_app/immutable/chunks/index.5c08976b.js +1 -0
- memos/static/_app/immutable/chunks/index.60ee613b.js +4 -0
- memos/static/_app/immutable/chunks/runtime.a7926cf6.js +5 -0
- memos/static/_app/immutable/chunks/scheduler.5c1cff6e.js +1 -0
- memos/static/_app/immutable/chunks/singletons.583bdf4e.js +1 -0
- memos/static/_app/immutable/entry/app.666c1643.js +1 -0
- memos/static/_app/immutable/entry/start.aed5c701.js +3 -0
- memos/static/_app/immutable/nodes/0.5862ea38.js +7 -0
- memos/static/_app/immutable/nodes/1.35378a5e.js +1 -0
- memos/static/_app/immutable/nodes/2.1ccf9ea5.js +81 -0
- memos/static/_app/version.json +1 -0
- memos/static/app.html +36 -0
- memos/static/favicon.png +0 -0
- memos/static/logos/memos_logo_1024.png +0 -0
- memos/static/logos/memos_logo_1024@2x.png +0 -0
- memos/static/logos/memos_logo_128.png +0 -0
- memos/static/logos/memos_logo_128@2x.png +0 -0
- memos/static/logos/memos_logo_16.png +0 -0
- memos/static/logos/memos_logo_16@2x.png +0 -0
- memos/static/logos/memos_logo_256.png +0 -0
- memos/static/logos/memos_logo_256@2x.png +0 -0
- memos/static/logos/memos_logo_32.png +0 -0
- memos/static/logos/memos_logo_32@2x.png +0 -0
- memos/static/logos/memos_logo_512.png +0 -0
- memos/static/logos/memos_logo_512@2x.png +0 -0
- memos/static/logos/memos_logo_64.png +0 -0
- memos/static/logos/memos_logo_64@2x.png +0 -0
- memos/test_server.py +802 -0
- memos/utils.py +49 -0
- memos_ml_backends/florence2_server.py +176 -0
- memos_ml_backends/qwen2vl_server.py +182 -0
- memos_ml_backends/schemas.py +48 -0
- pensiev-0.25.5.dist-info/LICENSE +201 -0
- pensiev-0.25.5.dist-info/METADATA +541 -0
- pensiev-0.25.5.dist-info/RECORD +111 -0
- pensiev-0.25.5.dist-info/WHEEL +5 -0
- pensiev-0.25.5.dist-info/entry_points.txt +2 -0
- pensiev-0.25.5.dist-info/top_level.txt +2 -0
memos/utils.py
ADDED
@@ -0,0 +1,49 @@
|
|
1
|
+
from PIL import Image
|
2
|
+
import piexif
|
3
|
+
from PIL.PngImagePlugin import PngInfo
|
4
|
+
import json
|
5
|
+
|
6
|
+
|
7
|
+
def write_image_metadata(image_path, metadata):
|
8
|
+
img = Image.open(image_path)
|
9
|
+
image_path_str = str(image_path)
|
10
|
+
|
11
|
+
if image_path_str.lower().endswith((".jpg", ".jpeg", ".tiff", ".webp")):
|
12
|
+
exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "thumbnail": None}
|
13
|
+
exif_dict["0th"][piexif.ImageIFD.ImageDescription] = json.dumps(
|
14
|
+
metadata
|
15
|
+
).encode("utf-8")
|
16
|
+
exif_bytes = piexif.dump(exif_dict)
|
17
|
+
img.save(image_path, exif=exif_bytes)
|
18
|
+
elif image_path_str.lower().endswith(".png"):
|
19
|
+
metadata_info = PngInfo()
|
20
|
+
metadata_info.add_text("Description", json.dumps(metadata))
|
21
|
+
img.save(image_path, "PNG", pnginfo=metadata_info)
|
22
|
+
else:
|
23
|
+
print(f"Skipping unsupported file format: {image_path_str}")
|
24
|
+
|
25
|
+
|
26
|
+
def get_image_metadata(image_path):
|
27
|
+
img = Image.open(image_path)
|
28
|
+
image_path_str = str(image_path)
|
29
|
+
|
30
|
+
if image_path_str.lower().endswith((".jpg", ".jpeg", ".tiff", ".webp")):
|
31
|
+
try:
|
32
|
+
exif_dict = piexif.load(image_path_str)
|
33
|
+
existing_description = exif_dict["0th"].get(
|
34
|
+
piexif.ImageIFD.ImageDescription, b"{}"
|
35
|
+
)
|
36
|
+
return json.loads(existing_description.decode("utf-8"))
|
37
|
+
except Exception as e:
|
38
|
+
print(f"Error decoding EXIF metadata for {image_path_str}: {e}")
|
39
|
+
return None
|
40
|
+
elif image_path_str.lower().endswith(".png"):
|
41
|
+
existing_description = img.info.get("Description", "{}")
|
42
|
+
try:
|
43
|
+
return json.loads(existing_description)
|
44
|
+
except json.JSONDecodeError as e:
|
45
|
+
print(f"Error decoding PNG metadata for {image_path_str}: {e}")
|
46
|
+
return None
|
47
|
+
else:
|
48
|
+
print(f"Unsupported file format: {image_path_str}")
|
49
|
+
return None
|
@@ -0,0 +1,176 @@
|
|
1
|
+
from fastapi import FastAPI, HTTPException
|
2
|
+
from pydantic import BaseModel
|
3
|
+
from typing import List, Dict, Any, Optional
|
4
|
+
import httpx
|
5
|
+
import torch
|
6
|
+
from PIL import Image
|
7
|
+
import base64
|
8
|
+
import io
|
9
|
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
10
|
+
import time
|
11
|
+
from memos_ml_backends.schemas import (
|
12
|
+
ChatCompletionRequest,
|
13
|
+
ChatCompletionResponse,
|
14
|
+
ModelData,
|
15
|
+
ModelsResponse,
|
16
|
+
get_image_from_url,
|
17
|
+
)
|
18
|
+
|
19
|
+
MODEL_INFO = {"name": "florence2-base-ft", "max_model_len": 2048}
|
20
|
+
|
21
|
+
# 检测可用的设备
|
22
|
+
if torch.cuda.is_available():
|
23
|
+
device = torch.device("cuda")
|
24
|
+
elif torch.backends.mps.is_available():
|
25
|
+
device = torch.device("mps")
|
26
|
+
else:
|
27
|
+
device = torch.device("cpu")
|
28
|
+
|
29
|
+
torch_dtype = (
|
30
|
+
torch.float32
|
31
|
+
if (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] <= 6)
|
32
|
+
or (not torch.cuda.is_available() and not torch.backends.mps.is_available())
|
33
|
+
else torch.float16
|
34
|
+
)
|
35
|
+
print(f"Using device: {device}")
|
36
|
+
|
37
|
+
# Load Florence-2 model
|
38
|
+
florence_model = AutoModelForCausalLM.from_pretrained(
|
39
|
+
"microsoft/Florence-2-base-ft",
|
40
|
+
torch_dtype=torch_dtype,
|
41
|
+
attn_implementation="sdpa",
|
42
|
+
trust_remote_code=True,
|
43
|
+
).to(device, torch_dtype)
|
44
|
+
florence_processor = AutoProcessor.from_pretrained(
|
45
|
+
"microsoft/Florence-2-base-ft", trust_remote_code=True
|
46
|
+
)
|
47
|
+
|
48
|
+
app = FastAPI()
|
49
|
+
|
50
|
+
|
51
|
+
async def generate_florence_result(text_input, image_input, max_tokens):
|
52
|
+
task_prompt = "<MORE_DETAILED_CAPTION>"
|
53
|
+
prompt = task_prompt + ""
|
54
|
+
|
55
|
+
inputs = florence_processor(
|
56
|
+
text=prompt, images=image_input, return_tensors="pt"
|
57
|
+
).to(device, torch_dtype)
|
58
|
+
|
59
|
+
generated_ids = florence_model.generate(
|
60
|
+
input_ids=inputs["input_ids"],
|
61
|
+
pixel_values=inputs["pixel_values"],
|
62
|
+
max_new_tokens=max_tokens or 1024,
|
63
|
+
do_sample=False,
|
64
|
+
num_beams=3,
|
65
|
+
)
|
66
|
+
|
67
|
+
generated_texts = florence_processor.batch_decode(
|
68
|
+
generated_ids, skip_special_tokens=False
|
69
|
+
)
|
70
|
+
|
71
|
+
parsed_answer = florence_processor.post_process_generation(
|
72
|
+
generated_texts[0],
|
73
|
+
task=task_prompt,
|
74
|
+
image_size=(image_input.width, image_input.height),
|
75
|
+
)
|
76
|
+
|
77
|
+
return parsed_answer.get(task_prompt, "")
|
78
|
+
|
79
|
+
|
80
|
+
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
|
81
|
+
async def chat_completions(request: ChatCompletionRequest):
|
82
|
+
try:
|
83
|
+
last_message = request.messages[-1]
|
84
|
+
text_input = last_message.get("content", "")
|
85
|
+
image_input = None
|
86
|
+
|
87
|
+
if isinstance(text_input, list):
|
88
|
+
for content in text_input:
|
89
|
+
if content.get("type") == "image_url":
|
90
|
+
image_url = content["image_url"].get("url")
|
91
|
+
image_input = await get_image_from_url(image_url)
|
92
|
+
break
|
93
|
+
text_input = " ".join(
|
94
|
+
[
|
95
|
+
content["text"]
|
96
|
+
for content in text_input
|
97
|
+
if content.get("type") == "text"
|
98
|
+
]
|
99
|
+
)
|
100
|
+
|
101
|
+
if image_input is None:
|
102
|
+
raise ValueError("Image input is required")
|
103
|
+
|
104
|
+
parsed_answer = await generate_florence_result(
|
105
|
+
text_input, image_input, request.max_tokens
|
106
|
+
)
|
107
|
+
|
108
|
+
result = ChatCompletionResponse(
|
109
|
+
id=str(int(time.time())),
|
110
|
+
object="chat.completion",
|
111
|
+
created=int(time.time()),
|
112
|
+
model=request.model,
|
113
|
+
choices=[
|
114
|
+
{
|
115
|
+
"index": 0,
|
116
|
+
"message": {
|
117
|
+
"role": "assistant",
|
118
|
+
"content": parsed_answer,
|
119
|
+
},
|
120
|
+
"finish_reason": "stop",
|
121
|
+
}
|
122
|
+
],
|
123
|
+
usage={
|
124
|
+
"prompt_tokens": 0,
|
125
|
+
"total_tokens": 0,
|
126
|
+
"completion_tokens": 0,
|
127
|
+
},
|
128
|
+
)
|
129
|
+
|
130
|
+
return result
|
131
|
+
except Exception as e:
|
132
|
+
print(f"Error generating chat completion: {str(e)}")
|
133
|
+
raise HTTPException(
|
134
|
+
status_code=500, detail=f"Error generating chat completion: {str(e)}"
|
135
|
+
)
|
136
|
+
|
137
|
+
|
138
|
+
@app.get("/v1/models", response_model=ModelsResponse)
|
139
|
+
async def get_models():
|
140
|
+
model_data = ModelData(
|
141
|
+
id=MODEL_INFO["name"],
|
142
|
+
created=int(time.time()),
|
143
|
+
max_model_len=MODEL_INFO["max_model_len"],
|
144
|
+
permission=[
|
145
|
+
{
|
146
|
+
"id": f"modelperm-{MODEL_INFO['name']}",
|
147
|
+
"object": "model_permission",
|
148
|
+
"created": int(time.time()),
|
149
|
+
"allow_create_engine": False,
|
150
|
+
"allow_sampling": False,
|
151
|
+
"allow_logprobs": False,
|
152
|
+
"allow_search_indices": False,
|
153
|
+
"allow_view": False,
|
154
|
+
"allow_fine_tuning": False,
|
155
|
+
"organization": "*",
|
156
|
+
"group": None,
|
157
|
+
"is_blocking": False,
|
158
|
+
}
|
159
|
+
],
|
160
|
+
)
|
161
|
+
|
162
|
+
return ModelsResponse(data=[model_data])
|
163
|
+
|
164
|
+
|
165
|
+
if __name__ == "__main__":
|
166
|
+
import argparse
|
167
|
+
import uvicorn
|
168
|
+
|
169
|
+
parser = argparse.ArgumentParser(description="Run the Florence-2 server")
|
170
|
+
parser.add_argument(
|
171
|
+
"--port", type=int, default=8000, help="Port to run the server on"
|
172
|
+
)
|
173
|
+
args = parser.parse_args()
|
174
|
+
|
175
|
+
print("Using Florence-2 model")
|
176
|
+
uvicorn.run(app, host="0.0.0.0", port=args.port)
|
@@ -0,0 +1,182 @@
|
|
1
|
+
from fastapi import FastAPI, HTTPException
|
2
|
+
import torch
|
3
|
+
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
4
|
+
from qwen_vl_utils import process_vision_info
|
5
|
+
import time
|
6
|
+
from memos_ml_backends.schemas import (
|
7
|
+
ChatCompletionRequest,
|
8
|
+
ChatCompletionResponse,
|
9
|
+
ModelData,
|
10
|
+
ModelsResponse,
|
11
|
+
get_image_from_url,
|
12
|
+
)
|
13
|
+
|
14
|
+
MODEL_INFO = {"name": "Qwen2-VL-2B-Instruct", "max_model_len": 32768}
|
15
|
+
|
16
|
+
# 检测可用的设备
|
17
|
+
if torch.cuda.is_available():
|
18
|
+
device = torch.device("cuda")
|
19
|
+
elif torch.backends.mps.is_available():
|
20
|
+
device = torch.device("mps")
|
21
|
+
else:
|
22
|
+
device = torch.device("cpu")
|
23
|
+
|
24
|
+
torch_dtype = (
|
25
|
+
torch.float32
|
26
|
+
if (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] <= 6)
|
27
|
+
or (not torch.cuda.is_available() and not torch.backends.mps.is_available())
|
28
|
+
else torch.float16
|
29
|
+
)
|
30
|
+
print(f"Using device: {device}")
|
31
|
+
|
32
|
+
# Load Qwen2VL model
|
33
|
+
qwen2vl_model = Qwen2VLForConditionalGeneration.from_pretrained(
|
34
|
+
"Qwen/Qwen2-VL-2B-Instruct",
|
35
|
+
torch_dtype=torch_dtype,
|
36
|
+
device_map="auto",
|
37
|
+
).to(device, torch_dtype)
|
38
|
+
qwen2vl_processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct-GPTQ-Int4")
|
39
|
+
|
40
|
+
app = FastAPI()
|
41
|
+
|
42
|
+
|
43
|
+
async def generate_qwen2vl_result(text_input, image_input, max_tokens):
|
44
|
+
messages = [
|
45
|
+
{
|
46
|
+
"role": "user",
|
47
|
+
"content": [
|
48
|
+
{"type": "image", "image": image_input},
|
49
|
+
{"type": "text", "text": text_input},
|
50
|
+
],
|
51
|
+
}
|
52
|
+
]
|
53
|
+
|
54
|
+
text = qwen2vl_processor.apply_chat_template(
|
55
|
+
messages, tokenize=False, add_generation_prompt=True
|
56
|
+
)
|
57
|
+
|
58
|
+
image_inputs, video_inputs = process_vision_info(messages)
|
59
|
+
|
60
|
+
inputs = qwen2vl_processor(
|
61
|
+
text=[text],
|
62
|
+
images=image_inputs,
|
63
|
+
videos=video_inputs,
|
64
|
+
padding=True,
|
65
|
+
return_tensors="pt",
|
66
|
+
)
|
67
|
+
inputs = inputs.to(device)
|
68
|
+
|
69
|
+
generated_ids = qwen2vl_model.generate(**inputs, max_new_tokens=(max_tokens or 512))
|
70
|
+
|
71
|
+
generated_ids_trimmed = [
|
72
|
+
out_ids[len(in_ids) :]
|
73
|
+
for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
74
|
+
]
|
75
|
+
|
76
|
+
output_text = qwen2vl_processor.batch_decode(
|
77
|
+
generated_ids_trimmed,
|
78
|
+
skip_special_tokens=True,
|
79
|
+
clean_up_tokenization_spaces=False,
|
80
|
+
)
|
81
|
+
|
82
|
+
return output_text[0] if output_text else ""
|
83
|
+
|
84
|
+
|
85
|
+
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
|
86
|
+
async def chat_completions(request: ChatCompletionRequest):
|
87
|
+
try:
|
88
|
+
last_message = request.messages[-1]
|
89
|
+
text_input = last_message.get("content", "")
|
90
|
+
image_input = None
|
91
|
+
|
92
|
+
if isinstance(text_input, list):
|
93
|
+
for content in text_input:
|
94
|
+
if content.get("type") == "image_url":
|
95
|
+
image_url = content["image_url"].get("url")
|
96
|
+
image_input = await get_image_from_url(image_url)
|
97
|
+
break
|
98
|
+
text_input = " ".join(
|
99
|
+
[
|
100
|
+
content["text"]
|
101
|
+
for content in text_input
|
102
|
+
if content.get("type") == "text"
|
103
|
+
]
|
104
|
+
)
|
105
|
+
|
106
|
+
if image_input is None:
|
107
|
+
raise ValueError("Image input is required")
|
108
|
+
|
109
|
+
parsed_answer = await generate_qwen2vl_result(
|
110
|
+
text_input, image_input, request.max_tokens
|
111
|
+
)
|
112
|
+
|
113
|
+
result = ChatCompletionResponse(
|
114
|
+
id=str(int(time.time())),
|
115
|
+
object="chat.completion",
|
116
|
+
created=int(time.time()),
|
117
|
+
model=request.model,
|
118
|
+
choices=[
|
119
|
+
{
|
120
|
+
"index": 0,
|
121
|
+
"message": {
|
122
|
+
"role": "assistant",
|
123
|
+
"content": parsed_answer,
|
124
|
+
},
|
125
|
+
"finish_reason": "stop",
|
126
|
+
}
|
127
|
+
],
|
128
|
+
usage={
|
129
|
+
"prompt_tokens": 0,
|
130
|
+
"total_tokens": 0,
|
131
|
+
"completion_tokens": 0,
|
132
|
+
},
|
133
|
+
)
|
134
|
+
|
135
|
+
return result
|
136
|
+
except Exception as e:
|
137
|
+
print(f"Error generating chat completion: {str(e)}")
|
138
|
+
raise HTTPException(
|
139
|
+
status_code=500, detail=f"Error generating chat completion: {str(e)}"
|
140
|
+
)
|
141
|
+
|
142
|
+
|
143
|
+
# 添加新的 GET /v1/models 端点
|
144
|
+
@app.get("/v1/models", response_model=ModelsResponse)
|
145
|
+
async def get_models():
|
146
|
+
model_data = ModelData(
|
147
|
+
id=MODEL_INFO["name"],
|
148
|
+
created=int(time.time()),
|
149
|
+
max_model_len=MODEL_INFO["max_model_len"],
|
150
|
+
permission=[
|
151
|
+
{
|
152
|
+
"id": f"modelperm-{MODEL_INFO['name']}",
|
153
|
+
"object": "model_permission",
|
154
|
+
"created": int(time.time()),
|
155
|
+
"allow_create_engine": False,
|
156
|
+
"allow_sampling": False,
|
157
|
+
"allow_logprobs": False,
|
158
|
+
"allow_search_indices": False,
|
159
|
+
"allow_view": False,
|
160
|
+
"allow_fine_tuning": False,
|
161
|
+
"organization": "*",
|
162
|
+
"group": None,
|
163
|
+
"is_blocking": False,
|
164
|
+
}
|
165
|
+
],
|
166
|
+
)
|
167
|
+
|
168
|
+
return ModelsResponse(data=[model_data])
|
169
|
+
|
170
|
+
|
171
|
+
if __name__ == "__main__":
|
172
|
+
import argparse
|
173
|
+
import uvicorn
|
174
|
+
|
175
|
+
parser = argparse.ArgumentParser(description="Run the Qwen2VL server")
|
176
|
+
parser.add_argument(
|
177
|
+
"--port", type=int, default=8000, help="Port to run the server on"
|
178
|
+
)
|
179
|
+
args = parser.parse_args()
|
180
|
+
|
181
|
+
print("Using Qwen2VL model")
|
182
|
+
uvicorn.run(app, host="0.0.0.0", port=args.port)
|
@@ -0,0 +1,48 @@
|
|
1
|
+
from pydantic import BaseModel
|
2
|
+
from typing import List, Dict, Any, Optional
|
3
|
+
import httpx
|
4
|
+
from PIL import Image
|
5
|
+
import base64
|
6
|
+
import io
|
7
|
+
|
8
|
+
class ChatCompletionRequest(BaseModel):
|
9
|
+
model: str
|
10
|
+
messages: List[Dict[str, Any]]
|
11
|
+
max_tokens: Optional[int] = None
|
12
|
+
|
13
|
+
class ChatCompletionResponse(BaseModel):
|
14
|
+
id: str
|
15
|
+
object: str
|
16
|
+
created: int
|
17
|
+
model: str
|
18
|
+
choices: List[Dict[str, Any]]
|
19
|
+
usage: Dict[str, int]
|
20
|
+
|
21
|
+
class ModelData(BaseModel):
|
22
|
+
id: str
|
23
|
+
object: str = "model"
|
24
|
+
created: int
|
25
|
+
owned_by: str = "transformers"
|
26
|
+
root: str = "models"
|
27
|
+
parent: Optional[str] = None
|
28
|
+
max_model_len: int
|
29
|
+
permission: List[Dict[str, Any]]
|
30
|
+
|
31
|
+
class ModelsResponse(BaseModel):
|
32
|
+
object: str = "list"
|
33
|
+
data: List[ModelData]
|
34
|
+
|
35
|
+
async def get_image_from_url(image_url):
|
36
|
+
if image_url.startswith("data:image/"):
|
37
|
+
image_data = base64.b64decode(image_url.split(",")[1])
|
38
|
+
return Image.open(io.BytesIO(image_data))
|
39
|
+
elif image_url.startswith("file://"):
|
40
|
+
file_path = image_url[len("file://") :]
|
41
|
+
return Image.open(file_path)
|
42
|
+
else:
|
43
|
+
async with httpx.AsyncClient() as client:
|
44
|
+
response = await client.get(image_url)
|
45
|
+
response.raise_for_status()
|
46
|
+
image_data = response.content
|
47
|
+
return Image.open(io.BytesIO(image_data))
|
48
|
+
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2024 Arkohut
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|