public void saves(String deviceId,String productId,List<IotDataCurrent> datas) throws Exception{ List<String> codes=new ArrayList<>(); for(IotDataCurrent data:datas)codes.add(data.getDataCode().trim().toLowerCase()); List<IotAlarmPropertyVo> alarmPropertys=iotAlarmPropertyService.getByCodes(productId,ToolUtils.getData().listToStrs(codes)); IotDataPropertyQueryDto queryDto=new IotDataPropertyQueryDto(); queryDto.setProductId(productId); List<IotDataPropertyVo> dataPropertyVos =iotDataPropertyService.queryList(queryDto,null,1,-1).getList(); IotDataCurrent parm=new IotDataCurrent(); parm.setDeviceId(deviceId); boolean contain = false; for(IotDataCurrent data:datas){ if ("C06".equals(data.getDataCode())) { double value = Double.parseDouble(data.getDataVal().trim()); if (value < 0) { return; } } } for(IotDataCurrent data:datas){ if ("C00".equals(data.getDataCode())) { contain = true; } data.setModifyTime(new Date()); IotDataRecord iotDataRecord=new IotDataRecord(); for(IotAlarmPropertyVo alarmProperty:alarmPropertys){ if(data.getDataCode().equals(alarmProperty.getDataCode())){ if(StringUtils.isNoneBlank(alarmProperty.getTriggerVal())){ try { boolean alarmbl=false; String bit = alarmProperty.getWei(); switch (alarmProperty.getTriggerType()) { case "<": if(new BigDecimal(data.getDataVal()).compareTo(new BigDecimal(alarmProperty.getTriggerVal()))<0){ alarmbl=true; } break; case "<=": if(new BigDecimal(data.getDataVal()).compareTo(new BigDecimal(alarmProperty.getTriggerVal()))<=0){ alarmbl=true; } break; case ">": if(new BigDecimal(data.getDataVal()).compareTo(new BigDecimal(alarmProperty.getTriggerVal()))>0){ alarmbl=true; } break; case ">=": if(new BigDecimal(data.getDataVal()).compareTo(new BigDecimal(alarmProperty.get

时间: 2025-06-16 08:49:31 浏览: 19
<think>好的,用户的问题是关于如何优化一段包含IoT数据处理和报警触发逻辑的Java代码。我需要结合他们提供的引用内容来给出建议。首先,我需要分析用户提供的引用内容,看看哪些部分可以用来优化代码。 引用[1]提到优化上报流程、增强上报机制、使用异步处理、消息队列、减少锁竞争、非阻塞IO等技术。这可能涉及到处理同一告警类型频繁触发的问题,需要优化告警触发机制,比如增加沉默周期或者去重。 引用[2]中的QuotaDTO新增了告警相关的属性,比如沉默周期(cycle)。这说明在代码中可能需要实现告警的沉默机制,避免同一告警重复触发。例如,设置一个时间窗口,在周期内不重复触发相同的告警。 引用[3]讨论了OPC UA的断连重连和数据监听的实现,提到了不同的订阅方式。这可能涉及到优化数据订阅和处理逻辑,比如使用更高效的订阅方式,或者异步处理数据,避免阻塞主线程。 引用[4]中的Pulse框架处理异常数据,使用表达式判断异常,并将异常数据存入Kafka。这可能意味着可以引入规则引擎来处理告警逻辑,使用更灵活的表达式配置,同时利用消息队列来缓冲和处理数据,避免堵塞。 现在,我需要将这些点整合到优化建议中。首先,处理频繁告警的问题,可以引入沉默周期和告警合并。其次,优化数据处理流程,使用异步和非阻塞IO,减少资源竞争。然后,使用消息队列来解耦数据处理和告警触发,提高系统吞吐量。最后,考虑引入规则引擎,使告警规则可配置,提升灵活性。 可能还需要考虑代码层面的优化,比如减少锁竞争,使用线程池管理资源,以及优化数据库或缓存访问。同时,监控和日志记录也很重要,帮助定位性能瓶颈。 需要确保建议的结构清晰,分点说明,每个优化点都结合引用内容,并自然添加引用标识。例如,提到沉默周期时引用[2],使用消息队列时引用[1]和[4]。 最后,生成的相关问题需要围绕IoT数据处理、告警优化、性能调优等方面,帮助用户进一步探索解决方案。</think>### 优化IoT数据处理与报警触发逻辑的Java代码方案 #### 一、代码功能优化 1. **告警沉默周期实现** 在`QuotaDTO`中定义的`cycle`字段可用于告警沉默周期控制[^2]。建议通过以下方式实现: ```java // 使用ConcurrentHashMap记录告警最后触发时间 private static final Map<String, Long> alarmSilenceMap = new ConcurrentHashMap<>(); public boolean checkAlarmSilence(String alarmKey) { Long lastTrigger = alarmSilenceMap.get(alarmKey); long currentTime = System.currentTimeMillis(); return lastTrigger != null && (currentTime - lastTrigger) < cycle * 1000L; } ``` 2. **告警规则引擎化** 参考Pulse框架的异常规则配置方式[^4],可将硬编码的告警条件改为可配置表达式: ```java // 示例规则配置 List<AlarmRule> rules = Arrays.asList( new AlarmRule("avg(temperature) > 40", "高温告警", "CRITICAL"), new AlarmRule("count(errorCode) > 5 within 60s", "频繁错误", "WARNING") ); ``` #### 二、性能优化策略 1. **异步处理架构** 采用生产者-消费者模式解耦数据处理与告警触发[^1]: ```java // 使用Disruptor高性能队列 Disruptor<DataEvent> disruptor = new Disruptor<>( DataEvent::new, bufferSize, DaemonThreadFactory.INSTANCE); disruptor.handleEventsWith(new DataProcessor(), new AlarmTrigger()); ``` 2. **非阻塞IO优化** 针对IoT设备通信层,使用Netty实现异步网络IO[^3]: ```java EventLoopGroup group = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new DeviceProtocolDecoder()); ch.pipeline().addLast(new DataHandler()); } }); ``` 3. **资源竞争优化** 对共享资源采用无锁数据结构: ```java // 使用LongAdder替代AtomicLong private final LongAdder messageCounter = new LongAdder(); public void processMessage(Message msg) { messageCounter.increment(); // 处理逻辑 } ``` #### 三、监控与调试 1. **关键指标埋点** ```java // 使用Micrometer指标收集 MeterRegistry registry = new PrometheusMeterRegistry(); registry.gauge("iot.alerts.active", alarmSilenceMap.size()); Timer processTimer = Timer.builder("data.process.time") .publishPercentiles(0.95, 0.99) .register(registry); ``` 2. **日志优化建议** - 对高频日志采用异步Appender - 使用JSON格式结构化日志 - 动态调整日志级别:`<AsyncLogger name="com.iot" level="${sys:LOG_LEVEL:-INFO}"/>` #### 四、架构级优化 1. **分布式处理** 当单节点处理能力不足时,可采用Kafka Streams进行分布式处理: ```java StreamsBuilder builder = new StreamsBuilder(); builder.stream("raw-data") .filter((k, v) -> v.getTemperature() > 40) .to("alarm-events"); ``` 2. **数据缓存优化** 对频繁访问的设备元数据使用Caffeine缓存: ```java LoadingCache<String, DeviceInfo> deviceCache = Caffeine.newBuilder() .maximumSize(10_000) .expireAfterWrite(5, TimeUnit.MINUTES) .build(this::loadDeviceInfoFromDB); ```
阅读全文

相关推荐

根据以下要求:Instead of using a binary file to save the arraylist of points, change the savaData method and the constructor of the Model class to use a database to write / read the coordinates of all the points. Use XAMPP and phpMyAdmin to create a database called "java" with a table called "points" that has two integer columns x and y (in addition to the ID primary key). Hint: make sure you delete all the old point coordinates from the database before inserting new ones. Hint: use phpMyAdmin to check what is stored in the database. Use the Test class to run all the tests for the software and check that all the tests still work. Use the Start class to run the software and check that closing the software correctly saves the point coordinates in the database (use phpMyAdmin to check the content of the database). Run the software again and check that all the points from the previous run are correctly displayed,修改下述代码:public class Model implements Serializable { private ArrayList points; private ArrayList<ModelListener> listeners; private static final String FILE_NAME = "points.bin"; public Model() { points = new ArrayList(); listeners = new ArrayList<ModelListener>(); // Read points from file if it exists File file = new File(FILE_NAME); if (file.exists()) { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); points = (ArrayList) in.readObject(); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } public void addListener(ModelListener l) { listeners.add(l); } public ArrayList getPoints() { return points; } public void addPoint(Point p) { points.add(p); notifyListeners(); // points changed so notify the listeners. saveData(); // save point to file } public void clearAllPoints() { points.clear(); notifyListeners(); // points changed so notify the listeners. saveData(); // save empty list to file } public void deleteLastPoint() { if (points.size() > 0) { points.remove(points.size() - 1); notifyListeners(); // points changed so notify the listeners. saveData(); // save updated list to file } } private void notifyListeners() { for (ModelListener l : listeners) { l.update(); // Tell the listener that something changed. } } public int numberOfPoints() { return points.size(); } public void saveData() { try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE_NAME)); out.writeObject(points); out.close(); } catch (IOException e) { e.printStackTrace(); } }

帮我根据以下要求:Add to the Model class a new method called savaData that saves into a text file called "points.txt" the integer coordinates x and y of each point in the arraylist of points. Also modify the constructor of the Model class to read the integer coordinates of all the points from the same text file, if it exists, and put them into the arraylist of points (if the file does not exist then the arraylist of points should remain empty).public class Model { private ArrayList points; private ArrayList<ModelListener> listeners; public Model() { points = new ArrayList(); listeners = new ArrayList<ModelListener>(); } public void addListener(ModelListener l) { listeners.add(l); } public ArrayList getPoints() { return points; } public void addPoint(Point p) { points.add(p); notifyListeners(); // points changed so notify the listeners. } public void clearAllPoints() { points.clear(); notifyListeners(); // points changed so notify the listeners. } public void deleteLastPoint() { if(points.size() > 0) { points.remove(points.size() - 1); notifyListeners(); // points changed so notify the listeners. } } private void notifyListeners() { for(ModelListener l: listeners) { l.update(); // Tell the listener that something changed. } } public int numberOfPoints() { return points.size(); } public static void testModel() { Model m = new Model(); m.addListener(new ModelListener() { @Override public void update() { System.out.println(true + " (listener)"); } }); System.out.println(m.getPoints() == m.points); Point p1 = new Point(1, 2); Point p2 = new Point(3, 4); m.addPoint(p1); // Listener called. m.addPoint(p2); // Listener called. System.out.println(m.numberOfPoints() == 2); System.out.println(m.points.get(0) == p1); System.out.println(m.points.get(1) == p2); m.deleteLastPoint(); // Listener called. System.out.println(m.numberOfPoints() == 1); System.out.println(m.points.get(0) == p1); m.clearAllPoints(); // Listener called. System.out.println(m.numberOfPoints() == 0); m.notifyListeners(); // Listener called. } }修改下述代码:

petalinux-config --get-hw-description=./project-spec/hw-description --silentconfig --force getopt: unrecognized option '--force' Configures the project or the specified component with menuconfig. Usage: petalinux-config [options] {--component <COMPONENT> |--get-hw-description[=SRC]} Options: -h, --help show function usage -p, --project path to PetaLinux SDK project. default is the working project --silentconfig takes the default configuration and skips the GUI. -c, --component <COMPONENT> Specify the component If no component is specified, it will do top level project configuration . If you specify a component,it will configure it with menuconfig and saves user's config fragments in meta-user. E.g. -c rootfs, -c busybox --get-hw-description [SRC] get hardware description. if [SRC] is specified, look in that location for an Vivado export to SDK directory. Otherwise, this MUST be run from WITHIN the vivado export to SDK directory. --defconfig [DEFCONFIG_TARGET] defconfig the specified component. It applies to kernel and u-boot. -v, --verbose verbose mode Note: There is no validation for configurable components. User can provide any component, bitbake will throw error for invalid components. Sync hardware description: Sync hardware description from Vivado export to PetaLinux BSP project: $ cd <Vivado_Export_to_SDK_Directory> $ petalinux-config --get-hw-description It will sync up the XSA file from <Vivado_Export_to_SDK_Directory> to project-spec/hw-description/ directory. Sync hardware description inside PetaLinux project but outside Vivado export to SDK directory: $ petalinux-config --get-hw-description=<Vivado_Export_to_SDK_Directory> If more than one XSA files in <Vivado_Export_to_SDK_Directory> specify the exact file path using $ petalinux-config --get-hw-description <Vivado_Export_to_SDK_Directory>/system.xsa Configure PetaLinux project: Configure subsystem level configuration: $ petalinux-config Configure kernel: $ petalinux-config -c kernel Configure rootfs: $ petalinux-config -c rootfs Defconfig kconfig kernel with xilinx_zynq_base_trd_defconfig: $ petalinux-config -c kernel --defconfig xilinx_zynq_base_trd_defconfig这个打印信息是正确的吗

/******************************************************************************* *BSD 3-Clause License * *Copyright (c) 2016-2023, Mech-Mind Robotics *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * *1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * *2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * *3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE *FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #pragma once #include <memory> #include <string> #include "common/StatusCode.h" namespace mmind::dl { /** * @brief Defines the Image. */ struct MMIND_DL_SDK_EXPORT MMindImage { /** * @brief Creates an image from its path. * @param [in] imagePath Image storage path. * @return See @ref StatusCode for details. */ StatusCode createFromPath(const std::string& imagePath); /** * @brief Visualizes an image. * @param [in] winName The window name for visualizing an image. * @return See @ref StatusCode for details. * @note The size of the image display window equals to that of the image. */ StatusCode show(const std::string& winName); /** * @brief Saves the image to a specified directory. * @param [in] savePath The path to save the image. * @return See @ref StatusCode for details. */ StatusCode save(const std::string& savePath); /** * @brief Releases the memory of the image. */ ~MMindImage(); int width = 0; ///< The width of the image. int height = 0; ///< The height of the image. int channel = 0; ///< The number of channels in the image. int depth = 0; ///< The depth of the image. std::shared_ptr<unsigned char> data = nullptr; ///< The pointer of the image data. }; } // namespace mmind::dl 这里面的析构函数还是虚函数,不需要绑定吗? ~MMindImage();

/home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources W0703 16:13:22.516433 3913223 torch/distributed/run.py:766] W0703 16:13:22.516433 3913223 torch/distributed/run.py:766] ***************************************** W0703 16:13:22.516433 3913223 torch/distributed/run.py:766] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. W0703 16:13:22.516433 3913223 torch/distributed/run.py:766] ***************************************** /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources [rank0]: Traceback (most recent call last): [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1863, in _get_module [rank0]: return importlib.import_module("." + module_name, self.__name__) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module [rank0]: return _bootstrap._gcd_import(name[level:], package, level) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import [rank0]: File "<frozen importlib._bootstrap>", line 1178, in _find_and_load [rank0]: File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked [rank0]: File "<frozen importlib._bootstrap>", line 690, in _load_unlocked [rank0]: File "<frozen importlib._bootstrap_external>", line 940, in exec_module [rank0]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama_fast.py", line 29, in <module> [rank0]: from .tokenization_llama import LlamaTokenizer [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama.py", line 27, in <module> [rank0]: import sentencepiece as spm [rank0]: File "/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py", line 10, in <module> [rank0]: from . import _sentencepiece [rank0]: ImportError: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank0]: The above exception was the direct cause of the following exception: [rank0]: Traceback (most recent call last): [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 82, in load_tokenizer [rank0]: tokenizer = AutoTokenizer.from_pretrained( [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 912, in from_pretrained [rank0]: tokenizer_class_from_name(config_tokenizer_class) is not None [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 611, in tokenizer_class_from_name [rank0]: return getattr(module, class_name) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1851, in __getattr__ [rank0]: module = self._get_module(self._class_to_module[name]) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1865, in _get_module [rank0]: raise RuntimeError( [rank0]: RuntimeError: Failed to import transformers.models.llama.tokenization_llama_fast because of the following error (look up to see its traceback): [rank0]: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank0]: The above exception was the direct cause of the following exception: [rank0]: Traceback (most recent call last): [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 23, in <module> [rank0]: launch() [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 19, in launch [rank0]: run_exp() [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 110, in run_exp [rank0]: _training_function(config={"args": args, "callbacks": callbacks}) [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 72, in _training_function [rank0]: run_sft(model_args, data_args, training_args, finetuning_args, generating_args, callbacks) [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/sft/workflow.py", line 48, in run_sft [rank0]: tokenizer_module = load_tokenizer(model_args) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 97, in load_tokenizer [rank0]: raise OSError("Failed to load tokenizer.") from e [rank0]: OSError: Failed to load tokenizer. [rank3]: Traceback (most recent call last): [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1863, in _get_module [rank3]: return importlib.import_module("." + module_name, self.__name__) [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module [rank3]: return _bootstrap._gcd_import(name[level:], package, level) [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import [rank3]: File "<frozen importlib._bootstrap>", line 1178, in _find_and_load [rank3]: File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked [rank3]: File "<frozen importlib._bootstrap>", line 690, in _load_unlocked [rank3]: File "<frozen importlib._bootstrap_external>", line 940, in exec_module [rank3]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama_fast.py", line 29, in <module> [rank3]: from .tokenization_llama import LlamaTokenizer [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama.py", line 27, in <module> [rank3]: import sentencepiece as spm [rank3]: File "/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py", line 10, in <module> [rank3]: from . import _sentencepiece [rank3]: ImportError: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank3]: The above exception was the direct cause of the following exception: [rank3]: Traceback (most recent call last): [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 82, in load_tokenizer [rank3]: tokenizer = AutoTokenizer.from_pretrained( [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 912, in from_pretrained [rank3]: tokenizer_class_from_name(config_tokenizer_class) is not None [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 611, in tokenizer_class_from_name [rank3]: return getattr(module, class_name) [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1851, in __getattr__ [rank3]: module = self._get_module(self._class_to_module[name]) [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1865, in _get_module [rank3]: raise RuntimeError( [rank3]: RuntimeError: Failed to import transformers.models.llama.tokenization_llama_fast because of the following error (look up to see its traceback): [rank3]: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank3]: The above exception was the direct cause of the following exception: [rank3]: Traceback (most recent call last): [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 23, in <module> [rank3]: launch() [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 19, in launch [rank3]: run_exp() [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 110, in run_exp [rank3]: _training_function(config={"args": args, "callbacks": callbacks}) [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 72, in _training_function [rank3]: run_sft(model_args, data_args, training_args, finetuning_args, generating_args, callbacks) [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/sft/workflow.py", line 48, in run_sft [rank3]: tokenizer_module = load_tokenizer(model_args) [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank3]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 97, in load_tokenizer [rank3]: raise OSError("Failed to load tokenizer.") from e [rank3]: OSError: Failed to load tokenizer. [rank1]: Traceback (most recent call last): [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1863, in _get_module [rank1]: return importlib.import_module("." + module_name, self.__name__) [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module [rank1]: return _bootstrap._gcd_import(name[level:], package, level) [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import [rank1]: File "<frozen importlib._bootstrap>", line 1178, in _find_and_load [rank1]: File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked [rank1]: File "<frozen importlib._bootstrap>", line 690, in _load_unlocked [rank1]: File "<frozen importlib._bootstrap_external>", line 940, in exec_module [rank1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama_fast.py", line 29, in <module> [rank1]: from .tokenization_llama import LlamaTokenizer [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama.py", line 27, in <module> [rank1]: import sentencepiece as spm [rank1]: File "/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py", line 10, in <module> [rank1]: from . import _sentencepiece [rank1]: ImportError: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank1]: The above exception was the direct cause of the following exception: [rank1]: Traceback (most recent call last): [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 82, in load_tokenizer [rank1]: tokenizer = AutoTokenizer.from_pretrained( [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 912, in from_pretrained [rank1]: tokenizer_class_from_name(config_tokenizer_class) is not None [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 611, in tokenizer_class_from_name [rank1]: return getattr(module, class_name) [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1851, in __getattr__ [rank1]: module = self._get_module(self._class_to_module[name]) [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1865, in _get_module [rank1]: raise RuntimeError( [rank1]: RuntimeError: Failed to import transformers.models.llama.tokenization_llama_fast because of the following error (look up to see its traceback): [rank1]: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank1]: The above exception was the direct cause of the following exception: [rank1]: Traceback (most recent call last): [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 23, in <module> [rank1]: launch() [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 19, in launch [rank1]: run_exp() [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 110, in run_exp [rank1]: _training_function(config={"args": args, "callbacks": callbacks}) [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 72, in _training_function [rank1]: run_sft(model_args, data_args, training_args, finetuning_args, generating_args, callbacks) [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/sft/workflow.py", line 48, in run_sft [rank1]: tokenizer_module = load_tokenizer(model_args) [rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank1]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 97, in load_tokenizer [rank1]: raise OSError("Failed to load tokenizer.") from e [rank1]: OSError: Failed to load tokenizer. [rank2]: Traceback (most recent call last): [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1863, in _get_module [rank2]: return importlib.import_module("." + module_name, self.__name__) [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module [rank2]: return _bootstrap._gcd_import(name[level:], package, level) [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import [rank2]: File "<frozen importlib._bootstrap>", line 1178, in _find_and_load [rank2]: File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked [rank2]: File "<frozen importlib._bootstrap>", line 690, in _load_unlocked [rank2]: File "<frozen importlib._bootstrap_external>", line 940, in exec_module [rank2]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama_fast.py", line 29, in <module> [rank2]: from .tokenization_llama import LlamaTokenizer [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/llama/tokenization_llama.py", line 27, in <module> [rank2]: import sentencepiece as spm [rank2]: File "/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py", line 10, in <module> [rank2]: from . import _sentencepiece [rank2]: ImportError: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank2]: The above exception was the direct cause of the following exception: [rank2]: Traceback (most recent call last): [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 82, in load_tokenizer [rank2]: tokenizer = AutoTokenizer.from_pretrained( [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 912, in from_pretrained [rank2]: tokenizer_class_from_name(config_tokenizer_class) is not None [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/models/auto/tokenization_auto.py", line 611, in tokenizer_class_from_name [rank2]: return getattr(module, class_name) [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1851, in __getattr__ [rank2]: module = self._get_module(self._class_to_module[name]) [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/usr/local/lib/python3.11/dist-packages/transformers/utils/import_utils.py", line 1865, in _get_module [rank2]: raise RuntimeError( [rank2]: RuntimeError: Failed to import transformers.models.llama.tokenization_llama_fast because of the following error (look up to see its traceback): [rank2]: cannot import name '_sentencepiece' from partially initialized module 'sentencepiece' (most likely due to a circular import) (/usr/local/lib/python3.11/dist-packages/sentencepiece/__init__.py) [rank2]: The above exception was the direct cause of the following exception: [rank2]: Traceback (most recent call last): [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 23, in <module> [rank2]: launch() [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 19, in launch [rank2]: run_exp() [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 110, in run_exp [rank2]: _training_function(config={"args": args, "callbacks": callbacks}) [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 72, in _training_function [rank2]: run_sft(model_args, data_args, training_args, finetuning_args, generating_args, callbacks) [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/sft/workflow.py", line 48, in run_sft [rank2]: tokenizer_module = load_tokenizer(model_args) [rank2]: ^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank2]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/model/loader.py", line 97, in load_tokenizer [rank2]: raise OSError("Failed to load tokenizer.") from e [rank2]: OSError: Failed to load tokenizer. [rank0]:[W703 16:13:30.861219244 ProcessGroupNCCL.cpp:1479] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator()) W0703 16:13:31.449512 3913223 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3913282 closing signal SIGTERM W0703 16:13:31.450263 3913223 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3913283 closing signal SIGTERM W0703 16:13:31.450724 3913223 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3913284 closing signal SIGTERM E0703 16:13:31.765744 3913223 torch/distributed/elastic/multiprocessing/api.py:874] failed (exitcode: 1) local_rank: 0 (pid: 3913281) of binary: /usr/bin/python3.11 Traceback (most recent call last): File "/usr/local/bin/torchrun", line 8, in <module> sys.exit(main()) ^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 355, in wrapper return f(*args, **kwargs) ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/run.py", line 892, in main run(args) File "/usr/local/lib/python3.11/dist-packages/torch/distributed/run.py", line 883, in run elastic_launch( File "/usr/local/lib/python3.11/dist-packages/torch/distributed/launcher/api.py", line 139, in __call__ return launch_agent(self._config, self._entrypoint, list(args)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/launcher/api.py", line 270, in launch_agent raise ChildFailedError( torch.distributed.elastic.multiprocessing.errors.ChildFailedError: ============================================================ /home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py FAILED ------------------------------------------------------------ Failures: <NO_OTHER_FAILURES> ------------------------------------------------------------ Root Cause (first observed failure): [0]: time : 2025-07-03_16:13:31 host : wiseatc-Super-Server rank : 0 (local_rank: 0) exitcode : 1 (pid: 3913281) error_file: <N/A> traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html ============================================================ Traceback (most recent call last): File "/home/wiseatc/.local/bin/llamafactory-cli", line 8, in <module> sys.exit(main()) ^^^^^^ File "/home/wiseatc/LLaMA-Factory/src/llamafactory/cli.py", line 130, in main process = subprocess.run( ^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/subprocess.py", line 569, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['torchrun', '--nnodes', '1', '--node_rank', '0', '--nproc_per_node', '4', '--master_addr', '127.0.0.1', '--master_port', '38589', '/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py', 'saves/DeepSeek-R1-1.5B-Distill/lora/train_2025-07-03-16-00-01/training_args.yaml']' returned non-zero exit status 1.

/**************************************************************************** ** ** This file is part of the LibreCAD project, a 2D CAD program ** ** Copyright (C) 2010 R. van Twisk ([email protected]) ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file gpl-2.0.txt included in the ** packaging of this file. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** This copyright notice MUST APPEAR in all copies of the script! ** **********************************************************************/ #ifndef QC_APPLICATIONWINDOW_H #define QC_APPLICATIONWINDOW_H #undef QT_NO_WORKSPACE #include <qworkspace.h> #include "qc_mdiwindow.h" #include "qg_mainwindowinterface.h" #ifdef RS_SCRIPTING #include "qs_scripter.h" #include <qsproject.h> #endif class QG_LibraryWidget; class QG_CadToolBar; class QC_DialogFactory; class QG_LayerWidget; class QG_BlockWidget; class QG_CommandWidget; class QG_CoordinateWidget; class QG_MouseWidget; class QG_SelectionWidget; class QG_RecentFiles; class QG_PenToolBar; class QHelpEngine; class QC_PluginInterface; /** * Main application window. Hold together document, view and controls. * * @author Andrew Mustun */ class QC_ApplicationWindow: public QMainWindow, public QG_MainWindowInterface { Q_OBJECT public: QC_ApplicationWindow(); ~QC_ApplicationWindow(); void initActions(); void initMenuBar(); void initToolBar(); void initStatusBar(); void initSettings(); void restoreDocks(); void storeSettings(); void updateRecentFilesMenu(); void initMDI(); void initView(); bool queryExit(bool force); /** Catch hotkey for giving focus to command line. */ virtual void keyPressEvent(QKeyEvent* e); virtual void keyReleaseEvent(QKeyEvent* e); public slots: virtual void show(); void finishSplashScreen(); void slotFocus(); void slotBack(); void slotKillAllActions(); //void slotNext(); void slotEnter(); void slotFocusCommandLine(); void slotError(const QString& msg); void slotWindowActivated(QWidget* w); void slotWindowsMenuAboutToShow(); void slotWindowsMenuActivated(int); void slotTileHorizontal(); void slotTileVertical(); void slotPenChanged(RS_Pen p); /** generates a new document for a graphic. */ QC_MDIWindow* slotFileNew(RS_Document* doc=NULL); /** opens a document */ void slotFileOpen(); /** * opens a recent file document * @param id File Menu id of the file */ void slotFileOpenRecent(int id); /** * opens the given file. */ void slotFileOpen(const QString& fileName, RS2::FormatType type); /** saves a document */ void slotFileSave(); /** saves a document under a different filename*/ void slotFileSaveAs(); /** auto-save document */ void slotFileAutoSave(); /** exports the document as bitmap */ void slotFileExport(); bool slotFileExport(const QString& name, const QString& format, QSize size, bool black, bool bw=false); /** closes the current file */ void slotFileClose(); /** closing the current file */ void slotFileClosing(); /** prints the current file */ void slotFilePrint(); /** shows print preview of the current file */ void slotFilePrintPreview(bool on); /** exits the application */ void slotFileQuit(); /** toggle the grid */ void slotViewGrid(bool toggle); /** toggle the draft mode */ void slotViewDraft(bool toggle); /** toggle the statusbar */ void slotViewStatusBar(bool toggle); // void slotBlocksEdit(); void slotOptionsGeneral(); void slotScriptOpenIDE(); void slotScriptRun(); void slotRunStartScript(); void slotRunScript(); void slotRunScript(const QString& name); void slotInsertBlock(); void slotInsertBlock(const QString& name); /** shows an about dlg*/ void slotHelpAbout(); void slotHelpManual(); /** dumps entities to file */ void slotTestDumpEntities(RS_EntityContainer* d=NULL); /** dumps undo info to stdout */ void slotTestDumpUndo(); /** updates all inserts */ void slotTestUpdateInserts(); /** draws some random lines */ void slotTestDrawFreehand(); /** inserts a test block */ void slotTestInsertBlock(); /** inserts a test ellipse */ void slotTestInsertEllipse(); /** inserts a test text */ void slotTestInsertText(); /** inserts a test image */ void slotTestInsertImage(); /** unicode table */ void slotTestUnicode(); /** math experimental */ void slotTestMath01(); /** resizes window to 640x480 for screen shots */ void slotTestResize640(); /** resizes window to 640x480 for screen shots */ void slotTestResize800(); /** resizes window to 640x480 for screen shots */ void slotTestResize1024(); signals: void gridChanged(bool on); void draftChanged(bool on); void printPreviewChanged(bool on); void windowsChanged(bool windowsLeft); public: /** * @return Pointer to application window. */ static QC_ApplicationWindow* getAppWindow() { return appWindow; } /** * @return Pointer to workspace. */ QWorkspace* getWorkspace() { return workspace; } /** * @return Pointer to the currently active MDI Window or NULL if no * MDI Window is active. */ QC_MDIWindow* getMDIWindow() { if (workspace!=NULL) { return (QC_MDIWindow*)workspace->activeWindow(); } else { return NULL; } } /** * Implementation from RS_MainWindowInterface (and QS_ScripterHostInterface). * * @return Pointer to the graphic view of the currently active document * window or NULL if no window is available. */ virtual RS_GraphicView* getGraphicView() { QC_MDIWindow* m = getMDIWindow(); if (m!=NULL) { return m->getGraphicView(); } return NULL; } /** * Implementation from RS_MainWindowInterface (and QS_ScripterHostInterface). * * @return Pointer to the graphic document of the currently active document * window or NULL if no window is available. */ virtual RS_Document* getDocument() { QC_MDIWindow* m = getMDIWindow(); if (m!=NULL) { return m->getDocument(); } return NULL; } /** * Creates a new document. Implementation from RS_MainWindowInterface. */ virtual void createNewDocument( const QString& fileName = QString::null, RS_Document* doc=NULL) { slotFileNew(doc); if (fileName!=QString::null && getDocument()!=NULL) { getDocument()->setFilename(fileName); } } /** * Implementation from QG_MainWindowInterface. * * @return Pointer to this. */ virtual QMainWindow* getMainWindow() { return this; } /** * @return Pointer to action handler. Implementation from QG_MainWindowInterface. */ virtual QG_ActionHandler* getActionHandler() { return actionHandler; } //virtual QToolBar* createToolBar(const QString& name); //virtual void addToolBarButton(QToolBar* tb); /** * @return Pointer to the qsa object. */ #ifdef RS_SCRIPTING QSProject* getQSAProject() { if (scripter!=NULL) { return scripter->getQSAProject(); } else { return NULL; } } #endif void redrawAll(); void updateGrids(); /** * Implementation from QG_MainWindowInterface. */ virtual void setFocus2() { setFocus(); } /** Block list widget */ QG_BlockWidget* getBlockWidget(void) { return blockWidget; } protected: void closeEvent(QCloseEvent*); virtual void mouseReleaseEvent(QMouseEvent* e); private: /** Pointer to the application window (this). */ static QC_ApplicationWindow* appWindow; QTimer *autosaveTimer; /** Workspace for MDI */ QWorkspace* workspace; /** Dialog factory */ QC_DialogFactory* dialogFactory; /** Layer list widget */ QG_LayerWidget* layerWidget; /** Block list widget */ QG_BlockWidget* blockWidget; /** Library browser widget */ QG_LibraryWidget* libraryWidget; /** Layer list dock widget */ QDockWidget* layerDockWindow; /** Block list dock widget */ QDockWidget* blockDockWindow; /** Library list dock widget */ QDockWidget* libraryDockWindow; /** Command line */ QG_CommandWidget* commandWidget; QDockWidget* commandDockWindow; /** Coordinate widget */ QG_CoordinateWidget* coordinateWidget; /** Mouse widget */ QG_MouseWidget* mouseWidget; /** Selection Status */ QG_SelectionWidget* selectionWidget; /** Option widget for individual tool options */ QToolBar* optionWidget; /** Recent files list */ QG_RecentFiles* recentFiles; /** Action handler. */ QG_ActionHandler* actionHandler; #ifdef RS_SCRIPTING /** Scripting interface. */ QS_Scripter* scripter; #endif QMenu* fileMenu; QMenu* windowsMenu; QMenu* scriptMenu; QMenu* helpMenu; QMenu* testMenu; /** the main toolbars */ QToolBar* fileToolBar; QToolBar* editToolBar; QToolBar* zoomToolBar; // Toolbar for selecting the current pen QG_PenToolBar* penToolBar; // Toolbar for CAD tools QG_CadToolBar* cadToolBar; QHelpEngine* helpEngine; QDockWidget *helpWindow; QAction* scriptOpenIDE; QAction* scriptRun; QAction* helpAboutApp; QAction* helpManual; QAction *testDumpEntities; QAction *testDumpUndo; QAction *testUpdateInserts; QAction *testDrawFreehand; QAction *testInsertBlock; QAction *testInsertText; QAction *testInsertImage; QAction *testUnicode; QAction *testInsertEllipse; QAction *testMath01; QAction *testResize640; QAction *testResize800; QAction *testResize1024; //Plugin support private: void loadPlugins(); QMenu *findMenu(const QString &searchMenu, const QObjectList thisMenuList, const QString& currentEntry); QList<QC_PluginInterface*> loadedPlugins; public slots: void execPlug(); }; #endif 给出完整的代码注释

/home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources W0703 16:30:36.069853 3914856 torch/distributed/run.py:766] W0703 16:30:36.069853 3914856 torch/distributed/run.py:766] ***************************************** W0703 16:30:36.069853 3914856 torch/distributed/run.py:766] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. W0703 16:30:36.069853 3914856 torch/distributed/run.py:766] ***************************************** /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,321 >> loading file tokenizer.model [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,322 >> loading file tokenizer.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,322 >> loading file added_tokens.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,322 >> loading file special_tokens_map.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,322 >> loading file tokenizer_config.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,322 >> loading file chat_template.jinja /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources /home/wiseatc/.local/lib/python3.11/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. import pkg_resources [INFO|tokenization_utils_base.py:2313] 2025-07-03 16:30:43,904 >> Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. [INFO|configuration_utils.py:697] 2025-07-03 16:30:43,913 >> loading configuration file /mnt/data1/models/1.5B/config.json [INFO|configuration_utils.py:771] 2025-07-03 16:30:43,919 >> Model config Qwen2Config { "_name_or_path": "/mnt/data1/models/1.5B", "architectures": [ "Qwen2ForCausalLM" ], "attention_dropout": 0.0, "bos_token_id": 151643, "eos_token_id": 151643, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 8960, "max_position_embeddings": 131072, "max_window_layers": 21, "model_type": "qwen2", "num_attention_heads": 12, "num_hidden_layers": 28, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 10000, "sliding_window": 4096, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.49.0", "use_cache": true, "use_mrope": false, "use_sliding_window": false, "vocab_size": 151936 } [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file tokenizer.model [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file tokenizer.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file added_tokens.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file special_tokens_map.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file tokenizer_config.json [INFO|tokenization_utils_base.py:2048] 2025-07-03 16:30:43,920 >> loading file chat_template.jinja [INFO|tokenization_utils_base.py:2313] 2025-07-03 16:30:44,493 >> Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. /usr/local/lib/python3.11/dist-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user. warnings.warn( # warn only once [rank1]:[W703 16:30:45.102845887 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 1] using GPU 1 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device. /usr/local/lib/python3.11/dist-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user. warnings.warn( # warn only once [rank2]:[W703 16:30:45.126706430 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 2] using GPU 2 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device. /usr/local/lib/python3.11/dist-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user. warnings.warn( # warn only once [rank3]:[W703 16:30:45.136836682 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 3] using GPU 3 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device. Setting num_proc from 16 back to 1 for the train split to disable multiprocessing as it only contains one shard. Generating train split: 0 examples [00:00, ? examples/s] Generating train split: 120 examples [00:00, 6525.39 examples/s] Converting format of dataset (num_proc=16): 0%| | 0/120 [00:00<?, ? examples/s] Converting format of dataset (num_proc=16): 0%| | 0/120 [00:00<?, ? examples/s] Converting format of dataset (num_proc=16): 0%| | 0/120 [00:00<?, ? examples/s] /usr/local/lib/python3.11/dist-packages/torch/distributed/distributed_c10d.py:4631: UserWarning: No device id is provided via init_process_group or barrier . Using the current device set by the user. warnings.warn( # warn only once [rank0]:[W703 16:31:05.679961201 ProcessGroupNCCL.cpp:4718] [PG ID 0 PG GUID 0 Rank 0] using GPU 0 as device used by this process is currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. You can pecify device_id in init_process_group() to force use of a particular device. [rank0]: multiprocess.pool.RemoteTraceback: [rank0]: """ [rank0]: Traceback (most recent call last): [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/multiprocess/pool.py", line 125, in worker [rank0]: result = (True, func(*args, **kwds)) [rank0]: ^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/utils/py_utils.py", line 688, in _write_generator_to_queue [rank0]: for i, result in enumerate(func(**kwargs)): [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/arrow_dataset.py", line 3501, in _map_single [rank0]: for i, example in iter_outputs(shard_iterable): [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/arrow_dataset.py", line 3475, in iter_outputs [rank0]: yield i, apply_function(example, i, offset=offset) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/arrow_dataset.py", line 3398, in apply_function [rank0]: processed_inputs = function(*fn_args, *additional_args, **fn_kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/data/converter.py", line 94, in __call__ [rank0]: if self.dataset_attr.prompt and example[self.dataset_attr.prompt]: [rank0]: ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/formatting/formatting.py", line 278, in __getitem__ [rank0]: value = self.data[key] [rank0]: ~~~~~~~~~^^^^^ [rank0]: KeyError: 'instruction' [rank0]: """ [rank0]: The above exception was the direct cause of the following exception: [rank0]: Traceback (most recent call last): [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 23, in <module> [rank0]: launch() [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py", line 19, in launch [rank0]: run_exp() [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 110, in run_exp [rank0]: _training_function(config={"args": args, "callbacks": callbacks}) [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/tuner.py", line 72, in _training_function [rank0]: run_sft(model_args, data_args, training_args, finetuning_args, generating_args, callbacks) [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/train/sft/workflow.py", line 51, in run_sft [rank0]: dataset_module = get_dataset(template, model_args, data_args, training_args, stage="sft", **tokenizer_module) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/data/loader.py", line 304, in get_dataset [rank0]: dataset = _get_merged_dataset(data_args.dataset, model_args, data_args, training_args, stage) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/data/loader.py", line 182, in _get_merged_dataset [rank0]: datasets[dataset_name] = _load_single_dataset(dataset_attr, model_args, data_args, training_args) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/data/loader.py", line 162, in _load_single_dataset [rank0]: return align_dataset(dataset, dataset_attr, data_args, training_args) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/LLaMA-Factory/src/llamafactory/data/converter.py", line 279, in align_dataset [rank0]: return dataset.map( [rank0]: ^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/arrow_dataset.py", line 557, in wrapper [rank0]: out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/arrow_dataset.py", line 3171, in map [rank0]: for rank, done, content in iflatmap_unordered( [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/utils/py_utils.py", line 728, in iflatmap_unordered [rank0]: [async_result.get(timeout=0.05) for async_result in async_results] [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/datasets/utils/py_utils.py", line 728, in [rank0]: [async_result.get(timeout=0.05) for async_result in async_results] [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/wiseatc/.local/lib/python3.11/site-packages/multiprocess/pool.py", line 774, in get [rank0]: raise self._value [rank0]: KeyError: 'instruction' [rank0]:[W703 16:31:06.912491219 ProcessGroupNCCL.cpp:1479] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator()) W0703 16:31:07.960560 3914856 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3914916 closing signal SIGTERM W0703 16:31:07.961188 3914856 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3914917 closing signal SIGTERM W0703 16:31:07.961536 3914856 torch/distributed/elastic/multiprocessing/api.py:900] Sending process 3914918 closing signal SIGTERM E0703 16:31:08.371267 3914856 torch/distributed/elastic/multiprocessing/api.py:874] failed (exitcode: 1) local_rank: 0 (pid: 3914915) of binary: /usr/bin/python3.11 Traceback (most recent call last): File "/usr/local/bin/torchrun", line 8, in <module> sys.exit(main()) ^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 355, in wrapper return f(*args, **kwargs) ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/run.py", line 892, in main run(args) File "/usr/local/lib/python3.11/dist-packages/torch/distributed/run.py", line 883, in run elastic_launch( File "/usr/local/lib/python3.11/dist-packages/torch/distributed/launcher/api.py", line 139, in __call__ return launch_agent(self._config, self._entrypoint, list(args)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/torch/distributed/launcher/api.py", line 270, in launch_agent raise ChildFailedError( torch.distributed.elastic.multiprocessing.errors.ChildFailedError: ============================================================ /home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py FAILED ------------------------------------------------------------ Failures: <NO_OTHER_FAILURES> ------------------------------------------------------------ Root Cause (first observed failure): [0]: time : 2025-07-03_16:31:07 host : wiseatc-Super-Server rank : 0 (local_rank: 0) exitcode : 1 (pid: 3914915) error_file: <N/A> traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html ============================================================ Traceback (most recent call last): File "/home/wiseatc/.local/bin/llamafactory-cli", line 8, in <module> sys.exit(main()) ^^^^^^ File "/home/wiseatc/LLaMA-Factory/src/llamafactory/cli.py", line 130, in main process = subprocess.run( ^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/subprocess.py", line 569, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['torchrun', '--nnodes', '1', '--node_rank', '0', '--nproc_per_node', '4', '--master_addr', '127.0.0.1', '--master_port', '41919', '/home/wiseatc/LLaMA-Factory/src/llamafactory/launcher.py', 'saves/DeepSeek-R1-1.5B-Distill/lora/train_2025-07-03-16-29-46/training_args.yaml']' returned non-zero exit status 1.

[INFO|<string>:438] 2025-03-04 19:33:39,759 >> Training completed. Do not forget to share your model on huggingface.co/models =) swanlab: Step 210 on key train/epoch already exists, ignored. swanlab: Step 210 on key train/num_input_tokens_seen already exists, ignored. {'train_runtime': 222.6408, 'train_samples_per_second': 7.546, 'train_steps_per_second': 0.943, 'train_loss': 3.434720888591948, 'epoch': 30.0, 'num_input_tokens_seen': 665264} 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 210/210 [03:39<00:00, 1.04s/it] [INFO|trainer.py:3942] 2025-03-04 19:33:39,764 >> Saving model checkpoint to saves/DeepSeek-R1-1.5B-Distill/lora/train_2025-03-04-19-22-19 [INFO|configuration_utils.py:697] 2025-03-04 19:33:39,782 >> loading configuration file /root/autodl-tmp/ai/models/DeepSeek-R1-Distill-Qwen-1.5B/config.json [INFO|configuration_utils.py:771] 2025-03-04 19:33:39,783 >> Model config Qwen2Config { "architectures": [ "Qwen2ForCausalLM" ], "attention_dropout": 0.0, "bos_token_id": 151643, "eos_token_id": 151643, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 8960, "max_position_embeddings": 131072, "max_window_layers": 21, "model_type": "qwen2", "num_attention_heads": 12, "num_hidden_layers": 28, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 10000, "sliding_window": 4096, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.49.0", "use_cache": true, "use_mrope": false, "use_sliding_window": false, "vocab_size": 151936 } ***** train metrics ***** epoch = 30.0 num_input_tokens_seen = 665264 total_flos = 5773005GF train_loss = 3.4347 train_runtime = 0:03:42.64 train_samples_per_second = 7.546 train_steps_per_second = 0.943 Figure saved at: saves/DeepSeek-R1-1.5B-Distill/lora/train_2025-03-04-19-22-19/training_loss.png [WARNING|2025-03-04 19:33:40] llamafactory.extras.ploting:162 >> No metric eval_loss to plot. [WARNING|2025-03-04 19:33:40] llamafactory.extras.ploting:162 >> No metric eval_accuracy to plot. [INFO|modelcard.py:449] 2025-03-04 19:33:40,019 >> Dropping the following result as it does not have all the necessary fields: {'task': {'name': 'Causal Language Modeling', 'type': 'text-generation'}} swanlab: Experiment dragon-6 has completed swanlab: 🌟 Run swanlab watch /root/autodl-tmp/ai/LLaMA-Factory/swanlog to view SwanLab Experiment Dashboard locally swanlab: 🏠 View project at https://swanlab.cn/@chrisfang/llamafactory-test swanlab: 🚀 View run at https://swanlab.cn/@chrisfang/llamafactory-test/runs/l0n927vfjxvq6iclvs3a8 优化空间

利用以上改善代码的思路帮我改善下面的代码 from maix import camera, display, image, nn, app import time, os # 初始化模型 detector = nn.YOLOv5(model="/root/models/mymodel/model_127448.mud", dual_buff=True) ocr = nn.PP_OCR("/root/models/pp_ocr.mud") # OCR模型初始化 SAVE_DIR = "/root/models/mymodel/" os.makedirs(SAVE_DIR, exist_ok=True) # 硬件初始化(关键修改点1) cam = camera.Camera( detector.input_width(), detector.input_height(), format=image.FORMAT_BGR888 # 强制指定摄像头输出格式 ) disp = display.Display() # 状态变量 last_save_time = 0 save_count = 0 # 调试信息打印(关键修改点2) print(f"[系统诊断] 摄像头格式: {cam.format}") print(f"[系统诊断] 检测器输入格式: {detector.input_format}") print(f"[系统诊断] OCR输入格式: {ocr.input_format}") def ocr_processing(img_path): """ 增强版OCR处理函数 """ try: # 加载并转换图像格式(关键修改点3) img = image.load(img_path) if img.format != ocr.input_format: print(f"[格式转换] 原始格式: {img.format} -> 目标格式: {ocr.input_format}") img = img.convert(format=ocr.input_format) # OCR识别处理 objs = ocr.detect(img) text = ''.join([obj.char_str() for obj in objs]) print(f"[识别结果] {text}") # 可视化增强处理 for obj in objs: points = obj.box.to_list() img.draw_keypoints(points, image.COLOR_RED, 4, -1, 1) img.draw_string(obj.box.x4, obj.box.y4, obj.char_str(), image.COLOR_RED) disp.show(img) return text except Exception as e: print(f"[OCR异常] {str(e)}") return "" while not app.need_exit(): try: img = cam.read() objs = detector.detect(img, conf_th=0.5, iou_th=0.45) # 物体检测处理(关键修改点4) if len(objs) > 0 and (time.time() - last_save_time) >= 3: filename = f"{SAVE_DIR}detect_{save_count}_{int(time.time())}.jpg" # 创建保存用图像副本 save_img = img.copy().convert(format=image.FORMAT_BGR888) # 确保保存格式一致 if save_img.save(filename, quality=85): print(f"[图像保存] {filename}") last_save_time = time.time() save_count += 1 ocr_result = ocr_processing(filename) print(f"[识别日志] {ocr_result}") # 显示处理增强 for obj in objs: img.draw_rect(obj.x, obj.y, obj.w, obj.h, color=image.COLOR_RED) msg = f'{detector.labels[obj.class_id]}: {obj.score:.2f}' img.draw_string(obj.x, obj.y+2, msg, scale=0.5, color=image.COLOR_RED) disp.show(img) except Exception as e: print(f"[运行异常] {str(e)}") break

最新推荐

recommend-type

基于单片机的水位自动检测与控制系统开题报告.doc

基于单片机的水位自动检测与控制系统开题报告.doc
recommend-type

cc65 Windows完整版发布:6502 C开发工具

cc65是一个针对6502处理器的完整C编程开发环境,特别适用于Windows操作系统。6502处理器是一种经典的8位微处理器,于1970年代被广泛应用于诸如Apple II、Atari 2600、NES(任天堂娱乐系统)等早期计算机和游戏机中。cc65工具集能够允许开发者使用C语言编写程序,这对于那些希望为这些老旧系统开发软件的程序员来说是一大福音,因为相较于汇编语言,C语言更加高级、易读,并且具备更好的可移植性。 cc65开发工具包主要包含以下几个重要组件: 1. C编译器:这是cc65的核心部分,它能够将C语言源代码编译成6502处理器的机器码。这使得开发者可以用高级语言编写程序,而不必处理低级的汇编指令。 2. 链接器:链接器负责将编译器生成的目标代码和库文件组合成一个单独的可执行程序。在6502的开发环境中,链接器还需要处理各种内存段的定位和映射问题。 3. 汇编器:虽然主要通过C语言进行开发,但某些底层操作仍然可能需要使用汇编语言来实现。cc65包含了一个汇编器,允许程序员编写汇编代码段。 4. 库和运行时:cc65提供了一套标准库,这些库函数为C语言提供了支持,并且对于操作系统级别的功能进行了封装,使得开发者能够更方便地进行编程。运行时支持包括启动代码、中断处理、内存管理等。 5. 开发工具和文档:除了基本的编译、链接和汇编工具外,cc65还提供了一系列辅助工具,如反汇编器、二进制文件编辑器、交叉引用器等。同时,cc65还包含丰富的文档资源,为开发者提供了详尽的使用指南、编程参考和示例代码。 cc65可以广泛用于学习和开发6502架构相关的软件,尤其适合那些对6502处理器、复古计算机或者早期游戏系统有兴趣的开发者。这些开发者可能想要创建或修改旧式游戏、系统软件、仿真器,或者进行技术研究和学习。 尽管cc65是一个功能强大的工具,但它也要求开发者对目标平台的硬件架构和操作系统有足够的了解。这是因为6502并非现代处理器,它对内存访问、I/O操作和中断管理等有着特殊的限制和要求。因此,使用cc65需要开发者具备一定的背景知识,包括但不限于6502指令集、内存映射、硬件寄存器操作等方面的内容。 此外,cc65针对Windows平台进行了优化和封装,使得它可以在Windows操作系统上无缝运行,这对于习惯于Windows环境的用户是一个好消息。不过,如果用户使用的是其他操作系统,可能需要通过相应的兼容层或虚拟机来运行Windows环境,以便使用cc65工具。 总的来说,cc65提供了一种相对简单的方式来开发运行在6502处理器上的软件。它极大地降低了开发难度,使得更多的人能够接触和参与到基于6502平台的软件开发中来,为这个历史悠久的平台注入了新的活力。
recommend-type

【CLIP模型实战】:从数据预处理到代码实现的图文相似度计算完全指南

# 1. CLIP模型概述 在人工智能领域中,CLIP(Contrastive Language-Image Pre-training)模型作为一款开创性的多模态学习技术,已经成为业界瞩目的焦点。CLIP模型是由OpenAI在2021年推出的,其创新之处在于通过大规模的图文对齐数据进行预训练,能够理解和匹配图像与自然语言描述之间的关联性。CLIP突破了传统方法在特定任务上需要大规模标注数据的限制
recommend-type

车载以太网doip协议格式

<think>首先,用户的问题是:“我想查找关于车载以太网DOIP协议的数据格式或规范”。用户引用了站内内容,其中提到DoIP是基于以太网的通讯协议,用于传输UDS协议的数据,规范于ISO13400标准。关键点:-DoIP协议:DiagnosticcommunicationoverInternetProtocol-规范:ISO13400标准-数据格式:我需要提供关于DoIP数据格式的详细信息根据系统级指令:-所有行内数学表达式使用$...$格式-独立公式使用$$...$$格式并单独成段-LaTeX语法正确-使用中文回答-生成相关问题-回答中引用的段落末尾自然地添加引用标识-回答结构清晰,帮助用
recommend-type

JavaScript中文帮助手册:初学者实用指南

### JavaScript中文帮助手册知识点概述 #### 1. JavaScript简介 JavaScript是一种轻量级的编程语言,广泛用于网页开发。它能够增强用户与网页的交互性,使得网页内容变得动态和富有生气。JavaScript能够操纵网页中的HTML元素,响应用户事件,以及与后端服务器进行通信等。 #### 2. JavaScript基本语法 JavaScript的语法受到了Java和C语言的影响,包括变量声明、数据类型、运算符、控制语句等基础组成部分。以下为JavaScript中常见的基础知识点: - 变量:使用关键字`var`、`let`或`const`来声明变量,其中`let`和`const`是ES6新增的关键字,提供了块级作用域和不可变变量的概念。 - 数据类型:包括基本数据类型(字符串、数值、布尔、null和undefined)和复合数据类型(对象、数组和函数)。 - 运算符:包括算术运算符、关系运算符、逻辑运算符、位运算符等。 - 控制语句:条件判断语句(if...else、switch)、循环语句(for、while、do...while)等。 - 函数:是JavaScript中的基础,可以被看作是一段代码的集合,用于封装重复使用的代码逻辑。 #### 3. DOM操作 文档对象模型(DOM)是HTML和XML文档的编程接口。JavaScript可以通过DOM操作来读取、修改、添加或删除网页中的元素和内容。以下为DOM操作的基础知识点: - 获取元素:使用`getElementById()`、`getElementsByTagName()`等方法获取页面中的元素。 - 创建和添加元素:使用`document.createElement()`创建新元素,使用`appendChild()`或`insertBefore()`方法将元素添加到文档中。 - 修改和删除元素:通过访问元素的属性和方法,例如`innerHTML`、`textContent`、`removeChild()`等来修改或删除元素。 - 事件处理:为元素添加事件监听器,响应用户的点击、鼠标移动、键盘输入等行为。 #### 4. BOM操作 浏览器对象模型(BOM)提供了独立于内容而与浏览器窗口进行交互的对象和方法。以下是BOM操作的基础知识点: - window对象:代表了浏览器窗口本身,提供了许多属性和方法,如窗口大小调整、滚动、弹窗等。 - location对象:提供了当前URL信息的接口,可以用来获取URL、重定向页面等。 - history对象:提供了浏览器会话历史的接口,可以进行导航历史操作。 - screen对象:提供了屏幕信息的接口,包括屏幕的宽度、高度等。 #### 5. JavaScript事件 JavaScript事件是用户或浏览器自身执行的某些行为,如点击、页面加载、键盘按键、鼠标移动等。通过事件,JavaScript可以对这些行为进行响应。以下为事件处理的基础知识点: - 事件类型:包括鼠标事件、键盘事件、表单事件、窗口事件等。 - 事件监听:通过`addEventListener()`方法为元素添加事件监听器,规定当事件发生时所要执行的函数。 - 事件冒泡:事件从最深的节点开始,然后逐级向上传播到根节点。 - 事件捕获:事件从根节点开始,然后逐级向下传播到最深的节点。 #### 6. JavaScript高级特性 随着ECMAScript标准的演进,JavaScript引入了许多高级特性,这些特性包括但不限于: - 对象字面量增强:属性简写、方法简写、计算属性名等。 - 解构赋值:可以从数组或对象中提取数据,赋值给变量。 - 模板字符串:允许嵌入表达式。 - 异步编程:Promise、async/await等用于处理异步操作。 - 模块化:使用`import`和`export`关键字导入和导出模块。 - 类和模块:引入了`class`关键字,允许使用面向对象编程风格定义类,以及模块的声明。 #### 7. 开发工具和调试技巧 为了提高JavaScript开发效率和调试问题,以下是一些常用的工具和调试技巧: - 浏览器的开发者工具:包括控制台(Console)、元素查看器(Elements)、网络监控(Network)、源码编辑器(Sources)等。 - 断点调试:在源码编辑器中设置断点,逐步执行代码,查看变量值和程序流程。 - console.log:在控制台输出日志,帮助理解程序执行流程和变量状态。 - 使用JavaScript验证工具:如JSHint、ESLint等,可以在开发过程中进行代码质量检查。 以上就是《JavaScript中文帮助手册》中可能包含的主要知识点。作为初学者,通过这些内容可以系统地学习和掌握JavaScript基础和进阶知识,实现从初学到实践的跨越。在实际应用中,还需结合具体实例和项目练习,不断加深理解和熟练操作。
recommend-type

深入理解MySQL存储引擎:InnoDB与MyISAM的终极对决

# 1. MySQL存储引擎概述 MySQL数据库的灵活性和高性能在很大程度上得益于其存储引擎架构。**存储引擎**是MySQL中用于存储、索引、查询数据的底层软件模块。不同的存储引擎拥有不同的功能和特性,允许数据库管理员针对特定的应用需求选择最佳的存储引擎。例如,**InnoDB**提供事务支持和行级锁定,适用于需要ACID(原子
recommend-type

window中系统中断,cpu占用100%

<think>首先,用户的问题是关于解决Windows系统中“系统中断”导致CPU占用100%的问题。我需要基于提供的引用和系统指令来构建一个结构清晰的回答。系统指令:-所有行内数学表达式必须使用$...$格式。-独立公式使用$$...$$格式并单独成段。-LaTeX语法正确。-使用中文回答。-生成相关问题。-在回答中引用的段落末尾添加引用标识,例如[^1]。-回答结构清晰,帮助用户逐步解决问题。-参考站内引用:引用[1]是关于CPU使用率100%的应急措施,引用[2]是关于Java程序CPU占用过高的解决步骤,引用[3]是关于CPU软中断导致高利用率的分析与解决方案。用户的问题:Window
recommend-type

C++Builder6.0缺失帮助文件的解决方案

标题“BCB6.0帮助文件”和描述“很多用户的C++Builder6.0的版本没有帮助文件,help文件对学习和研究BCB6.0是很重要的。”表明了我们讨论的主题是关于C++Builder(通常简称BCB)6.0版本的官方帮助文件。C++Builder是一款由Borland公司(后被Embarcadero Technologies公司收购)开发的集成开发环境(IDE),专门用于C++语言的开发。该软件的第六版,即BCB6.0,于2002年发布,是该系列的一个重要版本。在这个版本中,提供了一个帮助文件,对于学习和研究BCB6.0至关重要。因为帮助文件中包含了大量关于IDE使用的指导、编程API的参考、示例代码等,是使用该IDE不可或缺的资料。 我们可以通过【压缩包子文件的文件名称列表】中的“BCB6.0_Help”推测,这可能是一个压缩文件,包含了帮助文件的副本,可能是一个ZIP或者其他格式的压缩文件。该文件的名称“BCB6.0_Help”暗示了文件中包含的是与C++Builder6.0相关的帮助文档。在实际获取和解压该文件后,用户能够访问到详尽的文档,以便更深入地了解和利用BCB6.0的功能。 BCB6.0帮助文件的知识点主要包括以下几个方面: 1. 环境搭建和配置指南:帮助文档会解释如何安装和配置BCB6.0环境,包括如何设置编译器、调试器和其他工具选项,确保用户能够顺利开始项目。 2. IDE使用教程:文档中应包含有关如何操作IDE界面的说明,例如窗口布局、菜单结构、快捷键使用等,帮助用户熟悉开发环境。 3. 语言参考:C++Builder6.0支持C++语言,因此帮助文件会包含C++语言核心特性的说明、标准库参考、模板和STL等。 4. VCL框架说明:BCB6.0是基于Visual Component Library(VCL)框架的,帮助文件会介绍如何使用VCL构建GUI应用程序,包括组件的使用方法、事件处理、窗体设计等。 5. 数据库编程:文档会提供关于如何利用C++Builder进行数据库开发的指导,涵盖了数据库连接、SQL语言、数据集操作等关键知识点。 6. 高级功能介绍:帮助文件还会介绍一些高级功能,如使用组件面板、定制组件、深入到编译器优化、代码分析工具的使用等。 7. 示例项目和代码:为了更好地演示如何使用IDE和语言特性,帮助文件通常包含了一个或多个示例项目以及一些实用的代码片段。 8. 第三方插件和工具:BCB6.0还可能支持第三方插件,帮助文件可能会对一些广泛使用的插件进行介绍和解释如何安装和使用它们。 9. 故障排除和调试:文档会提供一些常见问题的解决方案、调试技巧以及性能调优建议。 10. 版本更新记录:虽然版本更新记录通常不会在帮助文件内详细描述,但可能会提到重大的新增特性、改进和已知问题。 11. 联系方式和资源:帮助文件中可能会包含Embarcadero公司的技术支持联系方式,以及推荐的外部资源,比如论坛、在线文档链接和社区。 在学习和研究BCB6.0时,帮助文件是一个十分宝贵的资源,它能提供快速准确的信息和指导。对于任何一个使用BCB6.0进行开发的程序员来说,熟悉这些知识点是必不可少的。
recommend-type

【湖北专升本MySQL强化训练】:5大SQL语句编写技巧,迅速提升实战能力

# 1. SQL语言基础 ## 1.1 SQL语言简介 SQL,即结构化查询语言(Structured Query Language),是一种用于管理关系数据库管理系统(RDBMS)的标准编程语言。它广泛应用于数据的查询、插入、更新和删除操作,是数据库管理员和开发人员必须掌握的核心技能。 ## 1.2 SQL语言的组成 SQL语言主要由数据定义语言(DDL),数据操纵语言
recommend-type

HFSS如何设置网格化细化

<think>我们正在讨论HFSS中的网格细化设置。根据引用[2]和[3],HFSS使用自适应网格剖分技术,通过迭代细化网格直到满足收敛标准。用户想了解具体的设置方法。关键点:1.自适应网格剖分过程:HFSS通过比较连续迭代之间的S参数(或其他参数)的变化来判断收敛。2.收敛标准设置:用户可以设置收敛的阈值(如ΔS)。3.初始网格设置:在求解设置中,可以设置初始网格的选项(如Lambda细化)。步骤:1.在HFSS中,右键点击工程树中的“Analysis”节点,选择“AddSolutionSetup”来添加一个新的求解设置(或者编辑已有的求解设置)。2.在求解设置对话框中,切换到“Genera