forked from xszyou/Fay
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1、集成灵聚NLP api(支持GPT3.5及多应用); 2、ui修正。
- Loading branch information
Showing
10 changed files
with
390 additions
and
234 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import json | ||
import requests | ||
import uuid | ||
from datetime import datetime, timedelta | ||
import time | ||
from utils import util | ||
from utils import config_util as cfg | ||
from core.authorize_tb import Authorize_Tb | ||
|
||
def question(cont): | ||
lingju = Lingju() | ||
answer = lingju.question(cont) | ||
return answer | ||
|
||
class Lingju: | ||
|
||
def __init__(self): | ||
self.userid = str(uuid.getnode()) | ||
self.authorize_tb = Authorize_Tb() | ||
|
||
def question(self, cont): | ||
token = self.__check_token() | ||
if token is None or token == 'expired': | ||
token_info = self.__get_token() | ||
if token_info is not None: | ||
#转换过期时间 | ||
updated_in_seconds = time.time() | ||
updated_datetime = datetime.fromtimestamp(updated_in_seconds) | ||
expires_timedelta = timedelta(days=token_info['data']['expires']) | ||
expiry_datetime = updated_datetime + expires_timedelta | ||
expiry_timestamp_in_seconds = expiry_datetime.timestamp() | ||
expiry_timestamp_in_milliseconds = int(expiry_timestamp_in_seconds) * 1000 | ||
token = token_info['data']['accessToken'] | ||
if token == 'expired': | ||
self.authorize_tb.update_by_userid(self.userid, token_info['data']['accessToken'], expiry_timestamp_in_milliseconds) | ||
else: | ||
self.authorize_tb.add(self.userid, token_info['data']['accessToken'], expiry_timestamp_in_milliseconds) | ||
else: | ||
token = None | ||
|
||
if token is not None: | ||
try: | ||
lat,lng,city = self.__get_location() | ||
url="https://dev.lingju.ai/httpapi/ljchat.do" | ||
req = json.dumps({"accessToken": token, "lat": lat, "lng": lng, "input": cont}) | ||
headers = {'Content-Type':'application/json;charset=UTF-8'} | ||
r = requests.post(url, headers=headers, data=req) | ||
if r.status_code != 200: | ||
util.log(1, f"灵聚api对接有误: {r.text}") | ||
return "哎呀,出错了!请重新发一下" | ||
info = json.loads(r.text) | ||
if info['status'] != 0: | ||
return info['description'] | ||
else: | ||
answer = json.loads(info['answer']) | ||
return answer['rtext'] | ||
except Exception as e: | ||
util.log(1, f"灵聚api对接有误: {str(e)}") | ||
return "哎呀,出错了!请重新发一下" | ||
|
||
def __check_token(self): | ||
self.authorize_tb.init_tb() | ||
info = self.authorize_tb.find_by_userid(self.userid) | ||
if info is not None: | ||
if info[1] >= int(time.time())*1000: | ||
return info[0] | ||
else: | ||
return 'expired' | ||
else: | ||
return None | ||
|
||
def __get_token(self): | ||
try: | ||
cfg.load_config() | ||
url=f"https://dev.lingju.ai/httpapi/authorize.do?appkey={cfg.key_lingju_api_key}&userid={self.userid}&authcode={cfg.key_lingju_api_authcode}" | ||
headers = {'Content-Type':'application/json;charset=UTF-8'} | ||
r = requests.post(url, headers=headers) | ||
if r.status_code != 200: | ||
util.log(1, f"灵聚api对接有误: {r.text}") | ||
return None | ||
info = json.loads(r.text) | ||
if info['status'] != 0: | ||
util.log(1, f"灵聚api对接有误:{info['description']}") | ||
return None | ||
else: | ||
return info | ||
except Exception as e: | ||
util.log(1, f"灵聚api对接有误: {str(e)}") | ||
return None | ||
|
||
def __get_location(self): | ||
try: | ||
response = requests.get('http://ip-api.com/json/') | ||
data = response.json() | ||
return data['lat'], data['lon'], data['city'] | ||
except requests.exceptions.RequestException as e: | ||
util.log(1, f"获取位置失败: {str(e)}") | ||
return 0, 0, "北京" | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import sqlite3 | ||
import time | ||
import threading | ||
import functools | ||
def synchronized(func): | ||
@functools.wraps(func) | ||
def wrapper(self, *args, **kwargs): | ||
with self.lock: | ||
return func(self, *args, **kwargs) | ||
return wrapper | ||
class Authorize_Tb: | ||
|
||
def __init__(self) -> None: | ||
self.lock = threading.Lock() | ||
|
||
|
||
|
||
#初始化 | ||
def init_tb(self): | ||
conn = sqlite3.connect('fay.db') | ||
c = conn.cursor() | ||
try: | ||
c.execute('SELECT * FROM T_Authorize') | ||
except sqlite3.OperationalError: | ||
c.execute(''' | ||
CREATE TABLE T_Authorize | ||
(id INTEGER PRIMARY KEY autoincrement, | ||
userid char(100), | ||
accesstoken TEXT, | ||
expirestime BigInt, | ||
createtime Int); | ||
''') | ||
conn.commit() | ||
finally: | ||
conn.close() | ||
|
||
#添加 | ||
@synchronized | ||
def add(self,userid,accesstoken,expirestime): | ||
conn = sqlite3.connect("fay.db") | ||
cur = conn.cursor() | ||
cur.execute("insert into T_Authorize (userid,accesstoken,expirestime,createtime) values (?,?,?,?)",(userid,accesstoken,expirestime,int(time.time()))) | ||
|
||
conn.commit() | ||
conn.close() | ||
return cur.lastrowid | ||
|
||
#查询 | ||
@synchronized | ||
def find_by_userid(self,userid): | ||
conn = sqlite3.connect("fay.db") | ||
cur = conn.cursor() | ||
cur.execute("select accesstoken,expirestime from T_Authorize where userid = ? order by id desc limit 1",(userid,)) | ||
info = cur.fetchone() | ||
conn.close() | ||
return info | ||
|
||
# 更新token | ||
@synchronized | ||
def update_by_userid(self, userid, new_accesstoken, new_expirestime): | ||
conn = sqlite3.connect("fay.db") | ||
cur = conn.cursor() | ||
cur.execute("UPDATE T_Authorize SET accesstoken = ?, expirestime = ? WHERE userid = ?", | ||
(new_accesstoken, new_expirestime, userid)) | ||
conn.commit() | ||
conn.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.