Upload 8 files
Browse filesFiles changed (8)
- app.py+26-181
- config.pyAdded+12
- models.pyAdded+25
- requirements.txt+9-5
- routes.pyAdded+61
- services.pyAdded+35
- test.pyAdded+56
- utils.pyAdded+127
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181# !/usr/bin/python3# -*- coding: utf-8 -*-"""@Author : Ailove------------------------------------@File : hf_app.py@CreateTime : 2025/5/23 13:41------------------------------------"""import loggingimport jsonimport aiohttpimport requestsfrom requests.exceptions import RequestExceptionfrom fastapi import FastAPI, HTTPException, Request, status, Query, Bodyfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field# 配置日志logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI()XAI_API_BASE = "https://api.x.ai/v1"class ChatRequest(BaseModel):messages: list[dict] = Field(..., description="消息列表")model: str = Field(..., description="模型ID")max_tokens: int | None = Nonetemperature: float | None = Nonetop_p: float | None = Nonestream: bool = Falsepresence_penalty: float | None = Nonefrequency_penalty: float | None = Noneasync def stream_generator(response, stream):try:for chunk in response.iter_lines():if chunk:decoded_chunk = chunk.decode('utf-8')if decoded_chunk.startswith("data: "):yield f"data: {decoded_chunk[6:]}\n\n"else:yield f"data: {json.dumps({'error': 'Invalid chunk format'})}\n\n"except RequestException as e:yield f"data: {json.dumps({'error': str(e)})}\n\n"finally:if stream:response.close()@app.post("/v1/chat/completions")async def chat_completions(req: ChatRequest, request: Request):logger.info(f"收到请求: {req.dict()}")api_key = request.headers.get("Authorization", "").replace("Bearer ", "")if not api_key:logger.error("缺少API密钥")raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少API密钥")try:headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json","User-Agent": "SillyTavern-Proxy/1.0","Accept": "text/event-stream" if req.stream else "application/json",}payload = req.dict(exclude_unset=True)filtered_payload = {k: vfor k, v in payload.items()if k in ["messages", "model", "max_tokens", "temperature", "top_p", "stream"]}logger.info(f"转发到xAI的负载: {filtered_payload}")response = requests.post(f"{XAI_API_BASE}/chat/completions", headers=headers, json=filtered_payload, stream=req.stream, timeout=20)response.raise_for_status()if req.stream:return StreamingResponse(stream_generator(response, req.stream), media_type="text/event-stream")else:try:return response.json()except json.JSONDecodeError:logger.error(f"无效的JSON响应: {response.text}")raise HTTPException(status_code=502, detail="上游服务器返回无效响应")except RequestException as e:error_detail = ""if e.response is not None:try:error_detail = e.response.json().get("error", e.response.text)except json.JSONDecodeError:error_detail = e.response.text[:500]status_code = e.response.status_codeelse:error_detail = str(e)status_code = 504logger.error(f"请求失败: {error_detail}")raise HTTPException(status_code=status_code, detail=f"xAI API错误: {error_detail}")class QuestionRequest(BaseModel):text: str = Field(..., description="用户提出的问题")end_flag: bool = Truestreaming: bool = Falsemodel: str = Field(..., description="要使用的模型ID")@app.post("/v1/question")async def ask_question(params: str = Query(..., description="通过 URL 查询参数传递的 token"), req: QuestionRequest = Body(...)):try:auth_data = json.loads(params)except json.JSONDecodeError:raise HTTPException(status_code=400, detail="参数 `params` 必须是有效的 JSON 字符串")headers = {"content-type": "application/json","user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",}url = "https://api.journeydraw.ai/chatgpt/v3/question"data = {"text":req.text,"end_flag":req.end_flag,"streaming":req.streaming,"model": req.model,}async with aiohttp.ClientSession() as session:try:async with session.post(url, params=auth_data, json=data, headers=headers) as resp:return await resp.text()except Exception as e:error_detail = str(e)status_code = 504raise HTTPException(status_code=status_code, detail=f"xAI API错误: {error_detail}")# 保持原来的模型列表端点@app.get("/v1/models")async def get_models(request: Request):api_key = request.headers.get("Authorization", "").replace("Bearer ", "")if not api_key:raise HTTPException(status_code=401, detail="缺少API密钥")try:headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}response = requests.get(f"{XAI_API_BASE}/models", headers=headers, timeout=10)response.raise_for_status()return response.json()except RequestException as e:logger.warning(f"获取模型失败: {str(e)},返回备用数据")return {"object": "list","data": [{"id": "grok-3-beta", "object": "model", "created": 1744681729, "owned_by": "xAI"},{"id": "grok-3-mini-beta", "object": "model", "created": 1744681729, "owned_by": "xAI"},{"id": "grok-3-fast-beta", "object": "model", "created": 1744681729, "owned_by": "xAI"},{"id": "grok-3-mini-fast-beta", "object": "model", "created": 1744681729, "owned_by": "xAI"},],}@app.get("/health")async def health_check():return {"status": "healthy"}if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)1234567891011121314151617181920212223242526# !/usr/bin/python3# -*- coding: utf-8 -*-"""@Author : Ailove------------------------------------@File : app.py.py@CreateTime : 2025/5/22 18:02------------------------------------"""import loggingfrom fastapi import FastAPIfrom ImageSimilarity.routes import router# 配置日志logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI(title="Image Similarity Service")app.include_router(router)if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
123456789101112# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : config.py
@CreateTime : 2025/5/22 20:37
------------------------------------
"""
import os
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "model")12345678910111213141516171819202122232425# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : models.py
@CreateTime : 2025/5/22 20:36
------------------------------------
"""
from pydantic import BaseModel, Field
class ImageRequest(BaseModel):
url: str = None
class ImageCompareRequest(BaseModel):
img_1: str = None
url_1: str = None
img_2: str = None
url_2: str = None
class QuestionRequest(BaseModel):
text: str = Field(..., description="用户提出的问题")
end_flag: bool = True
streaming: bool = False
model: str = Field(..., description="要使用的模型ID")
12345fastapi==0.115.0uvicorn==0.30.6requests==2.32.3pydantic==2.9.2python-multipart123456789fastapi==0.115.0uvicorn==0.30.6requests==2.32.3pydantic==2.9.2python-multipartGPUtil==1.4.0onnxruntime==1.15.1opencv-python==4.7.0.72numpy==1.23.5
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : routes.py
@CreateTime : 2025/5/22 20:36
------------------------------------
"""
import json
import aiohttp
from fastapi.responses import JSONResponse
from fastapi import APIRouter, HTTPException, Query, Body
from ImageSimilarity.services import analyze_image
from .models import QuestionRequest
router = APIRouter()
@router.get("/")
async def root():
return {"message": "Hello World"}
@router.get("/health")
async def health_check():
return {"status": "healthy"}
@router.get("/image_similarity")
async def analyze(url: str = Query(..., description="通过 URL 查询参数传递的 url")):
try:
body = {'url': url}
data = analyze_image(body)
return JSONResponse(content=data, status_code=200)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.post("/v1/question")
async def ask_question(
params: str = Query(..., description="通过 URL 查询参数传递的 token"), req: QuestionRequest = Body(...)
):
try:
auth_data = json.loads(params)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="参数 `params` 必须是有效的 JSON 字符串")
headers = {
"content-type": "application/json",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
}
url = "https://api.journeydraw.ai/chatgpt/v3/question"
data = {"text": req.text, "end_flag": req.end_flag, "streaming": req.streaming, "model": req.model}
async with aiohttp.ClientSession() as session:
try:
async with session.post(url, params=auth_data, json=data, headers=headers) as resp:
return await resp.text()
except Exception as e:
error_detail = str(e)
status_code = 504
raise HTTPException(status_code=status_code, detail=f"xAI API错误: {error_detail}")1234567891011121314151617181920212223242526272829303132333435# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : services.py
@CreateTime : 2025/5/22 20:37
------------------------------------
"""
from ImageSimilarity.utils import readimg, is_bottom_third_blank, detect_features, get_embedding, get_cos_similar
def analyze_image(body):
inputs = readimg(body, keys=['url'])
img = list(inputs.values())[0]
if img is None:
raise ValueError("Image not found or invalid.")
result = {
"embedding": get_embedding(img).round(6).tolist(),
"blank": bool(is_bottom_third_blank(img)),
"features": detect_features(img)
}
return result
def compare_images(body):
print(body)
keys = ["img_1", "url_1", "img_2", "url_2"]
inputs = readimg(body, keys=[k for k in keys if k in body])
img1, img2 = inputs.get("img_1") or inputs.get("url_1"), inputs.get("img_2") or inputs.get("url_2")
if not img1 or not img2:
raise ValueError("Both images must be provided.")
emb1 = get_embedding(img1)
emb2 = get_embedding(img2)
sim = get_cos_similar(emb1, emb2)
return {"similarity": float(round(sim, 6))}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : test.py
@CreateTime : 2025/5/23 13:57
------------------------------------
"""
import json
import requests
import aiohttp
import asyncio
async def call_question_api():
url = "https://hf1024-grok-api.hf.space/v1/question"
auth_params = {'app_id': 'nc_ai_ng', 't': 1747982239, 'nonce': '25187cf7-d9e4-484f-25e8-5fdc097ea16f', 'sign': 'Ff+yi45SXkoGkvHxEDEaGpz83uQzJKYWxweuv0TmrL1jn01/yhYv1wUpek1Sbn6h6iWKguH5MbhwZeWSpHdU9dy+UOBoV4Sp+eSdvfY4C6DDKFKnoOOfevVGBK152Xqo/fQ5S/OV20cm8da/QpPZMRbeWnHXRmKrEatMuLLaAR/L5Q5namoBZDw6DQqLFO0kqs/d30dHHmTmri48ufiAgAZx/0DPEG7dIbgrwdXy5MNeaPnN/+x1AVhXptyxqUt9N+6BwsAmMxybudshNKuDDMzXqmGbdcMVWUNpVzJkns/ZbxJp19ULXtNjI7dNg3bpULMp7wFuoxkQwS2F4U4DIw==', 'secret_key': 'ZMmF0t34CWRwSFWRdD3vKw9nSJf625z1QwLPRdpdEjw3GyvYI6Nb7LlgAVcKfuu6tHOk2QixyLBGA62murcgYZxY9QZg/BtJlR73a2bisAfU7tAyUitvw1doUBDdmGpA75gQVEYWano8ntIZqFAzsPFqalIvuAl+ESWHzb8cFgQ=', 'uid': '257bee57-686e-4c35-566a-6c8e55fc4219'}
data = {
"text": 'who are you',
"end_flag": True,
"streaming": False,
"model": "gpt-4.1-mini", #'#"gpt-4o",
}
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
# 'Authorization':'Bearer xai-yrl52zS3KE5k3KZzX7n1ZeXS76G0gUzpIRFk5Sqqm3iuUOXW7UHaRJyXJpmZuFOLtjlDl514n9199P90'
}
params = {"params":json.dumps(auth_params)}
async with aiohttp.ClientSession() as session:
async with session.post(url, params=params, json=data,headers=headers) as resp:
print(await resp.json())
async def call_image_api():
url ='http://127.0.0.1:7860/compare?params=123123'
params={"params":"adsf"}
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
print(resp.status)
text = await resp.text()
print(text)
if __name__ == '__main__':
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if loop.is_closed():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(call_image_api())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Ailove
------------------------------------
@File : utils.py
@CreateTime : 2025/5/22 20:37
------------------------------------
"""
import os, hashlib, glob, re, base64, cv2
import numpy as np
from PIL import Image
from io import BytesIO
import requests
import onnxruntime
from ImageSimilarity.config import MEDIA_ROOT
# 缓存 GPU 可用性
_CACHED_CUDA_AVAILABLE = None
def is_cuda_available():
global _CACHED_CUDA_AVAILABLE
if _CACHED_CUDA_AVAILABLE is None:
try:
import GPUtil
_CACHED_CUDA_AVAILABLE = len(GPUtil.getGPUs()) > 0
except:
_CACHED_CUDA_AVAILABLE = False
return _CACHED_CUDA_AVAILABLE
def read_file(file_path):
with open(file_path, "rb") as f:
return f.read()
def is_md5(string):
return re.match(r"^[0-9a-f]{32}$", string)
def id2address(image_id, type="s"):
if not is_md5(image_id):
image_id = hashlib.md5(str(image_id).encode("utf-8")).hexdigest()
addrs = [str(int(image_id[i:i + 7], 16) % 1024) for i in range(0, 17, 8)]
base = "image_storage" if type == "s" else "store"
return os.path.join(MEDIA_ROOT, base, *addrs)
def readimg(body, keys):
inputs = {}
for key in keys:
try:
if key.startswith("url"):
image_string = requests.get(body[key]).content
elif key.startswith("img"):
image_string = base64.b64decode(body[key])
elif key.startswith("id"):
path = id2address(body[key])
files = glob.glob(os.path.join(path, '*'))
file = next((f for f in files if os.path.isfile(f)), None)
if not file:
continue
image_string = read_file(file)
else:
continue
inputs[key] = np.array(Image.open(BytesIO(image_string)).convert("RGB"))
except:
inputs[key] = None
return inputs
# 其他函数(如 get_embedding、detect_features、is_bottom_third_blank、get_cos_similar)可保持不变
def is_bottom_third_blank(image_data: np.ndarray) -> bool:
original = cv2.cvtColor(image_data, cv2.COLOR_RGB2BGR)
height, width, _ = original.shape
if height > 510:
original = cv2.resize(original, (350, 510))
height, width, _ = original.shape
bottom_third_start = height * 2 // 3
bottom_third = original[bottom_third_start:, :]
hist = cv2.calcHist([bottom_third], [0], None, [256], [0, 256])[5:150]
if np.sum(hist) > 0:
middle_section = original[200:400, :]
middle_hist = cv2.calcHist([middle_section], [0], None, [256], [0, 256])[5:150]
return np.sum(middle_hist) == 0
else:
return True
def detect_features(original_image: np.ndarray) -> int:
model_path = MEDIA_ROOT#os.path.join(MEDIA_ROOT, "model")
feature_image_path = os.path.join(model_path, "xx.png")
feature = cv2.imread(feature_image_path)
if original_image.shape[0] > 600:
original = original_image
target_size = (15, 15)
else:
original = cv2.resize(original_image, (350, 510))
target_size = (9, 9)
resized_feature = cv2.resize(feature, target_size)
result = cv2.matchTemplate(original, resized_feature, cv2.TM_CCOEFF_NORMED)
_, binary = cv2.threshold(result, 0.8, 1, cv2.THRESH_BINARY)
locations = np.where(binary == 1)
return len(locations[0])
def get_embedding(img: np.ndarray) -> np.ndarray:
cuda = is_cuda_available()
model_path = os.path.join(MEDIA_ROOT, "image-similarity.onnx")
session = onnxruntime.InferenceSession(
model_path,
providers=["CUDAExecutionProvider"] if cuda else ["CPUExecutionProvider"]
)
img = img / 255.0
img = cv2.resize(img, (448, 448))
img = img.transpose(2, 0, 1).astype(np.float32)[np.newaxis, :]
embedding = session.run(['output'], {'input': img})[0][0]
return embedding
def get_cos_similar(v1: np.ndarray, v2: np.ndarray) -> float:
num = float(np.dot(v1, v2))
denom = np.linalg.norm(v1) * np.linalg.norm(v2)
return 0.5 + 0.5 * (num / denom)app.py+26-181
config.pyAdded+12
models.pyAdded+25
requirements.txt+9-5
routes.pyAdded+61
services.pyAdded+35
test.pyAdded+56
utils.pyAdded+127