checklang/app/checklang.py
2025-06-22 21:02:55 +08:00

49 lines
1009 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from ahserver.webapp import webapp
from ahserver.serverenv import ServerEnv
from appPublic.registerfunction import RegisterFunction
import fasttext
def docs(request):
return """Check langage for text
path: /v1/checklang
method: POST
headers:
Content-Text: application/json
data:
{
"text": "what is language of this sentence? "
}
response:
{
"lang": "en"
}
"""
def checklang(request, params_kw, *args, **kw):
engine = kw.get('engine')
text = params_kw.text
pred = engine.predict(text)
d = pred[0][0][9:]
return {
'lang':d
}
def init():
p = os.path.join(os.path.dirname(__file__), 'lid.176.ftz')
print(f'model path={p}')
model = fasttext.load_model(p)
# 需先下载模型https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.ftz
env = ServerEnv()
env.engine = model
rf = RegisterFunction()
rf.register('checklang', checklang)
if __name__ == '__main__':
rf = RegisterFunction()
rf.register('checklang', checklang)
rf.register('docs', docs)
webapp(init)