此篇是向日盛證券股票拍立得致敬,不過我們這次採用的是透過Telegram來作為介面,啟動相機拍攝圖片,並且解析出上市櫃公司,並且找出對應的股票代號,可以方便股民們快速對應股票代號,不用一一尋找與輸入.
注意事項:
- 本篇不會提及如何製作Telegram Bot,預設讀者已經有過類似經驗,所以僅就架構說明.
- 此OCR可以用在不同場景之下.
- 讀者預先知識Python、Django、Telegram API、pyTelegramBotAPI
1.預先安裝對應套件(僅就重要套件進行說明,其餘是需求自行安裝)
pip install pyTelegramBotAPI #安裝TelegramAPI套件
2.建立專案架構
django-admin startproject {ProjectName}
3.建立APP
python manage.py startapp {AppName}
3.建立暫存資料夾(在專案下建立一個Tmp資料夾)
4.處理專案下路由
from django.urls import path, include
urlpatterns = [
path('webhook/', include('wehook.urls')),
]
5.撰寫主要程式碼,在{AppName}下的View.py撰寫
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import os, json
import telebot #主要引入pyTelegramBotAPI
from telebot import types #主要引入pyTelegramBotAPI
#API Token
TOKEN = {您申請到的Bot Token}
bot = telebot.TeleBot(TOKEN)
#處理CallBack
@csrf_exempt
def callback(request):
print('in webhook....')
if request.method == 'POST':
json_string = json.dumps(json.loads(request.body))
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return HttpResponse('webhook is ok')
else:
print('error')
return HttpResponse('error')
#重點程式區
@bot.message_handler(content_types=['photo'])
def get_photo(message):
print('進入圖片')
fileID = message.photo[-1].file_id #取得圖ID
file = bot.get_file(fileID) #取得圖片
downloaded_file = bot.download_file(file.file_path) #取得圖
savename = str(fileID) + '_file.jpg'
save_url = './Tmp/' + savename
# 存檔
with open(save_url, 'wb') as new_file:
new_file.write(downloaded_file)
#呼叫OCR與取得關鍵資訊
OCR_URL = {OCR SERVER URL}
stock_text = ocr(save_url, OCR_URL)
bot.reply_to(message, stock_text)
6.將App路由加入({AppName}下的url.py)
from django.urls import path
from . import views
urlpatterns = [
path('callback', views.callback)
]
7.成果展示