小伙伴們,大家好今天我們來利用ollama本地大模型,三步實現電子發票發票號碼的提取。? ? ? ? ??
步驟1:安裝Ollama
????訪問官網https://ollama.com/?下載相應的版本進行安裝,下載屬于自己平臺的ollama,根據安裝向導完成安裝。
步驟2:安裝Llama 3.2-Vision模型
通過在終端運行以下命令
安裝Llama 3.2-Vision模型
ollama run llama3.2-vision
步驟3:利用python調用ollma llama3.2-vision 大模型獲取對應電子發票的發票號碼
? ? ? ? ??
1)添加提示詞:?? ?
2)調用llama3.2-vision 大模型
3)最終結果:查看了下,獲取的信息還是比較準確的。? ? ? ? ??
? ? ? ? ? ??
全部代碼展示:????
import?base64 ? ? ? ? ?
import?requests ? ? ? ? ?
import?json ? ? ? ? ?
import?streamingjson ? ? ? ? ?
SYSTEM_PROMPT =?"""作為OCR助手。分析提供的圖像并:? ? ? ? ?
1. 盡可能準確地識別圖像中所有可識別的文本。? ? ? ? ?
2.?盡可能保持文本的原始結構和格式。? ? ? ??
3. 請主要識別發票號碼后面的數字,并重點標識出來 ? ? ? ? ?
僅提供轉錄,不要有任何額外的評論。""" ? ? ? ? ?
def?encode_image_to_base64(image_path): ? ? ? ? ?
with?open(image_path,?"rb")?as?image_file: ? ? ? ? ?
return?base64.b64encode(image_file.read()).decode('utf-8') ? ? ? ? ?
def?perform_ocr(image_path): ? ? ? ? ?
base64_image = encode_image_to_base64(image_path) ? ? ? ? ?
response = requests.post( ? ? ? ? ?
"http://10.10.10.56:11434/api/chat",??# 確保此URL與你的Ollama服務端點匹配 ? ? ? ? ?
json={ ? ? ? ? ?
"model":?"llama3.2-vision", ? ? ? ? ?
"messages": [ ? ? ? ? ?
{ ? ? ? ? ?
"role":?"user", ? ? ? ? ?
"content": SYSTEM_PROMPT, ? ? ? ? ?
"images": [base64_image], ? ? ? ? ?
}, ? ? ? ? ?
], ? ? ? ? ?
} ? ? ? ? ?
) ? ? ? ? ?
if?response.status_code ==?200: ? ? ? ? ?
data_string = response.text ? ? ? ? ?
json_segment_a = data_string??? ? ??
lexer = streamingjson.Lexer() ? ? ? ? ?
lexer.append_string(json_segment_a) ? ? ? ? ?
completed_json = lexer.complete_json() ? ? ? ? ?
return?completed_json ? ? ? ? ?
else: ? ? ? ? ?
print("錯誤:",?response.status_code,?response.text) ? ? ? ? ?
return None ? ? ? ? ?
if?__name__ ==?"__main__": ? ? ? ? ?
image_path =?"發票.png"??# 替換為你的圖像路徑 ? ? ? ? ?
result = perform_ocr(image_path) ? ? ? ? ?? ??
with?open('result.txt',?'w')?as?file: ? ? ? ? ?
file.write(result) ? ? ? ? ?
ls=[] ? ? ? ? ?
with?open('result.txt',?'r')?as?file: ? ? ? ? ?
while True: ? ? ? ? ?
content = file.readline() ? ? ? ? ?
if not?content: ? ? ? ? ?
break ? ? ? ? ?
content_json=json.loads(content) ? ? ? ? ?
ls.append(content_json.get("message",?{}).get("content",?"")) ? ? ? ? ?
my_string =?' '.join(ls) ? ? ? ? ?
print(my_string)?? ?
感謝大家的支持,希望得到大家的關注與點贊,我們下期見。? ??