11import json
22import os
33import datetime
4- import random
4+ # import random
55from typing import List
66from ..dao .dao import tags_db_path
77import sqlite3
8+ import secrets
89
910current_dir = os .path .dirname (os .path .abspath (__file__ ))
1011init_file_path = os .path .join (current_dir , '../../../random_tag' )
12+
13+
1114def save_template (data ):
1215 """
1316 保存模板到random_tag文件夹
14-
17+
1518 参数:
1619 name: 文件名前缀(可选)
1720 data: 要保存的字典数据
@@ -20,23 +23,23 @@ def save_template(data):
2023 # 检查random_tag文件夹是否存在,不存在则创建
2124 if not os .path .exists (init_file_path ):
2225 os .makedirs (init_file_path )
23-
26+
2427 # 生成时间戳文件名
2528 timestamp = datetime .datetime .now ().strftime ("%Y%m%d_%H%M%S" )
2629 file_name = timestamp
2730 file_path = os .path .join (init_file_path , f"{ file_name } .json" )
28-
31+
2932 # 检查文件是否已存在
3033 if os .path .exists (file_path ):
3134 print ("文件已存在" )
3235 raise Exception ("文件已存在" )
33-
36+
3437 # 写入JSON文件
3538 with open (file_path , 'w' , encoding = 'utf-8' ) as f :
3639 json .dump (data , f , ensure_ascii = False , indent = 4 )
37-
40+
3841 return {"code" : 200 , "path_name" : str (file_name )}
39-
42+
4043 except Exception as e :
4144 print (str (e ))
4245 raise Exception (str (e ))
@@ -45,50 +48,49 @@ def save_template(data):
4548def update_template (name : str , data ):
4649 """
4750 更新random_tag文件夹中的模板文件
48-
51+
4952 参数:
5053 name: 文件名(不带.json后缀)
5154 data: 要更新的字典数据
5255 """
5356 try :
5457 # 构建完整文件路径
5558 file_path = os .path .join (init_file_path , f"{ name } .json" )
56-
59+
5760 # 检查文件是否存在
5861 if not os .path .exists (file_path ):
5962 raise Exception ("文件不存在" )
60-
63+
6164 # 写入JSON文件(覆盖更新)
6265 with open (file_path , 'w' , encoding = 'utf-8' ) as f :
6366 json .dump (data , f , ensure_ascii = False , indent = 4 )
64-
67+
6568 return {"code" : 200 , "path_name" : str (name )}
66-
69+
6770 except Exception as e :
6871 raise Exception (str (e ))
6972
7073
71-
7274def delete_template (name : str ):
7375 """
7476 删除random_tag文件夹中的模板文件
75-
77+
7678 参数:
7779 name: 文件名(不带.json后缀)
7880 """
7981 try :
8082 # 构建完整文件路径
8183 file_path = os .path .join (init_file_path , f"{ name } .json" )
82-
84+
8385 # 检查文件是否存在
8486 if not os .path .exists (file_path ):
8587 raise Exception ("文件不存在" )
86-
88+
8789 # 删除文件
8890 os .remove (file_path )
89-
91+
9092 return {"code" : 200 , "message" : "文件删除成功" , "path_name" : str (name )}
91-
93+
9294 except Exception as e :
9395 raise Exception (str (e ))
9496
@@ -102,7 +104,7 @@ def get_template_list():
102104 # 检查random_tag文件夹是否存在
103105 if not os .path .exists (init_file_path ):
104106 return {"code" : 200 , "data" : []}
105-
107+
106108 # 获取所有JSON文件
107109 file_list = []
108110 for filename in os .listdir (init_file_path ):
@@ -115,21 +117,22 @@ def get_template_list():
115117 file_name = data .get ('file_name' , '' )
116118 except :
117119 file_name = ''
118-
120+
119121 file_list .append ({
120122 "file_name" : file_name ,
121123 "path_name" : filename .replace ('.json' , '' )
122124 })
123-
125+
124126 return {"code" : 200 , "data" : file_list }
125-
127+
126128 except Exception as e :
127129 raise Exception (str (e ))
128130
131+
129132def get_template_data (name : str ):
130133 """
131134 获取指定模板文件的JSON数据
132-
135+
133136 参数:
134137 name: 文件名(不带.json后缀)
135138 返回:
@@ -138,17 +141,17 @@ def get_template_data(name: str):
138141 try :
139142 # 构建完整文件路径
140143 file_path = os .path .join (init_file_path , f"{ name } .json" )
141-
144+
142145 # 检查文件是否存在
143146 if not os .path .exists (file_path ):
144147 raise Exception ("文件不存在" )
145-
148+
146149 # 读取JSON文件
147150 with open (file_path , 'r' , encoding = 'utf-8' ) as f :
148151 data = json .load (f )
149-
152+
150153 return {"code" : 200 , "data" : data , "path_name" : str (name )}
151-
154+
152155 except Exception as e :
153156 raise Exception (str (e ))
154157
@@ -165,65 +168,74 @@ def get_random_tags_by_group(p_uuid: str) -> List[str]:
165168 results = cursor .fetchall ()
166169 return [row [0 ] for row in results ]
167170
171+
168172def get_random_tags_by_subgroup (g_uuid : str ) -> List [str ]:
169173 """根据subgroup的g_uuid获取随机标签"""
170174 conn = sqlite3 .connect (tags_db_path )
171- cursor = conn .cursor ()
175+ cursor = conn .cursor ()
172176 cursor .execute ('''
173177 SELECT text FROM tag_tags WHERE g_uuid = ?
174178 ''' , (g_uuid ,))
175179 results = cursor .fetchall ()
176180 return [row [0 ] for row in results ]
177181
182+
178183def shuffle_and_select (tags : List [str ], count : int ) -> List [str ]:
179184 """随机打乱并选择指定数量的标签"""
180- random .shuffle (tags )
181- return tags [:count ]
185+ # random.shuffle(tags)
186+ # return tags[:count]
187+ rng = secrets .SystemRandom () # 加密级真随机数生成器
188+ shuffled = tags .copy ()
189+ rng .shuffle (shuffled )
190+ return shuffled [:count ]
191+
182192
183193def generate_random_tags (data : dict ) -> str :
184194 """生成随机标签字符串"""
185195 result = []
186-
196+
187197 for rule in data ['rules' ]:
188198 min_count = rule ['range' ]['min' ]
189199 max_count = rule ['range' ]['max' ]
190200 count = max_count - min_count + 1
191-
201+
192202 if rule ['type' ] == 'category' :
193203 tags = []
194204 for group in rule ['tagGroupList' ]:
195205 if group ['sub' ]:
196- tags .extend (get_random_tags_by_subgroup (group ['sub' ]['g_uuid' ]))
206+ tags .extend (get_random_tags_by_subgroup (
207+ group ['sub' ]['g_uuid' ]))
197208 else :
198- tags .extend (get_random_tags_by_group (group ['group' ]['p_uuid' ]))
209+ tags .extend (get_random_tags_by_group (
210+ group ['group' ]['p_uuid' ]))
199211 selected_tags = shuffle_and_select (tags , count )
200212 result .extend (selected_tags )
201-
213+
202214 elif rule ['type' ] == 'specific' :
203215 tags = rule ['specificTags' ]
204216 selected_tags = shuffle_and_select (tags , min (count , len (tags )))
205217 result .extend (selected_tags )
206-
218+
207219 return ',' .join (result ) + ','
208220
209221
210222def go_radom_template (name : str ):
211223 try :
212224 # 构建完整文件路径
213225 file_path = os .path .join (init_file_path , f"{ name } .json" )
214-
226+
215227 # 检查文件是否存在
216228 if not os .path .exists (file_path ):
217229 raise Exception ("文件不存在" )
218-
230+
219231 # 读取JSON文件
220232 with open (file_path , 'r' , encoding = 'utf-8' ) as f :
221233 data = json .load (f )
222-
234+
223235 # 生成随机标签
224236 random_tags = generate_random_tags (data )
225-
237+
226238 return {"code" : 200 , "random_tags" : random_tags , "path_name" : str (name )}
227-
239+
228240 except Exception as e :
229- raise Exception (str (e ))
241+ raise Exception (str (e ))
0 commit comments