settings.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. from wsgiref import headers
  2. from dotenv import load_dotenv, find_dotenv
  3. from pathlib import Path # Python 3.6+ only
  4. import configparser, json, pytz
  5. import requests,os
  6. import pillow_avif
  7. from utils.common import message_queue
  8. import hashlib
  9. from pathlib import Path
  10. import os,stat
  11. TIME_ZONE = pytz.timezone("Asia/Shanghai")
  12. from numpy import true_divide
  13. from databases import (
  14. create_all_database,
  15. DeviceConfig,
  16. SysConfigs,
  17. CRUD,
  18. batch_insert_sys_configs,
  19. SqlQuery,
  20. batch_insert_device_configs,
  21. batch_insert_device_configsNew,
  22. )
  23. USER_TOKEN = None # 可以通过外部设置或从配置文件中加载
  24. USER_ENV = None # 可以通过外部设置或从配置文件中加载
  25. # 追加配置参数 machine_type 拍照机设备类型;0鞋;1服装
  26. MACHINE_TYPE = 0
  27. # 初始化数据表
  28. create_all_database()
  29. session = SqlQuery()
  30. device_config_crud = CRUD(DeviceConfig)
  31. all_devices = device_config_crud.read_all(session)
  32. if len(all_devices) == 0:
  33. # 如果配置表中一条数据都没有,就将初始化数据全部插入到数据表中
  34. action_tabs = json.load(open("action_tabs.json", encoding="utf-8"))
  35. actions = json.load(open("action.json", encoding="utf-8"))
  36. batch_insert_device_configs(session, action_tabs, actions)
  37. sys_config_crud = CRUD(SysConfigs)
  38. all_sys_configs = sys_config_crud.read_all(session)
  39. if len(all_sys_configs) == 0:
  40. # 如果配置表中一条数据都没有,就将初始化数据全部插入到数据表中
  41. sys_config_json = json.load(open("sys_configs.json", encoding="utf-8"))
  42. batch_insert_sys_configs(session, sys_config_json)
  43. else:
  44. # 查询数据库中缺失哪个数据,进行补充
  45. sys_config_json = json.load(open("sys_configs.json", encoding="utf-8"))
  46. for sys_config in sys_config_json:
  47. photos = CRUD(SysConfigs)
  48. item = photos.read(session, conditions={"key": sys_config.get("key")})
  49. if item == None:
  50. config = SysConfigs(**sys_config)
  51. session.add(config)
  52. session.commit() # 合并事务提交
  53. session.close()
  54. # 初始化数据表---结束
  55. def get_config_by_items(config_dict):
  56. __config_dict = {}
  57. for i, k in config_dict:
  58. __config_dict[i] = k
  59. return __config_dict
  60. keys = ["面料", "里料"]
  61. def sync_sys_configs2Online():
  62. hlm_token = USER_TOKEN
  63. headers = {
  64. "Authorization": f"Bearer {hlm_token}",
  65. "content-type": "application/json",
  66. }
  67. # 追加配置参数 machine_type 拍照机设备类型;0鞋;1服装
  68. session = SqlQuery()
  69. sysConfigs = CRUD(SysConfigs)
  70. all_configs = sysConfigs.read_all(session)
  71. localConfigData = {}
  72. for local_config in all_configs:
  73. localConfigData[local_config.key] = json.loads(local_config.value)
  74. data_json = json.dumps(
  75. {"configs": localConfigData, "machine_type": MACHINE_TYPE},
  76. ensure_ascii=False,
  77. )
  78. # 同步本地到线上
  79. url = DOMAIN + "/api/ai_image/camera_machine/update_all_user_configs"
  80. requests.post(url=url, headers=headers, data=data_json)
  81. session.close()
  82. def getSysConfigs(key, item, default=None):
  83. session = SqlQuery()
  84. crud = CRUD(SysConfigs)
  85. one_item = crud.read(session, conditions={"key": key})
  86. config = json.loads(one_item.value)
  87. session.close()
  88. if item == "image_out_format":
  89. default_format = config.get(item, default)
  90. if default_format == "" or default_format == None:
  91. return "png"
  92. return config.get(item, default)
  93. def updateSysConfigs(params):
  94. session = SqlQuery()
  95. sysConfig = CRUD(SysConfigs)
  96. # 如果value是字典或列表,需要转换为JSON字符串
  97. if "value" in params and isinstance(params["value"], (dict, list)):
  98. params["value"] = json.dumps(params["value"], ensure_ascii=False)
  99. # 走编辑逻辑
  100. # kws = params.__dict__
  101. sysConfig.updateConditions(session, conditions={"key": params["key"]}, **params)
  102. session.close()
  103. def get_dict_value(_dict, key, default=None):
  104. if key in _dict:
  105. return _dict[key]
  106. else:
  107. return default
  108. # 鞋设备为1 服装设备为5
  109. MCU_CODE = 1
  110. MACHINE_LEVEL = (
  111. "二档"
  112. if getSysConfigs("other_configs", "device_speed", "二档") == ""
  113. else getSysConfigs("other_configs", "device_speed", "二档")
  114. )
  115. IS_TEST = False
  116. IS_MCU = True
  117. IS_LIN_SHI_TEST = False
  118. PhotographSeconds = float(
  119. 0.5
  120. if getSysConfigs("take_photo_configs", "camera_delay", "0.5") == ""
  121. else getSysConfigs("take_photo_configs", "camera_delay", "0.5")
  122. ) # 拍照停留时间
  123. MAX_PIXIAN_SIZE = 12000000
  124. def moveSpeed(level: str = None):
  125. config = {
  126. "一档": {
  127. "camera_high_motor": {
  128. "max_speed": 10000,
  129. "up_speed": 800,
  130. "down_speed": 700,
  131. },
  132. "turntable_steering": {
  133. "max_speed": 6000,
  134. "up_speed": 500,
  135. "down_speed": 400,
  136. },
  137. },
  138. "二档": {
  139. "camera_high_motor": {
  140. "max_speed": 7000,
  141. "up_speed": 600,
  142. "down_speed": 500,
  143. },
  144. "turntable_steering": {
  145. "max_speed": 4500,
  146. "up_speed": 350,
  147. "down_speed": 300,
  148. },
  149. },
  150. "三档": {
  151. "camera_high_motor": {
  152. "max_speed": 3500,
  153. "up_speed": 400,
  154. "down_speed": 300,
  155. },
  156. "turntable_steering": {
  157. "max_speed": 3000,
  158. "up_speed": 200,
  159. "down_speed": 200,
  160. },
  161. },
  162. }
  163. if level is None:
  164. return config[MACHINE_LEVEL]
  165. else:
  166. return config[level]
  167. config = configparser.ConfigParser()
  168. config_name = "config.ini"
  169. config.read(config_name, encoding="utf-8")
  170. # 应用名称
  171. APP_NAME = config.get("app", "app_name")
  172. # 应用版本号
  173. APP_VERSION = config.get("app", "version")
  174. # 是否开启调试模式
  175. IS_DEBUG = config.get("app", "debug")
  176. IS_UPLOAD_HLM = True if config.get("app", "is_upload") == "true" else False
  177. # 应用端口号
  178. PORT = config.get("app", "port")
  179. # 应用线程数
  180. APP_WORKS = config.get("app", "works")
  181. # 应用host地址
  182. APP_HOST = config.get("app", "host")
  183. # 应用服务启动名称
  184. APP_RUN = config.get("app", "app_run")
  185. # 日志名称
  186. LOG_FILE_NAME = config.get("log", "log_file_name")
  187. # 最大字节数
  188. MAX_BYTES = config.get("log", "max_bytes")
  189. print("Max bytes is", MAX_BYTES)
  190. # 备份数量
  191. BACKUP_COUNTS = config.get("log", "backup_counts")
  192. # 远程服务器地址
  193. HLM_HOST = config.get("log", "hlm_host")
  194. PROJECT = config.get("app", "project")
  195. # ----------------------------------
  196. mcu_config_dict = config.items("mcu_config")
  197. _mcu_config_dict = {}
  198. for i, k in mcu_config_dict:
  199. _mcu_config_dict[i] = int(k)
  200. # print(_mcu_config_dict)
  201. _config_mcu_config = get_config_by_items(config.items("mcu_config"))
  202. LEFT_FOOT_ACTION = _mcu_config_dict["left_foot_action"]
  203. LEFT_FOOT_PHOTOGRAPH = _mcu_config_dict["left_foot_photograph"]
  204. LEFT_FOOT_ACTION_1 = _mcu_config_dict["left_foot_action_1"]
  205. LEFT_FOOT_ACTION_2 = _mcu_config_dict["left_foot_action_2"]
  206. RIGHT_FOOT_ACTION = _mcu_config_dict["right_foot_action"]
  207. RIGHT_FOOT_PHOTOGRAPH = _mcu_config_dict["right_foot_photograph"]
  208. RIGHT_FOOT_ACTION_1 = _mcu_config_dict["right_foot_action_1"]
  209. RIGHT_FOOT_ACTION_2 = _mcu_config_dict["right_foot_action_2"]
  210. NEXT_STEP = int(get_dict_value(_config_mcu_config, "next_step", 6)) # 下一步
  211. MOVE_UP = _mcu_config_dict["move_up"]
  212. MOVE_DOWN = _mcu_config_dict["move_down"]
  213. STOP = _mcu_config_dict["stop"]
  214. # camera_config_dict = config.items("camera_config")
  215. # _camera_config_dict = {}
  216. # for i, k in mcu_config_dict:
  217. # _camera_config_dict[i] = int(k)
  218. # _camera_config_dict = get_config_by_items(camera_config_dict)
  219. # LOW_ISO = _camera_config_dict["low_iso"]
  220. # HIGH_ISO = _camera_config_dict["high_iso"]
  221. DOMAIN = (
  222. "https://dev2.valimart.net"
  223. if config.get("app", "env") != "dev"
  224. else "https://dev2.pubdata.cn"
  225. )
  226. def getDoman(env):
  227. return "https://dev2.valimart.net" if env != "dev" else "https://dev2.pubdata.cn"
  228. Company = "惠利玛"
  229. is_test_plugins = true_divide
  230. OUT_PIC_MODE = "." + getSysConfigs("basic_configs", "image_out_format", "png") # ".png"
  231. OUT_PIC_SIZE = (
  232. [1600]
  233. if getSysConfigs("basic_configs", "main_image_size", [1600]) == ""
  234. else getSysConfigs("basic_configs", "main_image_size", [1600])
  235. ) # 主图大小
  236. Mode = getSysConfigs("other_configs", "product_type", "鞋类") # 程序执行类
  237. OUT_PIC_FACTOR = float(
  238. 1
  239. if getSysConfigs("basic_configs", "image_sharpening", "1") == ""
  240. else getSysConfigs("basic_configs", "image_sharpening", "1")
  241. ) # 图片锐化
  242. RESIZE_IMAGE_MODE = 1
  243. GRENERATE_MAIN_PIC_BRIGHTNESS = 254 # 色阶是否调整到位判断
  244. RUNNING_MODE = getSysConfigs("other_configs", "running_mode", "普通模式")
  245. DEFAULT_CUTOUT_MODE = getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  246. CUTOUT_MODE = (
  247. 0 if getSysConfigs("other_configs", "cutout_mode", "普通抠图") == "普通抠图" else 1
  248. )
  249. import importlib
  250. OUT_PIC_QUALITY = "普通"
  251. GRENERATE_MAIN_PIC_BRIGHTNESS = int(
  252. getSysConfigs("other_configs", "grenerate_main_pic_brightness", 254)
  253. ) # 色阶是否调整到位判断
  254. SHADOW_PROCESSING = int(
  255. getSysConfigs("other_configs", "shadow_processing", 0)
  256. ) # 0表示要直线和曲线,1 表示只要直线
  257. LOWER_Y = int(
  258. getSysConfigs("other_configs", "lower_y", 4)
  259. ) # 鞋底以下多少距离作为阴影蒙版
  260. CHECK_LOWER_Y = int(
  261. getSysConfigs("other_configs", "check_lower_y", 4)
  262. ) # 检测亮度区域,倒数第几行
  263. IS_GET_GREEN_MASK = (
  264. True if getSysConfigs("other_configs", "is_get_green_mask", "否") == "是" else False
  265. ) # 是否进行绿幕抠图
  266. IMAGE_SAVE_MAX_WORKERS = int(
  267. getSysConfigs("other_configs", "image_save_max_workers", 20)
  268. ) # 批量保存的线程大小
  269. COLOR_GRADATION_CYCLES = int(
  270. getSysConfigs("other_configs", "color_gradation_cycles", 23)
  271. ) # 色阶处理循环次数
  272. # grenerate_main_pic_brightness 亮度范围 默认值254 范围 200 -255 步长 1
  273. # opacity 透明度 默认值 0.5 范围 0.5-1 步长 0.1
  274. # IMAGE_MASK_CONFIG = int(
  275. # getSysConfigs("basic_configs", "image_mask_config", {"mode":0,"opacity":0.5,"grenerate_main_pic_brightness":254})
  276. # ) # 色阶处理循环次数
  277. def recordDataPoint(token=None, page="", uuid=None, data=""):
  278. """记录日志"""
  279. if token == None:
  280. return
  281. if page == "":
  282. return
  283. if uuid == None:
  284. return
  285. headers = {"Content-Type": "application/json", "authorization": "Bearer " + token}
  286. params = {
  287. "site": 1,
  288. "type": 5,
  289. "channel": "aigc-camera",
  290. "uuid": uuid,
  291. "page": page,
  292. "page_url": "/",
  293. "describe": {"action": page, "data": data},
  294. "time": 0,
  295. }
  296. return requests.post(
  297. headers=headers, data=json.dumps(params), url=DOMAIN + "/api/record/point"
  298. )
  299. def syncPhotoRecord(data,action_type=0):
  300. """同步图片记录"""
  301. headers = {
  302. "Authorization": f"Bearer {USER_TOKEN}",
  303. "content-type": "application/json",
  304. }
  305. machine_type = MACHINE_TYPE
  306. url = getDoman(USER_ENV) + f"/api/ai_image/camera_machine/photo_records_handler"
  307. postData = {"data":data,"machine_type":machine_type,'action_type':action_type}
  308. response = requests.post(url=url,data=json.dumps(postData, ensure_ascii=False, default=str), headers=headers)
  309. print("用户token",response.content)
  310. def syncBatchPhotoRecordDelete():
  311. """同步图片记录"""
  312. headers = {
  313. "Authorization": f"Bearer {USER_TOKEN}",
  314. "content-type": "application/json",
  315. }
  316. machine_type = MACHINE_TYPE
  317. url = getDoman(USER_ENV) + f"/api/ai_image/camera_machine/photo_records_handler"
  318. postData = {"machine_type": machine_type, "action_type": 4}
  319. response = requests.post(
  320. url=url,
  321. data=json.dumps(postData, ensure_ascii=False, default=str),
  322. headers=headers,
  323. )
  324. print("用户token", response.content)
  325. def checkRecordSyncStatus():
  326. # check_photo_record_sync_status
  327. headers = {
  328. "Authorization": f"Bearer {USER_TOKEN}",
  329. "content-type": "application/json",
  330. }
  331. machine_type = MACHINE_TYPE
  332. url = getDoman(USER_ENV) + f"/api/ai_image/camera_machine/photo_records_handler?machine_type={machine_type}"
  333. try:
  334. response = requests.get(url=url, headers=headers).json()
  335. return response.get("data").get('status',True)
  336. except Exception as e:
  337. return True
  338. async def sendSocketMessage(
  339. code=0, msg="", data=None, device_status=2, msg_type=""
  340. ):
  341. data = {
  342. "code": code,
  343. "msg": msg,
  344. "status": device_status,
  345. "data": data,
  346. "msg_type": msg_type,
  347. }
  348. await message_queue.put(data)
  349. def calculate_md5(filepath):
  350. # 打开文件,以二进制只读模式打开
  351. with open(filepath, "rb") as f:
  352. # 创建MD5哈希对象
  353. md5hash = hashlib.md5()
  354. # 循环读取文件的内容并更新哈希对象
  355. for chunk in iter(lambda: f.read(4096), b""):
  356. md5hash.update(chunk)
  357. # 返回MD5哈希的十六进制表示
  358. return md5hash.hexdigest()
  359. __output_dir = config.get("output_config", "output_dir")
  360. path_obj = Path(os.path.abspath(__output_dir))
  361. OUTPUT_DIR = path_obj.absolute()
  362. print("OUTPUT_DIR",__output_dir,OUTPUT_DIR)
  363. def handle_remove_readonly(func, path, exc):
  364. os.chmod(path, stat.S_IWRITE)
  365. func(path)
  366. try:
  367. __scan_dir = config.get("scan_config", "scan_dir")
  368. if __scan_dir == "" or __scan_dir is None:
  369. SCAN_DIR = None
  370. else:
  371. scan_path_obj = Path(os.path.abspath(__scan_dir))
  372. SCAN_DIR = scan_path_obj.absolute()
  373. if not os.path.exists(SCAN_DIR):
  374. # 创建多级目录
  375. os.makedirs(SCAN_DIR, exist_ok=True)
  376. except:
  377. SCAN_DIR = None
  378. print('扫码配置不存在')
  379. print("SCAN_DIR",SCAN_DIR)
  380. CUSTOMER_TEMPLATE_URL = config.get("customer_template", "template_url")
  381. def hex_to_rgb(hex_color):
  382. """
  383. 将十六进制颜色值转换为RGB颜色值
  384. :param hex_color: 十六进制颜色值,例如 "#FF0000" 或 "FF0000"
  385. :return: RGB元组,例如 (255, 0, 0)
  386. """
  387. # 移除可能存在的 # 符号
  388. hex_color = hex_color.lstrip('#')
  389. # 确保是有效的十六进制字符串
  390. if len(hex_color) != 6:
  391. raise ValueError("十六进制颜色值格式不正确,应为6位十六进制数")
  392. # 将十六进制字符串转换为RGB值
  393. try:
  394. r = int(hex_color[0:2], 16)
  395. g = int(hex_color[2:4], 16)
  396. b = int(hex_color[4:6], 16)
  397. return (r, g, b)
  398. except ValueError:
  399. return (255, 255, 255)
  400. def rgb_to_hex(r, g, b):
  401. """
  402. 将RGB颜色值转换为十六进制颜色值
  403. :param r: 红色分量 (0-255)
  404. :param g: 绿色分量 (0-255)
  405. :param b: 蓝色分量 (0-255)
  406. :return: 十六进制颜色值,例如 "#FF0000"
  407. """
  408. # 验证RGB值在有效范围内
  409. if not all(0 <= val <= 255 for val in [r, g, b]):
  410. return "#FFFFFF"
  411. return "#{:02X}{:02X}{:02X}".format(r, g, b)