first commit
This commit is contained in:
0
models/__init__.py
Normal file
0
models/__init__.py
Normal file
BIN
models/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
models/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
models/__pycache__/connect_db.cpython-313.pyc
Normal file
BIN
models/__pycache__/connect_db.cpython-313.pyc
Normal file
Binary file not shown.
BIN
models/__pycache__/emoji_db.cpython-313.pyc
Normal file
BIN
models/__pycache__/emoji_db.cpython-313.pyc
Normal file
Binary file not shown.
BIN
models/__pycache__/generator.cpython-313.pyc
Normal file
BIN
models/__pycache__/generator.cpython-313.pyc
Normal file
Binary file not shown.
BIN
models/__pycache__/logger.cpython-313.pyc
Normal file
BIN
models/__pycache__/logger.cpython-313.pyc
Normal file
Binary file not shown.
88
models/connect_db.py
Normal file
88
models/connect_db.py
Normal file
@@ -0,0 +1,88 @@
|
||||
import toml
|
||||
import pymysql
|
||||
from pymysql.cursors import DictCursor
|
||||
from pymysql.connections import Connection
|
||||
from models.logger import setup_logger
|
||||
|
||||
logger = setup_logger()
|
||||
|
||||
def connect_db() -> Connection | None:
|
||||
"""连接数据库,如果没有则初始化数据库和表"""
|
||||
try:
|
||||
config = toml.load("../config.toml")
|
||||
db_host = config["db_host"]
|
||||
db_port = config["db_port"]
|
||||
db_user = config["db_user"]
|
||||
db_password = config["db_password"]
|
||||
db_database = config["db_database"]
|
||||
except Exception as e:
|
||||
logger.error(f"读取数据库配置错误{e}")
|
||||
return None
|
||||
|
||||
connection = pymysql.connect(
|
||||
host=db_host,
|
||||
port=int(db_port),
|
||||
user=db_user,
|
||||
password=db_password,
|
||||
database=db_database,
|
||||
charset='utf8mb4',
|
||||
cursorclass=DictCursor
|
||||
)
|
||||
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# 创建 emoji 表
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS emoji (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
uuid VARCHAR(255) NOT NULL,
|
||||
description VARCHAR(255),
|
||||
url VARCHAR(255) NOT NULL,
|
||||
hash VARCHAR(255) NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# 创建 approved 表
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS approved
|
||||
(
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
uuid VARCHAR(255) NOT NULL,
|
||||
approved BOOL,
|
||||
approver VARCHAR(255)
|
||||
)
|
||||
''')
|
||||
|
||||
# 创建 token 表
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS token
|
||||
(
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
token VARCHAR(255) NOT NULL ,
|
||||
userid INT NOT NULL ,
|
||||
expires TIMESTAMP NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# 创建 user 表
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS user
|
||||
(
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL,
|
||||
passwd VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255),
|
||||
lastlogin TIMESTAMP,
|
||||
submission_count INT DEFAULT 0
|
||||
)
|
||||
''')
|
||||
|
||||
return connection
|
||||
except Exception as e:
|
||||
logger.error(f"数据库连接或表创建失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
conn = connect_db()
|
||||
conn.cursor()
|
||||
73
models/emoji_db.py
Normal file
73
models/emoji_db.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from models.connect_db import connect_db
|
||||
from models.logger import setup_logger
|
||||
|
||||
logger = setup_logger()
|
||||
connection = connect_db()
|
||||
|
||||
def update_description(emoji_uuid: str, description: str) -> bool:
|
||||
"""
|
||||
更新表情包描述词
|
||||
|
||||
Args:
|
||||
emoji_uuid: 表情包UUID
|
||||
description: 新的描述词
|
||||
|
||||
Returns:
|
||||
成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
sql = """
|
||||
UPDATE emoji
|
||||
SET description = %s
|
||||
WHERE uuid = %s
|
||||
"""
|
||||
|
||||
params = (description, emoji_uuid)
|
||||
|
||||
with connection.cursor() as cursor:
|
||||
affected_rows = cursor.execute(sql, params)
|
||||
|
||||
if affected_rows > 0:
|
||||
logger.info(f"成功更新表情包描述,UUID: {emoji_uuid}")
|
||||
return True
|
||||
else:
|
||||
logger.warning(f"未找到要更新的表情包,UUID: {emoji_uuid}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"更新表情包描述失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_emoji(uuid: str) -> bool:
|
||||
"""
|
||||
检查UUID是否存在于emoji表中
|
||||
|
||||
Args:
|
||||
uuid: 要检查的UUID字符串
|
||||
|
||||
Returns:
|
||||
uuid 在数据库中存在则为 True,否则 False
|
||||
"""
|
||||
# 参数验证
|
||||
if not uuid or not isinstance(uuid, str):
|
||||
logger.warning(f"无效的UUID参数: {uuid}")
|
||||
return False
|
||||
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# 执行查询
|
||||
sql = "SELECT 1 FROM emoji WHERE uuid = %s LIMIT 1"
|
||||
cursor.execute(sql, (uuid,))
|
||||
|
||||
# 如果查询到结果则返回True
|
||||
result = cursor.fetchone()
|
||||
return result is not None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"检查UUID失败: {uuid}, 错误: {e}")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
record = check_emoji("ffe1663c-44e1-4719-a5ba-01485f70a87e")
|
||||
print(record)
|
||||
44
models/generator.py
Normal file
44
models/generator.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import os
|
||||
from typing import Optional
|
||||
from dashscope import MultiModalConversation
|
||||
from models.logger import setup_logger
|
||||
|
||||
logger = setup_logger()
|
||||
|
||||
class Generator:
|
||||
def __init__(self, api_key: str, model: str = 'qwen3-vl-plus'):
|
||||
self.api_key = api_key
|
||||
self.model = model
|
||||
|
||||
def process_single_image(self, image_path: str) -> Optional[str]:
|
||||
"""处理单张图片,生成描述词"""
|
||||
try:
|
||||
image_url = f"file://{image_path}"
|
||||
messages = [
|
||||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{'image': image_url},
|
||||
{'text': '使用简洁语言描述该表情包 ,例如 在吗 ,生气,?'}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
response = MultiModalConversation.call(
|
||||
model=self.model,
|
||||
messages=messages
|
||||
)
|
||||
|
||||
if response and hasattr(response, 'output'):
|
||||
if hasattr(response.output.choices[0].message.content[0], 'text'):
|
||||
return response.output.choices[0].message.content[0]["text"]
|
||||
elif isinstance(response.output.choices[0].message.content[0], dict):
|
||||
return response.output.choices[0].message.content[0].get("text", "")
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"API调用失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
61
models/logger.py
Normal file
61
models/logger.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
def setup_logger(log_file=None, log_level=logging.INFO, max_bytes=10485760, backup_count=5):
|
||||
"""
|
||||
初始化日志记录器,将日志按指定格式输出并记录到文件
|
||||
|
||||
Args:
|
||||
log_file (str): 日志文件路径,默认为None,会自动生成以当天日期命名的日志文件
|
||||
log_level: 日志级别
|
||||
max_bytes (int): 单个日志文件最大字节数
|
||||
backup_count (int): 保留的备份日志文件数量
|
||||
|
||||
Returns:
|
||||
logging.Logger: 配置好的日志记录器
|
||||
"""
|
||||
# 创建logger
|
||||
logger = logging.getLogger('emoji-text-generator')
|
||||
logger.setLevel(log_level)
|
||||
logger.propagate = False
|
||||
|
||||
# 避免重复添加handler
|
||||
if logger.handlers:
|
||||
return logger
|
||||
|
||||
# 创建logs目录(如果不存在)
|
||||
log_dir = Path('logs')
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
|
||||
# 如果未指定日志文件名,则使用当天日期命名
|
||||
if log_file is None:
|
||||
today = datetime.now().strftime('%Y-%m-%d')
|
||||
log_file = log_dir / f'{today}.log'
|
||||
|
||||
# 创建格式化器
|
||||
formatter = logging.Formatter(
|
||||
'[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)d] - %(message)s'
|
||||
)
|
||||
|
||||
# 创建文件处理器(带轮转)
|
||||
file_handler = RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
file_handler.setLevel(log_level)
|
||||
file_handler.setFormatter(formatter)
|
||||
|
||||
# 创建控制台处理器
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(log_level)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# 添加处理器到logger
|
||||
logger.addHandler(file_handler)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
return logger
|
||||
2
models/logs/2025-12-07.log
Normal file
2
models/logs/2025-12-07.log
Normal file
@@ -0,0 +1,2 @@
|
||||
[2025-12-07 13:44:14,574] [ERROR] [connect_db.py:19] - 读取数据库配置错误[Errno 2] No such file or directory: 'config.toml'
|
||||
[2025-12-07 13:44:14,574] [ERROR] [emoji_db.py:68] - 检查表情包是否存在失败: 'NoneType' object has no attribute 'cursor'
|
||||
Reference in New Issue
Block a user