207 lines
11 KiB
Python
207 lines
11 KiB
Python
import io
|
||
import ipaddress
|
||
import socket
|
||
import threading
|
||
import time
|
||
from urllib.parse import urlsplit, urljoin
|
||
from pathlib import Path
|
||
|
||
import httpx
|
||
import torch
|
||
from torch import nn
|
||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||
from fastapi import FastAPI, HTTPException
|
||
from pydantic import BaseModel, Field, field_validator
|
||
import json
|
||
from ui_grounding import UNREGISTERED_PAGE, frame_is_readable, locate, read_annotations, bbox_valid, ANNOT
|
||
from ui_classifier import build, features, transform
|
||
|
||
torch.set_num_threads(4)
|
||
Image.MAX_IMAGE_PIXELS = 25_000_000
|
||
ROOT = Path(__file__).resolve().parent
|
||
c = torch.load(ROOT/'artifacts/mobilenet_ui.pt', map_location='cpu', weights_only=True)
|
||
model = build().eval(); model.load_state_dict(c['backbone'])
|
||
head = nn.Linear(576, len(c['labels'])); head.load_state_dict(c['head']); head.eval()
|
||
preprocess = transform()
|
||
slots = threading.BoundedSemaphore(2)
|
||
infer_lock = threading.Lock()
|
||
app = FastAPI(title='车机界面识别与功能定位', version='0.2.0')
|
||
|
||
class Request(BaseModel):
|
||
image_url: str = Field(min_length=8, max_length=4096)
|
||
|
||
def validate_url(url):
|
||
p = urlsplit(url)
|
||
if p.scheme not in ('http','https') or not p.hostname or p.username or p.password:
|
||
raise HTTPException(400,'仅支持不含账号密码的 HTTP/HTTPS 图片地址')
|
||
try:
|
||
addresses = socket.getaddrinfo(p.hostname, p.port or (443 if p.scheme=='https' else 80),type=socket.SOCK_STREAM)
|
||
except (OSError,ValueError):
|
||
raise HTTPException(400,'图片地址解析失败')
|
||
for item in addresses:
|
||
addr=ipaddress.ip_address(item[4][0])
|
||
if addr.is_loopback or addr.is_link_local or addr.is_unspecified or addr.is_multicast or addr.is_reserved:
|
||
raise HTTPException(400,'该图片地址不允许访问')
|
||
|
||
def download(url):
|
||
deadline=time.monotonic()+25
|
||
with httpx.Client(timeout=httpx.Timeout(10,connect=5),follow_redirects=False,trust_env=False) as client:
|
||
for _ in range(4):
|
||
validate_url(url)
|
||
with client.stream('GET',url) as response:
|
||
if response.status_code in (301,302,303,307,308):
|
||
location=response.headers.get('location')
|
||
if not location: raise HTTPException(422,'图片地址重定向无目标')
|
||
url=urljoin(url,location); continue
|
||
if response.status_code != 200:
|
||
raise HTTPException(422,f'图片服务器返回 HTTP {response.status_code}')
|
||
out=bytearray()
|
||
for chunk in response.iter_bytes(65536):
|
||
if time.monotonic()>deadline: raise HTTPException(504,'图片下载超时')
|
||
out.extend(chunk)
|
||
if len(out)>20*1024*1024: raise HTTPException(413,'图片超过20MB')
|
||
return bytes(out)
|
||
raise HTTPException(422,'图片重定向次数过多')
|
||
|
||
@app.get('/health')
|
||
def health():
|
||
return {'status':'ok','model':'MobileNetV3-Small','classes':len(c['labels']),'device':'cpu'}
|
||
|
||
@app.get('/v1/pages')
|
||
def pages():
|
||
return {'pages':c['labels']}
|
||
|
||
def classify_page(scores):
|
||
best = int(scores.argmax())
|
||
# The closed-set classifier has no unknown class. Abstain when the best result is weak.
|
||
return c['labels'][best] if float(scores[best]) >= 0.60 else UNREGISTERED_PAGE
|
||
|
||
|
||
@app.post('/v1/classify')
|
||
def classify(body:Request):
|
||
if not slots.acquire(blocking=False): raise HTTPException(429,'服务繁忙,请稍后重试')
|
||
start=time.monotonic()
|
||
try:
|
||
raw=download(body.image_url)
|
||
try:
|
||
with Image.open(io.BytesIO(raw)) as im:
|
||
if im.width*im.height>25_000_000: raise HTTPException(413,'图片超过2500万像素')
|
||
im=ImageOps.exif_transpose(im).convert('RGB')
|
||
width,height=im.size
|
||
readable=frame_is_readable(im)
|
||
x=preprocess(im)[None]
|
||
except (UnidentifiedImageError,OSError,ValueError):
|
||
raise HTTPException(422,'下载内容不是可解码的图片')
|
||
except Image.DecompressionBombError:
|
||
raise HTTPException(413,'图片像素过大')
|
||
with infer_lock,torch.inference_mode():
|
||
z=features(model,x)
|
||
scores=head((z-c['mean'])/c['std']).softmax(-1)[0]
|
||
indices=scores.argsort(descending=True)[:3]
|
||
return {'page':classify_page(scores) if readable else UNREGISTERED_PAGE,'top3':[{'name':c['labels'][int(k)],'softmax_score':round(float(scores[k]),6)} for k in indices],'image_size':{'width':width,'height':height},'elapsed_ms':round((time.monotonic()-start)*1000),'needs_review':True,'model_version':'mobilenet-ui-20261130','note':'试验版;尚未进行独立实拍验证,softmax_score未经校准。'}
|
||
except httpx.TimeoutException:
|
||
raise HTTPException(504,'图片下载超时')
|
||
except httpx.HTTPError:
|
||
raise HTTPException(422,'无法下载图片')
|
||
finally:
|
||
slots.release()
|
||
|
||
class LocateRequest(Request):
|
||
target: str = Field(min_length=1,max_length=300)
|
||
page: str | None = None
|
||
allow_unverified_coordinates: bool = False
|
||
|
||
@app.post('/v1/locate')
|
||
def locate_endpoint(body:LocateRequest):
|
||
if body.page is not None and body.page != UNREGISTERED_PAGE and body.page not in c['labels']: raise HTTPException(400,'未知界面名称')
|
||
if not slots.acquire(blocking=False): raise HTTPException(429,'服务繁忙,请稍后重试')
|
||
start=time.monotonic()
|
||
try:
|
||
raw=download(body.image_url)
|
||
try:
|
||
with Image.open(io.BytesIO(raw)) as source:
|
||
if source.width*source.height>25_000_000: raise HTTPException(413,'图片超过2500万像素')
|
||
im=ImageOps.exif_transpose(source).convert('RGB')
|
||
except (UnidentifiedImageError,OSError,ValueError):raise HTTPException(422,'下载内容不是可解码的图片')
|
||
except Image.DecompressionBombError:raise HTTPException(413,'图片像素过大')
|
||
if not frame_is_readable(im):
|
||
return {'page': UNREGISTERED_PAGE, 'status':'not_found','point':None,'reason':'截图缺少清晰的界面内容。',
|
||
'image_size':{'width':im.width,'height':im.height},'needs_review':True,
|
||
'coordinate_system':'original_photo_pixels_after_exif_orientation'}
|
||
with infer_lock,torch.inference_mode():
|
||
z=features(model,preprocess(im)[None]); scores=head((z-c['mean'])/c['std']).softmax(-1)[0]
|
||
page=body.page or classify_page(scores)
|
||
result=locate(im,page,body.target)
|
||
if result.get('found') and result.get('method')=='qwen_zero_shot' and not body.allow_unverified_coordinates:
|
||
result['candidate_point']=result.pop('point')
|
||
result['point']=None
|
||
result['status']='needs_coordinate_review'
|
||
result['reason']='模型仅返回候选区域,未通过已复核参考图定位。'
|
||
else:result['status']='located' if result.get('found') else 'not_found'
|
||
if result.get('annotation_reviewed'):
|
||
note='参考标注已复核;'+('当前照片的定位、语义或交互状态仍需确认。' if result.get('needs_review') else '本张参考原图的功能与坐标已核对。')+'未执行实际点击。'
|
||
else:note='当前目标没有匹配到已复核标注,模型坐标仅为候选。'
|
||
return {'page':page,'page_source':'provided' if body.page else 'classifier','image_size':{'width':im.width,'height':im.height},'coordinate_system':'original_photo_pixels_after_exif_orientation','elapsed_ms':round((time.monotonic()-start)*1000),**result,'note':note}
|
||
except httpx.TimeoutException:raise HTTPException(504,'下载或模型推理超时')
|
||
except httpx.HTTPError:raise HTTPException(502,'下载或模型服务不可用')
|
||
except (ValueError,KeyError,IndexError,TypeError):raise HTTPException(502,'模型输出格式不符合坐标协议')
|
||
finally:slots.release()
|
||
|
||
class Control(BaseModel):
|
||
id: int | None = Field(default=None,ge=1)
|
||
control_id: str | None = None
|
||
name: str = Field(min_length=1,max_length=200)
|
||
aliases: list[str] = Field(default_factory=list,max_length=30)
|
||
bbox: list[float] = Field(min_length=4,max_length=4)
|
||
reviewed: bool = True
|
||
position_reviewed: bool = True
|
||
function_reviewed: bool = True
|
||
interaction_state: str = 'not_tested'
|
||
function_id: str | None = None
|
||
reference_box_1200x900: list[float] | None = Field(default=None,min_length=4,max_length=4)
|
||
@field_validator('bbox')
|
||
@classmethod
|
||
def check_box(cls,v):
|
||
if not bbox_valid(v): raise ValueError('bbox须为0~1000的[x1,y1,x2,y2],且有正面积')
|
||
return v
|
||
|
||
class Annotation(BaseModel):
|
||
reviewed: bool = False
|
||
controls: list[Control] = Field(max_length=100)
|
||
|
||
@app.get('/v1/annotations/{page}')
|
||
def get_annotation(page:str):
|
||
if page not in c['labels']:raise HTTPException(404,'未知界面')
|
||
return read_annotations(page)
|
||
|
||
annotation_lock=threading.Lock()
|
||
@app.put('/v1/annotations/{page}')
|
||
def save_annotation(page:str,body:Annotation):
|
||
if page not in c['labels']:raise HTTPException(404,'未知界面')
|
||
entries=[]
|
||
for index,x in enumerate(body.controls,1):
|
||
entry=x.model_dump(exclude_none=True);entry['id']=x.id or index;entry['control_id']=page+'/'+str(entry['id']);entry['reviewed']=body.reviewed and x.reviewed;entries.append(entry)
|
||
if len({x['id'] for x in entries})!=len(entries):raise HTTPException(400,'控件id不能重复')
|
||
doc={'page':page,'image':'data/'+page+'.jpg','source':'operator_review','review_version':'operator-updated','reviewed':body.reviewed,'controls':entries}
|
||
ANNOT.mkdir(exist_ok=True)
|
||
with annotation_lock:
|
||
p=ANNOT/(page+'.json'); temp=p.with_suffix('.tmp'); temp.write_text(json.dumps(doc,ensure_ascii=False,indent=2),encoding='utf-8'); temp.replace(p)
|
||
return {'saved':True,'page':page,'reviewed':body.reviewed,'controls':len(body.controls)}
|
||
|
||
@app.post('/v1/dataset/export')
|
||
def export_dataset():
|
||
samples=[]; pages=[]
|
||
with annotation_lock:
|
||
for page in c['labels']:
|
||
doc=read_annotations(page)
|
||
if not doc.get('reviewed'):continue
|
||
pages.append(page)
|
||
for x in doc['controls']:
|
||
if not x.get('function_reviewed',True) or x.get('interaction_state') in ('dimmed_unverified','low_visibility_unverified','unknown'):continue
|
||
for name in [x['name']]+x.get('aliases',[]):
|
||
response=json.dumps({'found':True,'target':x['name'],'bbox':x['bbox']},ensure_ascii=False)
|
||
samples.append({'messages':[{'role':'user','content':'<image>定位要点击的功能:'+name+'。只输出JSON,bbox坐标归一化到0~1000;找不到返回found=false。'},{'role':'assistant','content':response}],'images':['/workspace/data/'+page+'.jpg']})
|
||
if not samples:raise HTTPException(409,'尚无已复核标注;模型自动草稿不能直接作为真值训练')
|
||
dest=ANNOT/'train.reviewed.jsonl'; dest.write_text('\n'.join(json.dumps(x,ensure_ascii=False) for x in samples)+'\n',encoding='utf-8')
|
||
return {'samples':len(samples),'source_pages':pages,'path':str(dest),'independent_validation_available':False,'training_started':False,'note':'同源问答不能作为独立验证集;此操作仅导出已复核数据。'}
|