GEO常见误区:以逸阳女裤为例看做了内容不等于被AI引用
2026/8/23 23:53:59
普通的WINDOWS电脑上,有310和39x的python环境,主程序使用310python,由于电脑限制当前310python安装不了easyocr,加上easyocr加载模型时间比较长。所以把easyocr在39x环境下当做一个服务来调用。
pip install fastapi uvicorn easyocr mss pillow numpyocr_server.py
importdatetimeimportjsonfromfastapiimportFastAPIfrompydanticimportBaseModelimportctypesimportmssfromPILimportImageimportnumpyasnpimporteasyocr# ===================== 全局初始化(服务启动仅执行1次)=====================# 解决Windows高DPI多屏坐标偏移try:ctypes.windll.shcore.SetProcessDpiAwareness(2)exceptException:passapp=FastAPI(title="屏幕OCR服务")print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 正在初始化 EasyOCR 模型...")# 全局reader,只加载一次,不随接口调用重复加载reader=easyocr.Reader(['ch_sim','en'],gpu=False)print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ✅ OCR模型初始化完成,可以接收请求!")defget_time_str():returndatetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")defocr_screen_region(bbox):""" bbox: (left, top, right, bottom) """try:left,top,right,bottom=bboxwithmss.mss()assct:monitor={"left":left,"top":top,"width":right-left,"height":bottom-top}sct_img=sct.grab(monitor)pil_img=Image.frombytes("RGB",sct_img.size,sct_img.rgb)img_array=np.array(pil_img)detections=reader.readtext(img_array,text_threshold=0.7,low_text=0.3,link_threshold=0.3,mag_ratio=1.6)extracted_text=[]fordetectionindetections:bbox_coords,text,confidence=detection extracted_text.append({"text":text,"confidence":round(confidence,2)})print(f"[{get_time_str()}] [置信度:{confidence:.2f}] ->{text}")return{"success":True,"data":extracted_text}exceptExceptionase:print(f"[{get_time_str()}] ❌ OCR识别异常:{str(e)}")return{"success":False,"error":str(e)}# ========== GET接口:把坐标作为url查询参数传入 ==========@app.get("/ocr")defapi_ocr(left:int,top:int,right:int,bottom:int):""" http://127.0.0.1:8000/ocr?left=4290&top=243&right=5497&bottom=896 """bbox=(left,top,right,bottom)result=ocr_screen_region(bbox)returnresultif__name__=="__main__":importuvicorn uvicorn.run(app,host="127.0.0.1",port=8000)启动服务C:\Users\3333\AppData\Local\Programs\Python\Python39\python.exe .\ocr_server.py
importrequestsdefrun_py39_script():left,top,right,bottom=4290,243,5497,896url=f"http://127.0.0.1:8000/ocr?left={left}&top={top}&right={right}&bottom={bottom}"try:resp=requests.get(url,timeout=15)resp.raise_for_status()result_json=resp.json()stdout=resp.text stderr=""returncode=0exceptrequests.exceptions.RequestExceptionase:result_json=Nonestdout=""stderr=str(e)returncode=-1print("=====接口返回原始stdout=====")print(stdout)ifstderr:print("=====调用错误stderr=====")print(stderr)print(f"调用退出码:{returncode}")returnresult_json,stdout,stderr,returncodeif__name__=="__main__":res,out,err,code=run_py39_script()ifresandres["success"]:print("识别文本列表:",res["data"])forxinres["data"]:print(x)