commit 73d42bbccf9901a7296c94b03cb253911ba4173c Author: HCha Date: Fri Mar 7 15:32:58 2025 +0800 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dac59c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Compiled Python files +*.pyc +__pycache__/ + +# PyInstaller files +main.spec +build/ +dist/ +main.build/ +main.dist/ +main.onefile-build/ +*.pyd + +# Executable files +*.exe +*.dll + +# OS generated files +.DS_Store +Thumbs.db +.directory + +# Dependency management +venv/ +env/ +.venv/ +*.egg-info/ + +# Log files +*.log + +# Temporary files +*.tmp +*.bak +*.swp +*~ + +# IDE specific files +.idea/ +.vscode/ +*.sublime-project +*.sublime-workspace + +# Data files +*.npz +*.npy + +# Ignore spec.md +spec.md \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dbbe355 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..35577d6 --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# Any2MIF 文件转换器 + +Any2MIF是一个现代化的文件转换工具,可以将任意文件转换为MIF(Memory Initialization File)格式,并提供基础的图像处理功能。 + +## 功能特点 + +- **文件转换**:将任意文件转换为MIF格式 +- **参数配置**:自定义WIDTH、DEPTH、基数设置和地址偏移量 +- **图像处理**:支持灰度化、二值化、降噪处理和尺寸标准化 +- **批量处理**:支持批量转换多个文件 +- **主题切换**:支持浅色/深色主题 + +## 系统要求 + +- Python 3.8+ +- PyQt6 +- Pillow +- NumPy + +## 安装 + +1. 克隆或下载本仓库 +2. 安装依赖: + +```bash +pip install -r requirements.txt +``` + +## 使用方法 + +运行主程序: + +```bash +python main.py +``` + +## 打包为可执行文件 + +Any2MIF可以使用Nuitka打包成单文件.exe可执行程序,无需安装Python环境即可运行。 + +### 使用build.py脚本打包 + +1. 确保已安装所有依赖: + ```bash + pip install -r requirements.txt + ``` + +2. 运行build.py脚本: + ```bash + python build.py + ``` + + 这将自动安装Nuitka(如果尚未安装),并将项目打包成名为"Any2MIF.exe"的单文件可执行程序。 + +3. 打包选项: + - 指定输出文件名:`python build.py --output MyConverter` + - 保留控制台窗口(用于调试):`python build.py --console` + +### 手动使用Nuitka打包 + +如果你想手动控制打包过程,可以直接使用Nuitka命令: + +```bash +pip install nuitka +python -m nuitka --standalone --onefile --windows-disable-console --include-package=PyQt6 --include-package=PIL --include-package=numpy --include-data-dir=resources=resources --output-filename=Any2MIF.exe main.py +``` + +打包后的可执行文件可以在任何Windows系统上运行,无需安装Python或其他依赖。 + +### 基本操作流程 + +1. 点击"添加文件"或"添加文件夹"按钮,或直接拖放文件到应用程序中 +2. 配置转换参数(数据宽度、深度、数据格式等) +3. 如果是图像文件,可以使用图像处理工具进行预处理 +4. 点击"转换"按钮开始转换 +5. 选择输出目录 +6. 等待转换完成 + +### 参数说明 + +- **数据宽度 (WIDTH)**:指定MIF文件中每个数据的位宽(8位、16位或32位) +- **深度 (DEPTH)**:指定MIF文件中的数据数量,可以自动计算或手动设置 +- **数据格式**:指定MIF文件中数据的表示方式(十六进制、二进制或十进制) +- **地址偏移量**:指定MIF文件中地址的起始值 +- **地址格式**:指定MIF文件中地址的表示方式(标准格式或紧凑格式) +- **每行数据数量**:指定MIF文件中每行显示的数据数量 + +### 图像处理 + +对于图像文件,Any2MIF提供以下处理功能: + +- **灰度化**:将彩色图像转换为灰度图像,支持平均值法、加权平均法和最大值法 +- **二值化**:将灰度图像转换为黑白图像,支持固定阈值、自适应阈值和Otsu阈值 +- **降噪处理**:去除图像中的噪点,支持中值滤波、高斯滤波和双边滤波 +- **尺寸标准化**:调整图像大小,可以保持或不保持纵横比 + +## 许可证 + +Copyright (c) 2025 Any2MIF Project + +本项目采用GNU Affero通用公共许可证第3版(AGPL-3.0)进行许可。 + +这意味着: +- 您可以自由使用、修改和分发本软件 +- 如果您修改了本软件,必须以相同的许可证发布修改后的版本 +- 如果您通过网络提供本软件的服务,必须提供完整的源代码 +- 详细条款请参阅[GNU AGPL-3.0许可证](https://www.gnu.org/licenses/agpl-3.0.html) \ No newline at end of file diff --git a/build.py b/build.py new file mode 100644 index 0000000..bf42159 --- /dev/null +++ b/build.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 打包脚本 +使用Nuitka将项目打包成单文件.exe可执行程序 +""" + +import os +import sys +import subprocess +import shutil +import argparse +from pathlib import Path + +def check_nuitka(): + """检查Nuitka是否已安装,如果未安装则安装""" + try: + import nuitka + return True + except ImportError: + print("Nuitka未安装,正在安装...") + try: + subprocess.check_call([sys.executable, "-m", "pip", "install", "nuitka"]) + print("Nuitka安装成功") + return True + except subprocess.CalledProcessError: + print("Nuitka安装失败") + return False + +def ensure_icon_exists(): + """确保图标文件存在""" + icon_path = Path("resources/icon.ico") + if not icon_path.exists(): + print("图标文件不存在,正在创建...") + try: + # 尝试导入create_icon模块 + try: + import create_icon + create_icon.create_icon() + except ImportError: + # 如果模块不存在,尝试运行脚本 + if Path("create_icon.py").exists(): + subprocess.check_call([sys.executable, "create_icon.py"]) + else: + print("警告:找不到create_icon.py脚本,将使用默认图标") + except Exception as e: + print(f"创建图标文件失败:{e}") + print("将使用默认图标") + else: + print(f"图标文件已存在:{icon_path.absolute()}") + +def build_executable(output_name=None, debug=False, console=False): + """使用Nuitka构建可执行文件""" + # 确保当前目录是项目根目录 + project_root = Path(__file__).parent.absolute() + os.chdir(project_root) + + # 确保图标文件存在 + ensure_icon_exists() + + # 设置输出名称 + if output_name is None: + output_name = "Any2MIF" + + # 构建Nuitka命令 + cmd = [ + sys.executable, + "-m", + "nuitka", + "--standalone", # 创建独立的可执行文件 + "--onefile", # 创建单文件可执行程序 + #"--windows-disable-console" if not console else "", # 禁用控制台窗口(除非debug模式) + "--windows-console-mode=disable", + "--windows-icon-from-ico=resources/icon.ico" if os.path.exists("resources/icon.ico") else "", # 设置图标 + #"--include-package=PyQt6", # 包含PyQt6包 + "--enable-plugin=pyqt6", + "--include-package=PIL", # 包含Pillow包 + "--include-package=numpy", # 包含numpy包 + "--include-data-dir=resources=resources", # 包含资源文件 + f"--output-filename={output_name}.exe", # 设置输出文件名 + "main.py" # 入口文件 + ] + + # 移除空字符串 + cmd = [item for item in cmd if item] + + # 打印命令 + print("执行命令:") + print(" ".join(cmd)) + + # 执行命令 + try: + subprocess.check_call(cmd) + print(f"构建成功!可执行文件位于:{os.path.join(project_root, output_name + '.exe')}") + return True + except subprocess.CalledProcessError as e: + print(f"构建失败:{e}") + return False + +def main(): + """主函数""" + parser = argparse.ArgumentParser(description="Any2MIF打包脚本") + parser.add_argument("--output", "-o", help="输出文件名(不包含扩展名)", default="Any2MIF") + parser.add_argument("--debug", "-d", action="store_true", help="启用调试模式") + parser.add_argument("--console", "-c", action="store_true", help="保留控制台窗口") + args = parser.parse_args() + + # 检查Nuitka + if not check_nuitka(): + print("请手动安装Nuitka:pip install nuitka") + return + + # 构建可执行文件 + build_executable(args.output, args.debug, args.console) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..2f5885a --- /dev/null +++ b/core/__init__.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 核心功能包 +""" \ No newline at end of file diff --git a/core/batch_manager.py b/core/batch_manager.py new file mode 100644 index 0000000..8e3554c --- /dev/null +++ b/core/batch_manager.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 批量队列管理器 +负责管理批量转换任务 +""" + +import os +import threading +import queue +from PyQt6.QtCore import QObject, pyqtSignal + +class BatchManager(QObject): + """批量队列管理器""" + + # 自定义信号 + progress_updated = pyqtSignal(int, int, str) # 进度更新信号 (当前, 总数, 文件名) + conversion_completed = pyqtSignal(int, int) # 转换完成信号 (成功数, 失败数) + + def __init__(self, converter): + """ + 初始化批量队列管理器 + + 参数: + converter: MIF转换器实例 + """ + super().__init__() + self.converter = converter + self.task_queue = queue.Queue() + self.is_running = False + self.worker_thread = None + self.success_count = 0 + self.fail_count = 0 + + def start_batch(self, files, output_dir, params, processed_image=None): + """ + 启动批量转换 + + 参数: + files (list): 文件路径列表 + output_dir (str): 输出目录 + params (dict): 转换参数 + processed_image (PIL.Image, optional): 处理后的图像,如果提供则用于所有图像文件 + """ + # 如果已经在运行,则返回 + if self.is_running: + return + + # 重置计数器 + self.success_count = 0 + self.fail_count = 0 + + # 清空队列 + while not self.task_queue.empty(): + self.task_queue.get() + + # 添加任务到队列 + for file_path in files: + output_file = os.path.join( + output_dir, + f"{os.path.splitext(os.path.basename(file_path))[0]}.mif" + ) + # 如果有处理后的图像,并且是图像文件,则标记为使用处理后的图像 + use_processed = processed_image is not None and file_path.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff')) + self.task_queue.put((file_path, output_file, params, use_processed, processed_image)) + + # 设置运行标志 + self.is_running = True + + # 创建并启动工作线程 + self.worker_thread = threading.Thread(target=self._worker) + self.worker_thread.daemon = True + self.worker_thread.start() + + def _worker(self): + """工作线程函数""" + total_tasks = self.task_queue.qsize() + current_task = 0 + + try: + while not self.task_queue.empty(): + # 获取任务 + file_path, output_file, params, use_processed, processed_image = self.task_queue.get() + current_task += 1 + + # 发出进度更新信号 + self.progress_updated.emit(current_task, total_tasks, os.path.basename(file_path)) + + try: + # 执行转换 + if use_processed and processed_image: + # 使用处理后的图像直接转换 + success = self.converter.convert_from_image(processed_image, output_file, params) + else: + # 使用文件路径转换 + success = self.converter.convert(file_path, output_file, params) + + # 更新计数器 + if success: + self.success_count += 1 + else: + self.fail_count += 1 + except Exception as e: + print(f"转换错误: {str(e)}") + self.fail_count += 1 + + # 标记任务完成 + self.task_queue.task_done() + finally: + # 设置运行标志 + self.is_running = False + + # 发出转换完成信号 + self.conversion_completed.emit(self.success_count, self.fail_count) + + def is_busy(self): + """ + 检查是否正在处理任务 + + 返回: + bool: 是否正在处理任务 + """ + return self.is_running + + def get_progress(self): + """ + 获取当前进度 + + 返回: + tuple: (当前任务数, 总任务数, 成功数, 失败数) + """ + total_tasks = self.task_queue.qsize() + self.success_count + self.fail_count + current_task = self.success_count + self.fail_count + return (current_task, total_tasks, self.success_count, self.fail_count) + + def cancel(self): + """取消所有任务""" + # 清空队列 + while not self.task_queue.empty(): + self.task_queue.get() + self.task_queue.task_done() \ No newline at end of file diff --git a/core/converter.py b/core/converter.py new file mode 100644 index 0000000..886c1d0 --- /dev/null +++ b/core/converter.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - MIF格式转换器 +负责将任意文件转换为MIF格式 +""" + +import os +import math +from datetime import datetime + +class MifConverter: + """MIF格式转换器""" + + def __init__(self): + """初始化转换器""" + pass + + def convert_from_image(self, image, output_file, params): + """ + 将PIL图像对象直接转换为MIF格式 + + 参数: + image (PIL.Image): PIL图像对象 + output_file (str): 输出文件路径 + params (dict): 转换参数 + width (int): 数据宽度 (8/16/32) + auto_depth (bool): 是否自动计算深度 + depth (int): 深度 (如果auto_depth为False) + radix (str): 数据格式 (HEX/BIN/DEC) + offset (int): 地址偏移量 + header (bool): 是否添加文件头注释 + addr_format (str): 地址格式 (standard/compact) + data_per_line (int): 每行数据数量 + + 返回: + bool: 转换是否成功 + """ + try: + # 将图像转换为字节数据 + if image.mode != 'L': + image = image.convert('L') # 转换为灰度图像 + + # 将图像转换为字节数组 + data = bytearray() + for y in range(image.height): + for x in range(image.width): + pixel = image.getpixel((x, y)) + data.append(pixel) + + # 计算深度 - 使用图像的当前尺寸(可能是标准化后的尺寸) + if params['auto_depth']: + # 如果启用了自动计算深度,根据图像的当前尺寸和数据宽度计算深度 + bytes_per_word = params['width'] // 8 + # 使用图像的实际尺寸计算深度 + depth = math.ceil((image.width * image.height) / bytes_per_word) + else: + depth = params['depth'] + + # 打开输出文件 + with open(output_file, 'w', encoding='utf-8') as f: + # 根据参数决定是否写入文件头 + if params.get('header', True): + self._write_header(f, "内存中图像", params, depth) + # 写入数据 + self._write_data(f, data, params, depth) + + return True + except Exception as e: + print(f"转换错误: {str(e)}") + return False + + def convert(self, input_file, output_file, params): + """ + 将输入文件转换为MIF格式 + + 参数: + input_file (str): 输入文件路径 + output_file (str): 输出文件路径 + params (dict): 转换参数 + width (int): 数据宽度 (8/16/32) + auto_depth (bool): 是否自动计算深度 + depth (int): 深度 (如果auto_depth为False) + radix (str): 数据格式 (HEX/BIN/DEC) + offset (int): 地址偏移量 + header (bool): 是否添加文件头注释 + addr_format (str): 地址格式 (standard/compact) + data_per_line (int): 每行数据数量 + + 返回: + bool: 转换是否成功 + """ + try: + # 读取输入文件 + with open(input_file, 'rb') as f: + data = f.read() + + # 计算深度 + if params['auto_depth']: + bytes_per_word = params['width'] // 8 + depth = math.ceil(len(data) / bytes_per_word) + else: + depth = params['depth'] + + # 打开输出文件 + with open(output_file, 'w', encoding='utf-8') as f: + # 根据参数决定是否写入文件头 + if params.get('header', True): + self._write_header(f, input_file, params, depth) + # 写入数据 + self._write_data(f, data, params, depth) + + return True + except Exception as e: + print(f"转换错误: {str(e)}") + return False + + def _write_header(self, file, input_file, params, depth): + """ + 写入MIF文件头 + + 参数: + file: 输出文件对象 + input_file: 输入文件路径 + params: 转换参数 + depth: 深度 + """ + file.write("WIDTH=%d;\n" % params['width']) + file.write("DEPTH=%d;\n" % depth) + file.write("\n") + file.write("ADDRESS_RADIX=%s;\n" % params.get('addr_radix', 'HEX')) + file.write("DATA_RADIX=%s;\n" % params['radix']) + file.write("\n") + file.write("CONTENT BEGIN\n") + + def _write_data(self, file, data, params, depth): + """写入MIF数据部分""" + bytes_per_word = params['width'] // 8 + words_per_line = params['data_per_line'] + + # 处理每个地址 + for addr in range(depth): + # 计算实际地址(加上偏移量) + actual_addr = addr + params['offset'] + + # 计算数据索引 + start_idx = addr * bytes_per_word + end_idx = start_idx + bytes_per_word + + # 如果超出数据范围,填充0 + if start_idx >= len(data): + word_data = 0 + else: + # 读取数据 + word_bytes = data[start_idx:min(end_idx, len(data))] + + # 如果数据不足,填充0 + if len(word_bytes) < bytes_per_word: + word_bytes = word_bytes + b'\x00' * (bytes_per_word - len(word_bytes)) + + # 转换为整数 + word_data = int.from_bytes(word_bytes, byteorder='little') + + # 格式化地址 + addr_radix = params.get('addr_radix', 'HEX') + + if addr_radix == 'HEX': + addr_format = "@%X" if params['addr_format'] == 'standard' else "%X:" + addr_str = addr_format % actual_addr + elif addr_radix == 'BIN': + # 计算二进制位数(根据深度和偏移量) + max_addr = depth + params['offset'] - 1 + bin_digits = len(bin(max_addr)[2:]) + if params['addr_format'] == 'standard': + addr_str = "@" + bin(actual_addr)[2:].zfill(bin_digits) + else: # compact + addr_str = bin(actual_addr)[2:].zfill(bin_digits) + ":" + else: # DEC + if params['addr_format'] == 'standard': + addr_str = "@%d" % actual_addr + else: # compact + addr_str = "%d:" % actual_addr + + # 格式化数据 + if params['radix'] == 'HEX': + # 计算十六进制位数(每4位二进制对应1位十六进制) + hex_digits = math.ceil(params['width'] / 4) + data_str = format(word_data, 'X').zfill(hex_digits) + elif params['radix'] == 'BIN': + data_str = bin(word_data)[2:].zfill(params['width']) + else: # DEC + # 对于十进制,根据位宽计算最大可能的位数 + max_dec_digits = len(str(2**params['width'] - 1)) + data_str = str(word_data).zfill(max_dec_digits) + + # 写入一行 + if (addr + 1) % words_per_line == 0 or addr == depth - 1: + file.write(f"{addr_str} {data_str};\n") + else: + file.write(f"{addr_str} {data_str},\n") + + # 写入文件尾 + file.write("END;\n") + + def estimate_output_size(self, input_file, params): + """ + 估计输出文件大小 + + 参数: + input_file (str): 输入文件路径 + params (dict): 转换参数 + + 返回: + int: 估计的输出文件大小(字节) + """ + try: + # 获取输入文件大小 + input_size = os.path.getsize(input_file) + + # 计算深度 + bytes_per_word = params['width'] // 8 + if params['auto_depth']: + depth = math.ceil(input_size / bytes_per_word) + else: + depth = params['depth'] + + # 估计每行平均长度 + if params['radix'] == 'HEX': + avg_data_len = params['width'] // 4 + elif params['radix'] == 'BIN': + avg_data_len = params['width'] + else: # DEC + avg_data_len = len(str(2 ** params['width'] - 1)) + + # 估计地址长度 + addr_radix = params.get('addr_radix', 'HEX') + if addr_radix == 'HEX': + addr_len = len(hex(depth + params['offset'])[2:]) + 2 + elif addr_radix == 'BIN': + addr_len = len(bin(depth + params['offset'])[2:]) + 2 + else: # DEC + addr_len = len(str(depth + params['offset'])) + 2 + + # 估计每行长度 + line_len = addr_len + avg_data_len + 3 # 包括空格、分隔符和换行符 + + # 估计总大小(不包含文件头) + total_size = depth * line_len + + return total_size + except Exception: + # 如果估计失败,返回一个保守的估计值 + return input_size * 5 \ No newline at end of file diff --git a/core/image_processor.py b/core/image_processor.py new file mode 100644 index 0000000..4cbbe15 --- /dev/null +++ b/core/image_processor.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 图像处理器 +负责图像的灰度化、二值化等操作 +""" + +import os +import numpy as np +from PIL import Image, ImageFilter + +class ImageProcessor: + """图像处理器""" + + def __init__(self): + """初始化图像处理器""" + # 支持的图像格式 + self.supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff'] + + def is_image_file(self, file_path): + """ + 检查文件是否为图像文件 + + 参数: + file_path (str): 文件路径 + + 返回: + bool: 是否为图像文件 + """ + _, ext = os.path.splitext(file_path.lower()) + return ext in self.supported_formats + + def grayscale(self, image, method='weighted'): + """ + 将图像转换为灰度图 + + 参数: + image (PIL.Image): 输入图像 + method (str): 灰度化方法 + 'average': 平均值法 + 'weighted': 加权平均法 + 'max': 最大值法 + + 返回: + PIL.Image: 灰度图像 + """ + # 确保图像是RGB模式 + if image.mode != 'RGB': + image = image.convert('RGB') + + # 转换为numpy数组 + img_array = np.array(image) + + # 根据方法进行灰度化 + if method == 'average': + # 平均值法: (R + G + B) / 3 + gray_array = np.mean(img_array, axis=2).astype(np.uint8) + elif method == 'weighted': + # 加权平均法: 0.299 * R + 0.587 * G + 0.114 * B + gray_array = (0.299 * img_array[:, :, 0] + + 0.587 * img_array[:, :, 1] + + 0.114 * img_array[:, :, 2]).astype(np.uint8) + elif method == 'max': + # 最大值法: max(R, G, B) + gray_array = np.max(img_array, axis=2).astype(np.uint8) + else: + # 默认使用加权平均法 + gray_array = (0.299 * img_array[:, :, 0] + + 0.587 * img_array[:, :, 1] + + 0.114 * img_array[:, :, 2]).astype(np.uint8) + + # 转换回PIL图像 + return Image.fromarray(gray_array, mode='L') + + def threshold(self, image, threshold=128, method='fixed'): + """ + 对图像进行二值化处理 + + 参数: + image (PIL.Image): 输入图像 + threshold (int): 阈值 (0-255) + method (str): 二值化方法 + 'fixed': 固定阈值 + 'adaptive': 自适应阈值 + 'otsu': Otsu阈值 + + 返回: + PIL.Image: 二值化图像 + """ + # 确保图像是灰度模式 + if image.mode != 'L': + image = image.convert('L') + + # 转换为numpy数组 + img_array = np.array(image) + + # 根据方法进行二值化 + if method == 'fixed': + # 固定阈值 + binary_array = (img_array > threshold).astype(np.uint8) * 255 + elif method == 'adaptive': + # 自适应阈值 (简化版本) + # 使用局部区域的平均值作为阈值 + kernel_size = 15 + # 创建一个平均滤波器 + kernel = np.ones((kernel_size, kernel_size)) / (kernel_size * kernel_size) + # 计算局部平均值 + local_mean = np.zeros_like(img_array, dtype=np.float32) + + # 简单的局部平均实现 + padded = np.pad(img_array, kernel_size // 2, mode='reflect') + for i in range(img_array.shape[0]): + for j in range(img_array.shape[1]): + local_mean[i, j] = np.mean(padded[i:i+kernel_size, j:j+kernel_size]) + + # 二值化 + binary_array = (img_array > local_mean - threshold // 2).astype(np.uint8) * 255 + elif method == 'otsu': + # Otsu阈值 + # 计算直方图 + hist, bins = np.histogram(img_array.flatten(), 256, [0, 256]) + + # 计算累积和 + cum_sum = hist.cumsum() + cum_sum_sq = (hist * np.arange(256)).cumsum() + + # 初始化 + max_var = 0 + otsu_threshold = 0 + + # 遍历所有可能的阈值 + for t in range(1, 256): + # 前景和背景的权重 + w_bg = cum_sum[t] + w_fg = cum_sum[-1] - w_bg + + # 如果前景或背景为空,跳过 + if w_bg == 0 or w_fg == 0: + continue + + # 前景和背景的均值 + mean_bg = cum_sum_sq[t] / w_bg + mean_fg = (cum_sum_sq[-1] - cum_sum_sq[t]) / w_fg + + # 计算类间方差 + var_between = w_bg * w_fg * (mean_bg - mean_fg) ** 2 + + # 更新最大方差和阈值 + if var_between > max_var: + max_var = var_between + otsu_threshold = t + + # 使用Otsu阈值进行二值化 + binary_array = (img_array > otsu_threshold).astype(np.uint8) * 255 + else: + # 默认使用固定阈值 + binary_array = (img_array > threshold).astype(np.uint8) * 255 + + # 转换回PIL图像 + return Image.fromarray(binary_array, mode='L') + + def denoise(self, image, method='median', strength=3): + """ + 对图像进行降噪处理 + + 参数: + image (PIL.Image): 输入图像 + method (str): 降噪方法 + 'median': 中值滤波 + 'gaussian': 高斯滤波 + 'bilateral': 双边滤波 (简化版本) + strength (int): 降噪强度 (1-10) + + 返回: + PIL.Image: 降噪后的图像 + """ + # 根据方法进行降噪 + if method == 'median': + # 中值滤波 + kernel_size = strength * 2 - 1 # 确保是奇数 + return image.filter(ImageFilter.MedianFilter(size=kernel_size)) + elif method == 'gaussian': + # 高斯滤波 + radius = strength / 2 + return image.filter(ImageFilter.GaussianBlur(radius=radius)) + elif method == 'bilateral': + # 双边滤波 (简化版本) + # 由于PIL没有内置的双边滤波,我们使用高斯滤波代替 + # 在实际应用中,可以使用OpenCV的双边滤波 + radius = strength / 2 + return image.filter(ImageFilter.GaussianBlur(radius=radius)) + else: + # 默认使用中值滤波 + kernel_size = strength * 2 - 1 # 确保是奇数 + return image.filter(ImageFilter.MedianFilter(size=kernel_size)) + + def resize(self, image, width, height, keep_aspect=True): + """ + 调整图像大小 + + 参数: + image (PIL.Image): 输入图像 + width (int): 目标宽度 + height (int): 目标高度 + keep_aspect (bool): 是否保持纵横比 + + 返回: + PIL.Image: 调整大小后的图像 + """ + if keep_aspect: + # 计算缩放比例 + width_ratio = width / image.width + height_ratio = height / image.height + ratio = min(width_ratio, height_ratio) + + # 计算新尺寸 + new_width = int(image.width * ratio) + new_height = int(image.height * ratio) + + # 调整图像大小 + resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS) + + # 创建新图像 + new_image = Image.new(image.mode, (width, height), (0, 0, 0)) + + # 计算粘贴位置 + paste_x = (width - new_width) // 2 + paste_y = (height - new_height) // 2 + + # 粘贴调整大小后的图像 + new_image.paste(resized_image, (paste_x, paste_y)) + + return new_image + else: + # 直接调整到指定大小 + return image.resize((width, height), Image.Resampling.LANCZOS) \ No newline at end of file diff --git a/create_icon.py b/create_icon.py new file mode 100644 index 0000000..b7785c5 --- /dev/null +++ b/create_icon.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 图标生成脚本 +创建一个简单的图标文件,用于打包时使用 +""" + +import os +from PIL import Image, ImageDraw, ImageFont + +def create_icon(): + """创建一个简单的图标文件""" + # 创建一个32x32像素的图像,背景为透明 + img = Image.new('RGBA', (256, 256), color=(0, 0, 0, 0)) + draw = ImageDraw.Draw(img) + + # 绘制一个圆形背景 + draw.ellipse((16, 16, 240, 240), fill=(41, 128, 185)) + + # 绘制文字 + try: + # 尝试加载系统字体 + font = ImageFont.truetype("arial.ttf", 120) + except IOError: + # 如果无法加载系统字体,使用默认字体 + font = ImageFont.load_default() + + # 绘制"A2M"文字 + draw.text((50, 70), "AM", fill=(255, 255, 255), font=font) + + # 确保resources目录存在 + if not os.path.exists("resources"): + os.makedirs("resources") + + # 保存为.ico文件 + img.save("resources/icon.ico", format="ICO", sizes=[(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]) + print(f"图标文件已创建:{os.path.abspath('resources/icon.ico')}") + +if __name__ == "__main__": + create_icon() \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..da5b117 --- /dev/null +++ b/main.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 任意文件转MIF格式转换器 +主程序入口 +""" + +import sys +import os +from PyQt6.QtWidgets import QApplication +from PyQt6.QtCore import QSettings +from ui.main_window import MainWindow + +def main(): + """主函数""" + # 创建应用程序实例 + app = QApplication(sys.argv) + app.setApplicationName("Any2MIF") + app.setOrganizationName("Any2MIF") + + # 加载设置 + settings = QSettings("Any2MIF", "Any2MIF") + + # 创建并显示主窗口 + window = MainWindow(settings) + window.show() + + # 运行应用程序事件循环 + sys.exit(app.exec()) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bb2d61e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +PyQt6>=6.0.0 +Pillow>=9.0.0 +numpy>=1.20.0 \ No newline at end of file diff --git a/resources/icon.ico b/resources/icon.ico new file mode 100644 index 0000000..36fbd22 Binary files /dev/null and b/resources/icon.ico differ diff --git a/resources/styles/dark.qss b/resources/styles/dark.qss new file mode 100644 index 0000000..476ce4c --- /dev/null +++ b/resources/styles/dark.qss @@ -0,0 +1,333 @@ +/* Any2MIF - 深色主题样式表 */ + +/* 全局样式 */ +QMainWindow, QDialog { + background-color: #2d2d2d; + color: #f0f0f0; +} + +QWidget { + background-color: #2d2d2d; + color: #f0f0f0; + font-family: "Microsoft YaHei", "Segoe UI", Arial, sans-serif; +} + +QLabel { + color: #f0f0f0; +} + +/* 按钮样式 */ +QPushButton { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + padding: 5px 10px; + color: #f0f0f0; + min-height: 25px; +} + +QPushButton:hover { + background-color: #4d4d4d; +} + +QPushButton:pressed { + background-color: #5d5d5d; +} + +QPushButton:disabled { + background-color: #3d3d3d; + color: #7d7d7d; + border: 1px solid #4d4d4d; +} + +/* 输入控件样式 */ +QLineEdit, QSpinBox, QComboBox { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + padding: 3px; + color: #f0f0f0; + selection-background-color: #5d5d5d; + selection-color: #f0f0f0; +} + +QLineEdit:focus, QSpinBox:focus, QComboBox:focus { + border: 1px solid #7d7d7d; +} + +QLineEdit:disabled, QSpinBox:disabled, QComboBox:disabled { + background-color: #2d2d2d; + color: #7d7d7d; + border: 1px solid #4d4d4d; +} + +/* 下拉框样式 */ +QComboBox { + padding-right: 20px; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: right center; + width: 20px; + border-left: 1px solid #5d5d5d; +} + +QComboBox::down-arrow { + width: 10px; + height: 10px; +} + +QComboBox QAbstractItemView { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + selection-background-color: #5d5d5d; + selection-color: #f0f0f0; +} + +/* 分组框样式 */ +QGroupBox { + border: 1px solid #5d5d5d; + border-radius: 4px; + margin-top: 10px; + padding-top: 10px; + font-weight: bold; + min-height: 50px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; + color: #f0f0f0; +} + +/* 图像预览样式 */ +QGroupBox[title="图像预览"] { + min-height: 100px; +} + +QGroupBox[title="图像预览"] QLabel { + min-height: 80px; +} + +/* 列表部件样式 */ +QListWidget { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + color: #f0f0f0; +} + +QListWidget::item { + padding: 5px; +} + +QListWidget::item:selected { + background-color: #5d5d5d; + color: #f0f0f0; +} + +QListWidget::item:hover { + background-color: #4d4d4d; +} + +/* 滑块样式 */ +QSlider::groove:horizontal { + border: 1px solid #5d5d5d; + height: 8px; + background: #3d3d3d; + margin: 2px 0; + border-radius: 4px; +} + +QSlider::handle:horizontal { + background: #5d5d5d; + border: 1px solid #7d7d7d; + width: 18px; + margin: -2px 0; + border-radius: 9px; +} + +QSlider::handle:horizontal:hover { + background: #6d6d6d; +} + +QSlider::sub-page:horizontal { + background: #6d6d6d; + border-radius: 4px; +} + +/* 复选框样式 */ +QCheckBox { + spacing: 5px; +} + +QCheckBox::indicator { + width: 15px; + height: 15px; +} + +QCheckBox::indicator:unchecked { + border: 1px solid #5d5d5d; + background-color: #3d3d3d; + border-radius: 3px; +} + +QCheckBox::indicator:checked { + border: 1px solid #5d5d5d; + background-color: #5d5d5d; + border-radius: 3px; +} + +/* 状态栏样式 */ +QStatusBar { + background-color: #3d3d3d; + color: #f0f0f0; + border-top: 1px solid #5d5d5d; +} + +/* 工具栏样式 */ +QToolBar { + background-color: #3d3d3d; + border-bottom: 1px solid #5d5d5d; + spacing: 5px; + padding: 2px; +} + +QToolBar::separator { + width: 1px; + background-color: #5d5d5d; + margin: 0 5px; +} + +/* 分割器样式 */ +QSplitter::handle { + background-color: #5d5d5d; +} + +QSplitter::handle:horizontal { + width: 1px; +} + +QSplitter::handle:vertical { + height: 1px; +} + +/* 滚动条样式 */ +QScrollBar:vertical { + border: 1px solid #5d5d5d; + background: #2d2d2d; + width: 12px; + margin: 16px 0 16px 0; + border-radius: 4px; +} + +QScrollBar::handle:vertical { + background: #5d5d5d; + min-height: 20px; + border-radius: 3px; +} + +QScrollBar::add-line:vertical { + border: 1px solid #5d5d5d; + background: #3d3d3d; + height: 15px; + subcontrol-position: bottom; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::sub-line:vertical { + border: 1px solid #5d5d5d; + background: #3d3d3d; + height: 15px; + subcontrol-position: top; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + width: 6px; + height: 6px; +} + +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; +} + +QScrollBar:horizontal { + border: 1px solid #5d5d5d; + background: #2d2d2d; + height: 12px; + margin: 0 16px 0 16px; + border-radius: 4px; +} + +QScrollBar::handle:horizontal { + background: #5d5d5d; + min-width: 20px; + border-radius: 3px; +} + +QScrollBar::add-line:horizontal { + border: 1px solid #5d5d5d; + background: #3d3d3d; + width: 15px; + subcontrol-position: right; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::sub-line:horizontal { + border: 1px solid #5d5d5d; + background: #3d3d3d; + width: 15px; + subcontrol-position: left; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal { + width: 6px; + height: 6px; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} + +/* 菜单样式 */ +QMenu { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + color: #f0f0f0; +} + +QMenu::item { + padding: 5px 30px 5px 20px; +} + +QMenu::item:selected { + background-color: #5d5d5d; + color: #f0f0f0; +} + +QMenu::separator { + height: 1px; + background-color: #5d5d5d; + margin: 5px 0; +} + +/* 消息框样式 */ +QMessageBox { + background-color: #2d2d2d; +} + +QMessageBox QLabel { + color: #f0f0f0; +} + +QMessageBox QPushButton { + min-width: 80px; +} \ No newline at end of file diff --git a/resources/styles/light.qss b/resources/styles/light.qss new file mode 100644 index 0000000..e156c27 --- /dev/null +++ b/resources/styles/light.qss @@ -0,0 +1,333 @@ +/* Any2MIF - 浅色主题样式表 */ + +/* 全局样式 */ +QMainWindow, QDialog { + background-color: #f5f5f5; + color: #333333; +} + +QWidget { + background-color: #f5f5f5; + color: #333333; + font-family: "Microsoft YaHei", "Segoe UI", Arial, sans-serif; +} + +QLabel { + color: #333333; +} + +/* 按钮样式 */ +QPushButton { + background-color: #e0e0e0; + border: 1px solid #b0b0b0; + border-radius: 4px; + padding: 5px 10px; + color: #333333; + min-height: 25px; +} + +QPushButton:hover { + background-color: #d0d0d0; +} + +QPushButton:pressed { + background-color: #c0c0c0; +} + +QPushButton:disabled { + background-color: #f0f0f0; + color: #a0a0a0; + border: 1px solid #d0d0d0; +} + +/* 输入控件样式 */ +QLineEdit, QSpinBox, QComboBox { + background-color: #ffffff; + border: 1px solid #b0b0b0; + border-radius: 4px; + padding: 3px; + color: #333333; + selection-background-color: #b0b0b0; + selection-color: #333333; +} + +QLineEdit:focus, QSpinBox:focus, QComboBox:focus { + border: 1px solid #808080; +} + +QLineEdit:disabled, QSpinBox:disabled, QComboBox:disabled { + background-color: #f0f0f0; + color: #a0a0a0; + border: 1px solid #d0d0d0; +} + +/* 下拉框样式 */ +QComboBox { + padding-right: 20px; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: right center; + width: 20px; + border-left: 1px solid #b0b0b0; +} + +QComboBox::down-arrow { + width: 10px; + height: 10px; +} + +QComboBox QAbstractItemView { + background-color: #ffffff; + border: 1px solid #b0b0b0; + selection-background-color: #e0e0e0; + selection-color: #333333; +} + +/* 分组框样式 */ +QGroupBox { + border: 1px solid #b0b0b0; + border-radius: 4px; + margin-top: 10px; + padding-top: 10px; + font-weight: bold; + min-height: 50px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; + color: #333333; +} + +/* 图像预览样式 */ +QGroupBox[title="图像预览"] { + min-height: 100px; +} + +QGroupBox[title="图像预览"] QLabel { + min-height: 80px; +} + +/* 列表部件样式 */ +QListWidget { + background-color: #ffffff; + border: 1px solid #b0b0b0; + border-radius: 4px; + color: #333333; +} + +QListWidget::item { + padding: 5px; +} + +QListWidget::item:selected { + background-color: #e0e0e0; + color: #333333; +} + +QListWidget::item:hover { + background-color: #f0f0f0; +} + +/* 滑块样式 */ +QSlider::groove:horizontal { + border: 1px solid #b0b0b0; + height: 8px; + background: #ffffff; + margin: 2px 0; + border-radius: 4px; +} + +QSlider::handle:horizontal { + background: #e0e0e0; + border: 1px solid #b0b0b0; + width: 18px; + margin: -2px 0; + border-radius: 9px; +} + +QSlider::handle:horizontal:hover { + background: #d0d0d0; +} + +QSlider::sub-page:horizontal { + background: #c0c0c0; + border-radius: 4px; +} + +/* 复选框样式 */ +QCheckBox { + spacing: 5px; +} + +QCheckBox::indicator { + width: 15px; + height: 15px; +} + +QCheckBox::indicator:unchecked { + border: 1px solid #b0b0b0; + background-color: #ffffff; + border-radius: 3px; +} + +QCheckBox::indicator:checked { + border: 1px solid #b0b0b0; + background-color: #e0e0e0; + border-radius: 3px; +} + +/* 状态栏样式 */ +QStatusBar { + background-color: #e0e0e0; + color: #333333; + border-top: 1px solid #b0b0b0; +} + +/* 工具栏样式 */ +QToolBar { + background-color: #e0e0e0; + border-bottom: 1px solid #b0b0b0; + spacing: 5px; + padding: 2px; +} + +QToolBar::separator { + width: 1px; + background-color: #b0b0b0; + margin: 0 5px; +} + +/* 分割器样式 */ +QSplitter::handle { + background-color: #b0b0b0; +} + +QSplitter::handle:horizontal { + width: 1px; +} + +QSplitter::handle:vertical { + height: 1px; +} + +/* 滚动条样式 */ +QScrollBar:vertical { + border: 1px solid #b0b0b0; + background: #f5f5f5; + width: 12px; + margin: 16px 0 16px 0; + border-radius: 4px; +} + +QScrollBar::handle:vertical { + background: #c0c0c0; + min-height: 20px; + border-radius: 3px; +} + +QScrollBar::add-line:vertical { + border: 1px solid #b0b0b0; + background: #e0e0e0; + height: 15px; + subcontrol-position: bottom; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::sub-line:vertical { + border: 1px solid #b0b0b0; + background: #e0e0e0; + height: 15px; + subcontrol-position: top; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + width: 6px; + height: 6px; +} + +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; +} + +QScrollBar:horizontal { + border: 1px solid #b0b0b0; + background: #f5f5f5; + height: 12px; + margin: 0 16px 0 16px; + border-radius: 4px; +} + +QScrollBar::handle:horizontal { + background: #c0c0c0; + min-width: 20px; + border-radius: 3px; +} + +QScrollBar::add-line:horizontal { + border: 1px solid #b0b0b0; + background: #e0e0e0; + width: 15px; + subcontrol-position: right; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::sub-line:horizontal { + border: 1px solid #b0b0b0; + background: #e0e0e0; + width: 15px; + subcontrol-position: left; + subcontrol-origin: margin; + border-radius: 3px; +} + +QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal { + width: 6px; + height: 6px; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} + +/* 菜单样式 */ +QMenu { + background-color: #ffffff; + border: 1px solid #b0b0b0; + color: #333333; +} + +QMenu::item { + padding: 5px 30px 5px 20px; +} + +QMenu::item:selected { + background-color: #e0e0e0; + color: #333333; +} + +QMenu::separator { + height: 1px; + background-color: #b0b0b0; + margin: 5px 0; +} + +/* 消息框样式 */ +QMessageBox { + background-color: #f5f5f5; +} + +QMessageBox QLabel { + color: #333333; +} + +QMessageBox QPushButton { + min-width: 80px; +} \ No newline at end of file diff --git a/ui/__init__.py b/ui/__init__.py new file mode 100644 index 0000000..f84db34 --- /dev/null +++ b/ui/__init__.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - UI包 +""" \ No newline at end of file diff --git a/ui/file_selector.py b/ui/file_selector.py new file mode 100644 index 0000000..0ec2276 --- /dev/null +++ b/ui/file_selector.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 文件选择模块 +负责文件的选择和管理 +""" + +import os +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QPushButton, + QListWidget, QListWidgetItem, QFileDialog, QLabel, + QMenu, QAbstractItemView +) +from PyQt6.QtCore import Qt, QSettings, pyqtSignal +from PyQt6.QtGui import QIcon, QDragEnterEvent, QDropEvent + +class FileSelector(QWidget): + """文件选择器组件""" + + # 自定义信号 + file_selected = pyqtSignal(str) # 文件被选择时发出的信号 + convert_clicked = pyqtSignal() # 转换按钮被点击时发出的信号 + batch_convert_clicked = pyqtSignal() # 批量转换按钮被点击时发出的信号 + + def __init__(self, settings: QSettings, parent=None): + """初始化文件选择器""" + super().__init__(parent) + self.settings = settings + self.recent_files = self.settings.value("recent_files", []) + if not isinstance(self.recent_files, list): + self.recent_files = [] + + self._init_ui() + self._load_recent_files() + + def _init_ui(self): + """初始化UI""" + # 设置接受拖放 + self.setAcceptDrops(True) + + # 创建主布局 + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + + # 创建标题标签 + title_label = QLabel("文件选择") + title_label.setStyleSheet("font-weight: bold; font-size: 14px;") + layout.addWidget(title_label) + + # 创建文件列表 + self.file_list = QListWidget() + self.file_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.file_list.itemDoubleClicked.connect(self._on_item_double_clicked) + self.file_list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.file_list.customContextMenuRequested.connect(self._show_context_menu) + layout.addWidget(self.file_list) + + # 创建按钮容器 + button_container = QWidget() + button_container_layout = QVBoxLayout(button_container) + button_container_layout.setContentsMargins(0, 0, 0, 0) + button_container_layout.setSpacing(5) + layout.addWidget(button_container) + + # 创建上方按钮布局 + top_button_layout = QHBoxLayout() + top_button_layout.setContentsMargins(0, 0, 0, 0) + button_container_layout.addLayout(top_button_layout) + + # 添加文件按钮 + self.add_file_button = QPushButton("添加文件") + self.add_file_button.clicked.connect(self._add_files) + top_button_layout.addWidget(self.add_file_button) + + # 添加文件夹按钮 + self.add_folder_button = QPushButton("添加文件夹") + self.add_folder_button.clicked.connect(self._add_folder) + top_button_layout.addWidget(self.add_folder_button) + + # 清除按钮 + self.clear_button = QPushButton("清除") + self.clear_button.clicked.connect(self._clear_files) + top_button_layout.addWidget(self.clear_button) + + # 创建下方按钮布局(转换和批量转换按钮) + bottom_button_layout = QHBoxLayout() + bottom_button_layout.setContentsMargins(0, 0, 0, 0) + button_container_layout.addLayout(bottom_button_layout) + + # 转换按钮 + self.convert_button = QPushButton("转换") + self.convert_button.clicked.connect(self._on_convert_clicked) + bottom_button_layout.addWidget(self.convert_button) + + # 批量转换按钮 + self.batch_convert_button = QPushButton("批量转换") + self.batch_convert_button.clicked.connect(self._on_batch_convert_clicked) + bottom_button_layout.addWidget(self.batch_convert_button) + + # 确保两行按钮的总宽度相同 + # 为上面三个按钮设置相同的最小宽度 + min_width = 80 + self.add_file_button.setMinimumWidth(min_width) + self.add_folder_button.setMinimumWidth(min_width) + self.clear_button.setMinimumWidth(min_width) + + # 为下面两个按钮设置宽度,使它们的总宽度与上面三个按钮相同 + convert_width = (min_width * 3) // 2 + self.convert_button.setMinimumWidth(convert_width) + self.batch_convert_button.setMinimumWidth(convert_width) + + def _load_recent_files(self): + """加载最近使用的文件""" + for file_path in self.recent_files: + if os.path.exists(file_path): + self._add_file_to_list(file_path) + + def _add_file_to_list(self, file_path): + """将文件添加到列表中""" + # 检查文件是否已经在列表中 + for i in range(self.file_list.count()): + if self.file_list.item(i).data(Qt.ItemDataRole.UserRole) == file_path: + return + + # 创建列表项 + item = QListWidgetItem(os.path.basename(file_path)) + item.setData(Qt.ItemDataRole.UserRole, file_path) + item.setToolTip(file_path) + + # 添加到列表 + self.file_list.addItem(item) + + # 更新最近文件列表 + if file_path in self.recent_files: + self.recent_files.remove(file_path) + self.recent_files.insert(0, file_path) + # 限制最近文件数量 + self.recent_files = self.recent_files[:10] + self.settings.setValue("recent_files", self.recent_files) + + def _add_files(self): + """添加文件""" + files, _ = QFileDialog.getOpenFileNames( + self, + "选择文件", + os.path.expanduser("~"), + "所有文件 (*.*)" + ) + + if files: + for file_path in files: + self._add_file_to_list(file_path) + + # 发出信号 + if len(files) == 1: + self.file_selected.emit(files[0]) + + def _add_folder(self): + """添加文件夹中的所有文件""" + folder = QFileDialog.getExistingDirectory( + self, + "选择文件夹", + os.path.expanduser("~") + ) + + if folder: + files_added = 0 + for root, _, files in os.walk(folder): + for file in files: + file_path = os.path.join(root, file) + self._add_file_to_list(file_path) + files_added += 1 + + if files_added == 1: + self.file_selected.emit(self.file_list.item(self.file_list.count() - 1).data(Qt.ItemDataRole.UserRole)) + + def _clear_files(self): + """清除文件列表""" + self.file_list.clear() + # 清除最近文件列表 + self.recent_files = [] + # 更新设置 + self.settings.setValue("recent_files", self.recent_files) + + def _on_item_double_clicked(self, item): + """处理项目双击事件""" + file_path = item.data(Qt.ItemDataRole.UserRole) + self.file_selected.emit(file_path) + + def _show_context_menu(self, position): + """显示上下文菜单""" + menu = QMenu() + + # 添加菜单项 + remove_action = menu.addAction("移除") + remove_action.triggered.connect(self._remove_selected_files) + + # 显示菜单 + menu.exec(self.file_list.mapToGlobal(position)) + + def _remove_selected_files(self): + """移除选定的文件""" + for item in self.file_list.selectedItems(): + self.file_list.takeItem(self.file_list.row(item)) + + def get_selected_files(self): + """获取选定的文件列表""" + files = [] + + # 如果有选定的项目,返回选定的文件 + if self.file_list.selectedItems(): + for item in self.file_list.selectedItems(): + files.append(item.data(Qt.ItemDataRole.UserRole)) + # 否则返回所有文件 + else: + for i in range(self.file_list.count()): + files.append(self.file_list.item(i).data(Qt.ItemDataRole.UserRole)) + + return files + + def dragEnterEvent(self, event: QDragEnterEvent): + """处理拖动进入事件""" + if event.mimeData().hasUrls(): + event.acceptProposedAction() + + def dropEvent(self, event: QDropEvent): + """处理放置事件""" + urls = event.mimeData().urls() + + for url in urls: + path = url.toLocalFile() + + if os.path.isfile(path): + self._add_file_to_list(path) + elif os.path.isdir(path): + for root, _, files in os.walk(path): + for file in files: + file_path = os.path.join(root, file) + self._add_file_to_list(file_path) + + # 如果只添加了一个文件,发出信号 + if len(urls) == 1 and os.path.isfile(urls[0].toLocalFile()): + self.file_selected.emit(urls[0].toLocalFile()) + + def _on_convert_clicked(self): + """处理转换按钮点击事件""" + self.convert_clicked.emit() + + def _on_batch_convert_clicked(self): + """处理批量转换按钮点击事件""" + self.batch_convert_clicked.emit() \ No newline at end of file diff --git a/ui/image_toolbar.py b/ui/image_toolbar.py new file mode 100644 index 0000000..a46e8ba --- /dev/null +++ b/ui/image_toolbar.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 图像处理工具栏 +负责图像的灰度化、二值化等操作 +""" + +import os +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, + QPushButton, QSlider, QGroupBox, QToolButton, + QSpinBox, QComboBox, QCheckBox, QFileDialog +) +from PyQt6.QtCore import Qt, QSettings, pyqtSignal, QTimer +from PyQt6.QtGui import QPixmap, QImage +from PIL import Image, ImageQt + +from core.image_processor import ImageProcessor + +class ImageToolbar(QWidget): + """图像处理工具栏""" + + def __init__(self, image_processor: ImageProcessor, settings: QSettings, preview_label=None, parent=None): + """初始化图像处理工具栏""" + super().__init__(parent) + self.image_processor = image_processor + self.settings = settings + self.preview_label = preview_label # 外部传入的预览标签 + self.original_image = None + self.processed_image = None + self._last_size = None # 初始化上一次窗口大小 + self._fixed_preview_height = None # 固定的预览高度 + + self._init_ui() + self._load_settings() + self._connect_signals() + + # 默认禁用工具栏 + self.setEnabled(False) + + def _init_ui(self): + """初始化UI""" + # 创建主布局 + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + + # 创建标题标签 + title_label = QLabel("图像处理") + title_label.setStyleSheet("font-weight: bold; font-size: 14px;") + layout.addWidget(title_label) + + # 创建2x2网格布局来放置四个功能区 + grid_layout = QHBoxLayout() + layout.addLayout(grid_layout) + + # 创建左侧和右侧的垂直布局 + left_column = QVBoxLayout() + right_column = QVBoxLayout() + grid_layout.addLayout(left_column) + grid_layout.addLayout(right_column) + + # 创建灰度化组 (左上) + grayscale_group = QGroupBox("灰度化") + grayscale_layout = QVBoxLayout(grayscale_group) + left_column.addWidget(grayscale_group) + + # 灰度化方法选择 + self.grayscale_method_combo = QComboBox() + self.grayscale_method_combo.addItems(["平均值法", "加权平均法", "最大值法"]) + grayscale_layout.addWidget(self.grayscale_method_combo) + + # 灰度化按钮 + self.grayscale_button = QPushButton("应用灰度化") + grayscale_layout.addWidget(self.grayscale_button) + + # 创建二值化组 (右上) + threshold_group = QGroupBox("二值化") + threshold_layout = QVBoxLayout(threshold_group) + right_column.addWidget(threshold_group) + + # 阈值滑块 + threshold_layout_h = QHBoxLayout() + threshold_layout.addLayout(threshold_layout_h) + + threshold_layout_h.addWidget(QLabel("阈值:")) + self.threshold_slider = QSlider(Qt.Orientation.Horizontal) + self.threshold_slider.setRange(0, 255) + self.threshold_slider.setValue(128) + threshold_layout_h.addWidget(self.threshold_slider) + + self.threshold_value_label = QLabel("128") + threshold_layout_h.addWidget(self.threshold_value_label) + + # 二值化方法选择 + self.threshold_method_combo = QComboBox() + self.threshold_method_combo.addItems(["固定阈值", "自适应阈值", "Otsu阈值"]) + threshold_layout.addWidget(self.threshold_method_combo) + + # 二值化按钮 + self.threshold_button = QPushButton("应用二值化") + threshold_layout.addWidget(self.threshold_button) + + # 创建降噪组 (左下) + denoise_group = QGroupBox("降噪处理") + denoise_layout = QVBoxLayout(denoise_group) + left_column.addWidget(denoise_group) + + # 降噪方法选择 + self.denoise_method_combo = QComboBox() + self.denoise_method_combo.addItems(["中值滤波", "高斯滤波", "双边滤波"]) + denoise_layout.addWidget(self.denoise_method_combo) + + # 降噪强度 + denoise_strength_layout = QHBoxLayout() + denoise_layout.addLayout(denoise_strength_layout) + + denoise_strength_layout.addWidget(QLabel("强度:")) + self.denoise_strength_slider = QSlider(Qt.Orientation.Horizontal) + self.denoise_strength_slider.setRange(1, 10) + self.denoise_strength_slider.setValue(3) + denoise_strength_layout.addWidget(self.denoise_strength_slider) + + self.denoise_strength_label = QLabel("3") + denoise_strength_layout.addWidget(self.denoise_strength_label) + + # 降噪按钮 + self.denoise_button = QPushButton("应用降噪") + denoise_layout.addWidget(self.denoise_button) + + # 创建尺寸标准化组 (右下) + resize_group = QGroupBox("尺寸标准化") + resize_layout = QVBoxLayout(resize_group) + right_column.addWidget(resize_group) + + # 尺寸设置 + size_layout = QHBoxLayout() + resize_layout.addLayout(size_layout) + + size_layout.addWidget(QLabel("宽度:")) + self.width_spin = QSpinBox() + self.width_spin.setRange(1, 1000) + self.width_spin.setValue(128) + size_layout.addWidget(self.width_spin) + + size_layout.addWidget(QLabel("高度:")) + self.height_spin = QSpinBox() + self.height_spin.setRange(1, 1000) + self.height_spin.setValue(128) + size_layout.addWidget(self.height_spin) + + # 保持纵横比 + self.keep_aspect_check = QCheckBox("保持纵横比") + self.keep_aspect_check.setChecked(True) + resize_layout.addWidget(self.keep_aspect_check) + + # 调整尺寸按钮 + self.resize_button = QPushButton("应用尺寸调整") + resize_layout.addWidget(self.resize_button) + + # 创建操作按钮布局 + button_layout = QHBoxLayout() + layout.addLayout(button_layout) + + # 重置按钮 + self.reset_button = QPushButton("重置图像") + button_layout.addWidget(self.reset_button) + + # 保存按钮 + self.save_button = QPushButton("保存图像") + button_layout.addWidget(self.save_button) + + def _load_settings(self): + """加载设置""" + # 加载灰度化方法 + grayscale_method_index = self.settings.value("image/grayscale_method_index", 0, int) + self.grayscale_method_combo.setCurrentIndex(grayscale_method_index) + + # 加载二值化设置 + threshold = self.settings.value("image/threshold", 128, int) + self.threshold_slider.setValue(threshold) + self.threshold_value_label.setText(str(threshold)) + + threshold_method_index = self.settings.value("image/threshold_method_index", 0, int) + self.threshold_method_combo.setCurrentIndex(threshold_method_index) + + # 加载降噪设置 + denoise_method_index = self.settings.value("image/denoise_method_index", 0, int) + self.denoise_method_combo.setCurrentIndex(denoise_method_index) + + denoise_strength = self.settings.value("image/denoise_strength", 3, int) + self.denoise_strength_slider.setValue(denoise_strength) + self.denoise_strength_label.setText(str(denoise_strength)) + + # 加载尺寸设置 + width = self.settings.value("image/width", 128, int) + self.width_spin.setValue(width) + + height = self.settings.value("image/height", 128, int) + self.height_spin.setValue(height) + + keep_aspect = self.settings.value("image/keep_aspect", True, bool) + self.keep_aspect_check.setChecked(keep_aspect) + + def _connect_signals(self): + """连接信号和槽""" + # 灰度化 + self.grayscale_button.clicked.connect(self._apply_grayscale) + self.grayscale_method_combo.currentIndexChanged.connect(self._save_settings) + + # 二值化 + self.threshold_slider.valueChanged.connect(self._on_threshold_changed) + self.threshold_button.clicked.connect(self._apply_threshold) + self.threshold_method_combo.currentIndexChanged.connect(self._save_settings) + + # 降噪 + self.denoise_strength_slider.valueChanged.connect(self._on_denoise_strength_changed) + self.denoise_button.clicked.connect(self._apply_denoise) + self.denoise_method_combo.currentIndexChanged.connect(self._save_settings) + + # 尺寸调整 + self.resize_button.clicked.connect(self._apply_resize) + self.width_spin.valueChanged.connect(self._save_settings) + self.height_spin.valueChanged.connect(self._save_settings) + self.keep_aspect_check.toggled.connect(self._save_settings) + + # 操作按钮 + self.reset_button.clicked.connect(self._reset_image) + self.save_button.clicked.connect(self._save_image) + + def _on_threshold_changed(self, value): + """处理阈值变化事件""" + self.threshold_value_label.setText(str(value)) + self._save_settings() + + def _on_denoise_strength_changed(self, value): + """处理降噪强度变化事件""" + self.denoise_strength_label.setText(str(value)) + self._save_settings() + + def _save_settings(self): + """保存设置""" + # 保存灰度化设置 + self.settings.setValue("image/grayscale_method_index", self.grayscale_method_combo.currentIndex()) + + # 保存二值化设置 + self.settings.setValue("image/threshold", self.threshold_slider.value()) + self.settings.setValue("image/threshold_method_index", self.threshold_method_combo.currentIndex()) + + # 保存降噪设置 + self.settings.setValue("image/denoise_method_index", self.denoise_method_combo.currentIndex()) + self.settings.setValue("image/denoise_strength", self.denoise_strength_slider.value()) + + # 保存尺寸设置 + self.settings.setValue("image/width", self.width_spin.value()) + self.settings.setValue("image/height", self.height_spin.value()) + self.settings.setValue("image/keep_aspect", self.keep_aspect_check.isChecked()) + + def load_image(self, image_path): + """加载图像""" + if not os.path.exists(image_path): + return + + # 加载原始图像 + self.original_image = Image.open(image_path) + self.processed_image = self.original_image.copy() + + # 如果是首次加载图像,设置固定的预览高度 + if self._fixed_preview_height is None and self.preview_label is not None: + self._fixed_preview_height = self.preview_label.height() + # 设置预览标签的固定高度 + self.preview_label.setFixedHeight(self._fixed_preview_height) + + # 更新预览 + self._update_preview() + + def _update_preview(self): + """更新预览""" + if self.processed_image is None or self.preview_label is None: + return + + # 调整图像大小以适应预览区域 + preview_width = self.preview_label.width() + + # 使用固定的预览高度,如果没有设置则使用当前高度 + preview_height = self._fixed_preview_height if self._fixed_preview_height is not None else self.preview_label.height() + + # 确保预览区域有有效尺寸 + if preview_width <= 10 or preview_height <= 10: + return + + # 计算缩放比例 - 使用宽度比例,但保持图片纵横比 + width_ratio = preview_width / self.processed_image.width + height_ratio = preview_height / self.processed_image.height + + # 使用较小的比例以确保图片完全适应预览区域,同时保持纵横比 + ratio = min(width_ratio, height_ratio) + + # 计算新尺寸 - 保持纵横比 + new_width = max(int(self.processed_image.width * ratio), 1) + new_height = max(int(self.processed_image.height * ratio), 1) + + # 调整图像大小 + preview_image = self.processed_image.resize((new_width, new_height), Image.Resampling.LANCZOS) + + # 转换为QPixmap并显示 + q_image = ImageQt.ImageQt(preview_image) + pixmap = QPixmap.fromImage(q_image) + self.preview_label.setPixmap(pixmap) + + # 确保预览标签的大小策略正确 + self.preview_label.setScaledContents(False) # 不自动缩放内容 + + def _apply_grayscale(self): + """应用灰度化""" + if self.processed_image is None: + return + + # 获取灰度化方法 + method_index = self.grayscale_method_combo.currentIndex() + method_map = {0: "average", 1: "weighted", 2: "max"} + method = method_map[method_index] + + # 应用灰度化 + self.processed_image = self.image_processor.grayscale(self.processed_image, method) + + # 更新预览 + self._update_preview() + + def _apply_threshold(self): + """应用二值化""" + if self.processed_image is None: + return + + # 获取二值化参数 + threshold = self.threshold_slider.value() + method_index = self.threshold_method_combo.currentIndex() + method_map = {0: "fixed", 1: "adaptive", 2: "otsu"} + method = method_map[method_index] + + # 应用二值化 + self.processed_image = self.image_processor.threshold(self.processed_image, threshold, method) + + # 更新预览 + self._update_preview() + + def _apply_denoise(self): + """应用降噪""" + if self.processed_image is None: + return + + # 获取降噪参数 + method_index = self.denoise_method_combo.currentIndex() + method_map = {0: "median", 1: "gaussian", 2: "bilateral"} + method = method_map[method_index] + + strength = self.denoise_strength_slider.value() + + # 应用降噪 + self.processed_image = self.image_processor.denoise(self.processed_image, method, strength) + + # 更新预览 + self._update_preview() + + def _apply_resize(self): + """应用尺寸调整""" + if self.processed_image is None: + return + + # 获取尺寸参数 + width = self.width_spin.value() + height = self.height_spin.value() + keep_aspect = self.keep_aspect_check.isChecked() + + # 应用尺寸调整 + self.processed_image = self.image_processor.resize(self.processed_image, width, height, keep_aspect) + + # 更新预览 + self._update_preview() + + def _reset_image(self): + """重置图像""" + if self.original_image is None: + return + + # 重置为原始图像 + self.processed_image = self.original_image.copy() + + # 更新预览 + self._update_preview() + + def _save_image(self): + """保存图像""" + if self.processed_image is None: + return + + # 获取保存路径 + file_path, _ = QFileDialog.getSaveFileName( + self, + "保存图像", + os.path.expanduser("~"), + "图像文件 (*.png *.jpg *.bmp)" + ) + + if file_path: + # 保存图像 + self.processed_image.save(file_path) + + def get_processed_image(self): + """获取处理后的图像""" + return self.processed_image + + + def resizeEvent(self, event): + """处理大小调整事件""" + # 获取当前窗口大小 + current_size = event.size() + + # 调用父类的resizeEvent + super().resizeEvent(event) + + # 如果已经设置了固定预览高度,确保预览标签保持该高度 + if self.preview_label is not None and self._fixed_preview_height is not None: + self.preview_label.setFixedHeight(self._fixed_preview_height) + + # 更新上一次窗口大小 + self._last_size = current_size + + # 使用QTimer延迟更新预览,确保布局已完全调整 + QTimer.singleShot(0, self._update_preview) \ No newline at end of file diff --git a/ui/main_window.py b/ui/main_window.py new file mode 100644 index 0000000..f33e64d --- /dev/null +++ b/ui/main_window.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 主窗口类 +包含应用程序的主界面和核心功能组织 +""" + +import os +import sys +from PyQt6.QtWidgets import ( + QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, + QSplitter, QStatusBar, QToolBar, QMessageBox, + QFileDialog, QGroupBox, QLabel +) +from PyQt6.QtCore import Qt, QSettings, QSize, QTimer +from PyQt6.QtGui import QIcon, QAction + +from ui.file_selector import FileSelector +from ui.param_panel import ParamPanel +from ui.image_toolbar import ImageToolbar +from ui.theme_controller import ThemeController +from core.converter import MifConverter +from core.batch_manager import BatchManager +from core.image_processor import ImageProcessor + +class MainWindow(QMainWindow): + """主窗口类""" + + def __init__(self, settings: QSettings, parent=None): + """初始化主窗口""" + super().__init__(parent) + self.settings = settings + self.converter = MifConverter() + self.batch_manager = BatchManager(self.converter) + self.image_processor = ImageProcessor() + + self._init_ui() + self._load_settings() + self._connect_signals() + + def _init_ui(self): + """初始化UI""" + # 设置窗口属性 + self.setWindowTitle("Any2MIF - 文件转换器") + self.setMinimumSize(900, 600) + + # 创建中央部件 + central_widget = QWidget() + self.setCentralWidget(central_widget) + + # 创建主布局 + main_layout = QVBoxLayout(central_widget) + main_layout.setContentsMargins(10, 10, 10, 10) + main_layout.setSpacing(10) + + # 创建左侧面板 + left_panel = QWidget() + left_layout = QVBoxLayout(left_panel) + left_layout.setContentsMargins(0, 0, 0, 0) + left_layout.setSpacing(10) + + # 创建文件选择器 + self.file_selector = FileSelector(self.settings) + left_layout.addWidget(self.file_selector) + + # 创建图像预览标签 + preview_group = QGroupBox("图像预览") + preview_layout = QVBoxLayout(preview_group) + self.preview_label = QLabel() + self.preview_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + # 设置固定高度而不是最小高度,确保在整个应用程序运行期间保持一致 + self.preview_label.setFixedHeight(200) + self.preview_label.setStyleSheet("background-color: #333333; border: 1px solid #5d5d5d;") + preview_layout.addWidget(self.preview_label) + left_layout.addWidget(preview_group) + + # 创建右侧面板 + right_panel = QWidget() + right_layout = QVBoxLayout(right_panel) + right_layout.setContentsMargins(0, 0, 0, 0) + right_layout.setSpacing(10) + + # 创建参数配置面板 + self.param_panel = ParamPanel(self.settings) + right_layout.addWidget(self.param_panel) + + # 创建图像处理工具栏 + self.image_toolbar = ImageToolbar(self.image_processor, self.settings, self.preview_label) + right_layout.addWidget(self.image_toolbar) + + # 创建分割器 + splitter = QSplitter(Qt.Orientation.Horizontal) + splitter.addWidget(left_panel) + splitter.addWidget(right_panel) + main_layout.addWidget(splitter) + + # 设置分割器比例 + splitter.setSizes([int(self.width() * 0.4), int(self.width() * 0.6)]) + + # 创建状态栏 + self.status_bar = QStatusBar() + self.setStatusBar(self.status_bar) + self.status_bar.showMessage("就绪") + + # 创建主题控制器(不显示在界面上) + self.theme_controller = ThemeController(self.settings) + + def _load_settings(self): + """加载设置""" + # 恢复窗口几何形状 + geometry = self.settings.value("geometry") + if geometry: + self.restoreGeometry(geometry) + + # 应用主题(锁定为深色模式) + self.theme_controller.apply_theme("dark") + + def _connect_signals(self): + """连接信号和槽""" + # 文件选择器信号 + self.file_selector.file_selected.connect(self.on_file_selected) + self.file_selector.convert_clicked.connect(self.convert_files) + self.file_selector.batch_convert_clicked.connect(self.batch_convert) + + # 主题控制器信号 + self.theme_controller.theme_changed.connect(self.on_theme_changed) + + # 批量管理器信号 + self.batch_manager.progress_updated.connect(self.update_progress) + self.batch_manager.conversion_completed.connect(self.on_conversion_completed) + + def on_file_selected(self, file_path): + """处理文件选择事件""" + self.status_bar.showMessage(f"已选择文件: {os.path.basename(file_path)}") + + # 如果是图像文件,启用图像处理工具栏 + if self.image_processor.is_image_file(file_path): + self.image_toolbar.setEnabled(True) + self.image_toolbar.load_image(file_path) + # 确保预览标签显示图像 + self.preview_label.setVisible(True) + else: + self.image_toolbar.setEnabled(False) + # 隐藏预览标签 + self.preview_label.setVisible(False) + + def on_theme_changed(self, theme): + """处理主题变更事件""" + self.settings.setValue("theme", theme) + + def update_progress(self, current, total, file_name): + """更新进度信息""" + self.status_bar.showMessage(f"正在转换 {file_name}... ({current}/{total})") + + def on_conversion_completed(self, success_count, fail_count): + """处理转换完成事件""" + self.status_bar.showMessage(f"转换完成。成功: {success_count}, 失败: {fail_count}") + + if success_count > 0: + QMessageBox.information( + self, + "转换完成", + f"已成功转换 {success_count} 个文件" + + (f",{fail_count} 个文件失败" if fail_count > 0 else "") + ) + elif fail_count > 0: + QMessageBox.warning( + self, + "转换失败", + f"所有 {fail_count} 个文件转换失败" + ) + + def convert_files(self): + """转换选定的文件""" + files = self.file_selector.get_selected_files() + if not files: + QMessageBox.warning(self, "警告", "请先选择要转换的文件") + return + + # 获取输出目录 + output_dir = QFileDialog.getExistingDirectory( + self, "选择输出目录", os.path.expanduser("~") + ) + if not output_dir: + return + + # 获取转换参数 + params = self.param_panel.get_params() + + # 执行转换 + for file_path in files: + try: + # 如果是图像文件且图像处理工具栏已启用,先处理图像 + if self.image_processor.is_image_file(file_path) and self.image_toolbar.isEnabled(): + processed_image = self.image_toolbar.get_processed_image() + if processed_image: + # 直接使用处理后的图像进行转换,而不是保存为临时文件 + output_file = os.path.join( + output_dir, + f"{os.path.splitext(os.path.basename(file_path))[0]}.mif" + ) + self.converter.convert_from_image(processed_image, output_file, params) + else: + # 如果没有处理后的图像,使用原始文件 + output_file = os.path.join( + output_dir, + f"{os.path.splitext(os.path.basename(file_path))[0]}.mif" + ) + self.converter.convert(file_path, output_file, params) + else: + # 非图像文件或图像处理工具栏未启用,直接转换 + output_file = os.path.join( + output_dir, + f"{os.path.splitext(os.path.basename(file_path))[0]}.mif" + ) + self.converter.convert(file_path, output_file, params) + + self.status_bar.showMessage(f"已转换: {os.path.basename(file_path)}") + except Exception as e: + QMessageBox.critical(self, "转换错误", f"转换文件 {os.path.basename(file_path)} 时出错: {str(e)}") + + QMessageBox.information(self, "转换完成", "文件转换完成") + + def batch_convert(self): + """批量转换文件""" + files = self.file_selector.get_selected_files() + if not files: + QMessageBox.warning(self, "警告", "请先选择要转换的文件") + return + + # 获取输出目录 + output_dir = QFileDialog.getExistingDirectory( + self, "选择输出目录", os.path.expanduser("~") + ) + if not output_dir: + return + + # 获取转换参数 + params = self.param_panel.get_params() + + # 检查是否有需要预处理的图像 + processed_image = None + if self.image_toolbar.isEnabled(): + processed_image = self.image_toolbar.get_processed_image() + + # 启动批量转换,传递处理后的图像 + self.batch_manager.start_batch(files, output_dir, params, processed_image) + + def closeEvent(self, event): + """处理窗口关闭事件""" + # 保存窗口几何形状 + self.settings.setValue("geometry", self.saveGeometry()) + super().closeEvent(event) \ No newline at end of file diff --git a/ui/param_panel.py b/ui/param_panel.py new file mode 100644 index 0000000..1cd7016 --- /dev/null +++ b/ui/param_panel.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 参数配置面板 +负责MIF转换的参数设置 +""" + +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, + QComboBox, QSpinBox, QLineEdit, QGroupBox, + QFormLayout, QCheckBox, QSlider +) +from PyQt6.QtCore import Qt, QSettings, QRegularExpression +from PyQt6.QtGui import QRegularExpressionValidator + +class ParamPanel(QWidget): + """参数配置面板""" + + def __init__(self, settings: QSettings, parent=None): + """初始化参数配置面板""" + super().__init__(parent) + self.settings = settings + + self._init_ui() + self._load_settings() + self._connect_signals() + + def _init_ui(self): + """初始化UI""" + # 创建主布局 + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + + # 创建标题标签 + title_label = QLabel("参数配置") + title_label.setStyleSheet("font-weight: bold; font-size: 14px;") + layout.addWidget(title_label) + + # 创建基本参数组 + basic_group = QGroupBox("基本参数") + basic_layout = QFormLayout(basic_group) + layout.addWidget(basic_group) + + # WIDTH 参数 + self.width_combo = QComboBox() + self.width_combo.addItems(["8位", "16位", "32位"]) + basic_layout.addRow("数据宽度 (WIDTH):", self.width_combo) + + # DEPTH 参数 + self.depth_layout = QHBoxLayout() + self.auto_depth_check = QCheckBox("自动计算") + self.auto_depth_check.setChecked(True) + self.depth_spin = QSpinBox() + self.depth_spin.setRange(1, 1000000) + self.depth_spin.setValue(1024) + self.depth_spin.setEnabled(False) + self.depth_layout.addWidget(self.auto_depth_check) + self.depth_layout.addWidget(self.depth_spin) + basic_layout.addRow("深度 (DEPTH):", self.depth_layout) + + # 基数设置 + self.radix_combo = QComboBox() + self.radix_combo.addItems(["十六进制 (HEX)", "二进制 (BIN)", "十进制 (DEC)"]) + basic_layout.addRow("数据格式:", self.radix_combo) + + # 地址偏移量 + self.offset_edit = QLineEdit("0") + # 设置十六进制验证器 + hex_validator = QRegularExpressionValidator(QRegularExpression("0x[0-9A-Fa-f]+|[0-9A-Fa-f]+")) + self.offset_edit.setValidator(hex_validator) + self.offset_edit.setPlaceholderText("十六进制值 (例如: 0x100)") + basic_layout.addRow("地址偏移量:", self.offset_edit) + + # 创建高级参数组 + advanced_group = QGroupBox("高级参数") + advanced_layout = QFormLayout(advanced_group) + layout.addWidget(advanced_group) + + # 文件头始终添加,不再提供选项 + + # 地址格式 + self.addr_format_combo = QComboBox() + self.addr_format_combo.addItems(["标准格式 (@XXXX)", "紧凑格式 (XXXX:)"]) + advanced_layout.addRow("地址格式:", self.addr_format_combo) + + # 地址进制 + self.addr_radix_combo = QComboBox() + self.addr_radix_combo.addItems(["十六进制 (HEX)", "二进制 (BIN)", "十进制 (DEC)"]) + advanced_layout.addRow("地址进制:", self.addr_radix_combo) + + # 每行数据数量 + self.data_per_line_spin = QSpinBox() + self.data_per_line_spin.setRange(1, 16) + self.data_per_line_spin.setValue(1) + advanced_layout.addRow("每行数据数量:", self.data_per_line_spin) + + # 添加弹性空间 + layout.addStretch(1) + + def _load_settings(self): + """加载设置""" + # 加载WIDTH设置 + width_index = self.settings.value("params/width_index", 0, int) + self.width_combo.setCurrentIndex(width_index) + + # 加载DEPTH设置 + auto_depth = self.settings.value("params/auto_depth", True, bool) + self.auto_depth_check.setChecked(auto_depth) + self.depth_spin.setEnabled(not auto_depth) + depth = self.settings.value("params/depth", 1024, int) + self.depth_spin.setValue(depth) + + # 加载基数设置 + radix_index = self.settings.value("params/radix_index", 0, int) + self.radix_combo.setCurrentIndex(radix_index) + + # 加载地址偏移量 + offset = self.settings.value("params/offset", "0") + self.offset_edit.setText(offset) + + # 加载高级设置 + + addr_format_index = self.settings.value("params/addr_format_index", 0, int) + self.addr_format_combo.setCurrentIndex(addr_format_index) + + addr_radix_index = self.settings.value("params/addr_radix_index", 0, int) + self.addr_radix_combo.setCurrentIndex(addr_radix_index) + + data_per_line = self.settings.value("params/data_per_line", 1, int) + self.data_per_line_spin.setValue(data_per_line) + + def _connect_signals(self): + """连接信号和槽""" + # 自动深度复选框 + self.auto_depth_check.toggled.connect(self._on_auto_depth_toggled) + + # 保存设置 + self.width_combo.currentIndexChanged.connect(self._save_settings) + self.auto_depth_check.toggled.connect(self._save_settings) + self.depth_spin.valueChanged.connect(self._save_settings) + self.radix_combo.currentIndexChanged.connect(self._save_settings) + self.offset_edit.editingFinished.connect(self._save_settings) + # 文件头选项已移除 + self.addr_format_combo.currentIndexChanged.connect(self._save_settings) + self.addr_radix_combo.currentIndexChanged.connect(self._save_settings) + self.data_per_line_spin.valueChanged.connect(self._save_settings) + + def _on_auto_depth_toggled(self, checked): + """处理自动深度复选框切换事件""" + self.depth_spin.setEnabled(not checked) + + def _save_settings(self): + """保存设置""" + self.settings.setValue("params/width_index", self.width_combo.currentIndex()) + self.settings.setValue("params/auto_depth", self.auto_depth_check.isChecked()) + self.settings.setValue("params/depth", self.depth_spin.value()) + self.settings.setValue("params/radix_index", self.radix_combo.currentIndex()) + self.settings.setValue("params/offset", self.offset_edit.text()) + # 文件头设置已移除,始终为True + self.settings.setValue("params/header", True) + self.settings.setValue("params/addr_format_index", self.addr_format_combo.currentIndex()) + self.settings.setValue("params/addr_radix_index", self.addr_radix_combo.currentIndex()) + self.settings.setValue("params/data_per_line", self.data_per_line_spin.value()) + + def get_params(self): + """获取参数""" + # 获取WIDTH值 + width_map = {0: 8, 1: 16, 2: 32} + width = width_map[self.width_combo.currentIndex()] + + # 获取DEPTH值 + auto_depth = self.auto_depth_check.isChecked() + depth = self.depth_spin.value() if not auto_depth else None + + # 获取基数 + radix_map = {0: "HEX", 1: "BIN", 2: "DEC"} + radix = radix_map[self.radix_combo.currentIndex()] + + # 获取地址偏移量 + offset_text = self.offset_edit.text() + if offset_text.startswith("0x"): + offset = int(offset_text, 16) + else: + offset = int(offset_text, 16) + + # 获取高级参数 + addr_format = "standard" if self.addr_format_combo.currentIndex() == 0 else "compact" + + # 获取地址进制 + addr_radix_map = {0: "HEX", 1: "BIN", 2: "DEC"} + addr_radix = addr_radix_map[self.addr_radix_combo.currentIndex()] + + data_per_line = self.data_per_line_spin.value() + + # 返回参数字典 + return { + "width": width, + "auto_depth": auto_depth, + "depth": depth, + "radix": radix, + "offset": offset, + "header": True, # 始终添加文件头 + "addr_format": addr_format, + "addr_radix": addr_radix, + "data_per_line": data_per_line + } \ No newline at end of file diff --git a/ui/theme_controller.py b/ui/theme_controller.py new file mode 100644 index 0000000..347af1d --- /dev/null +++ b/ui/theme_controller.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Any2MIF Project +# All rights reserved. + +""" +Any2MIF - 主题控制器 +负责应用程序的主题设置,锁定为深色模式 +""" + +import os +from PyQt6.QtWidgets import QWidget +from PyQt6.QtCore import QSettings, pyqtSignal + +class ThemeController(QWidget): + """主题控制器,锁定为深色模式""" + + # 自定义信号 + theme_changed = pyqtSignal(str) # 主题变更时发出的信号 + + def __init__(self, settings: QSettings, parent=None): + """初始化主题控制器""" + super().__init__(parent) + self.settings = settings + + # 直接设置为深色模式 + self.settings.setValue("theme", "dark") + self.apply_theme("dark") + self.theme_changed.emit("dark") + + def apply_theme(self, theme): + """应用主题""" + # 加载样式表 + style_file = os.path.join("resources", "styles", f"{theme}.qss") + + if os.path.exists(style_file): + with open(style_file, "r", encoding="utf-8") as f: + style_sheet = f.read() + # 应用样式表到应用程序 + app = self.window().parent() + if app: + app.setStyleSheet(style_sheet) + else: + # 如果样式文件不存在,使用默认样式 + self._apply_default_style(theme) + + def _apply_default_style(self, theme): + """应用默认样式""" + if theme == "light": + style_sheet = """ + QMainWindow, QDialog { + background-color: #f5f5f5; + color: #333333; + } + + QWidget { + background-color: #f5f5f5; + color: #333333; + } + + QLabel { + color: #333333; + } + + QPushButton { + background-color: #e0e0e0; + border: 1px solid #b0b0b0; + border-radius: 4px; + padding: 5px 10px; + color: #333333; + } + + QPushButton:hover { + background-color: #d0d0d0; + } + + QPushButton:pressed { + background-color: #c0c0c0; + } + + QLineEdit, QSpinBox, QComboBox { + background-color: #ffffff; + border: 1px solid #b0b0b0; + border-radius: 4px; + padding: 3px; + color: #333333; + } + + QGroupBox { + border: 1px solid #b0b0b0; + border-radius: 4px; + margin-top: 10px; + padding-top: 10px; + } + + QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; + color: #333333; + } + + QListWidget { + background-color: #ffffff; + border: 1px solid #b0b0b0; + border-radius: 4px; + color: #333333; + } + + QListWidget::item:selected { + background-color: #b0b0b0; + color: #333333; + } + + QSlider::groove:horizontal { + border: 1px solid #b0b0b0; + height: 8px; + background: #ffffff; + margin: 2px 0; + border-radius: 4px; + } + + QSlider::handle:horizontal { + background: #e0e0e0; + border: 1px solid #b0b0b0; + width: 18px; + margin: -2px 0; + border-radius: 9px; + } + + QSlider::handle:horizontal:hover { + background: #d0d0d0; + } + + QStatusBar { + background-color: #e0e0e0; + color: #333333; + } + + QToolBar { + background-color: #e0e0e0; + border-bottom: 1px solid #b0b0b0; + } + """ + else: # dark + style_sheet = """ + QMainWindow, QDialog { + background-color: #2d2d2d; + color: #f0f0f0; + } + + QWidget { + background-color: #2d2d2d; + color: #f0f0f0; + } + + QLabel { + color: #f0f0f0; + } + + QPushButton { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + padding: 5px 10px; + color: #f0f0f0; + } + + QPushButton:hover { + background-color: #4d4d4d; + } + + QPushButton:pressed { + background-color: #5d5d5d; + } + + QLineEdit, QSpinBox, QComboBox { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + padding: 3px; + color: #f0f0f0; + } + + QGroupBox { + border: 1px solid #5d5d5d; + border-radius: 4px; + margin-top: 10px; + padding-top: 10px; + } + + QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; + padding: 0 5px; + color: #f0f0f0; + } + + QListWidget { + background-color: #3d3d3d; + border: 1px solid #5d5d5d; + border-radius: 4px; + color: #f0f0f0; + } + + QListWidget::item:selected { + background-color: #5d5d5d; + color: #f0f0f0; + } + + QSlider::groove:horizontal { + border: 1px solid #5d5d5d; + height: 8px; + background: #3d3d3d; + margin: 2px 0; + border-radius: 4px; + } + + QSlider::handle:horizontal { + background: #5d5d5d; + border: 1px solid #7d7d7d; + width: 18px; + margin: -2px 0; + border-radius: 9px; + } + + QSlider::handle:horizontal:hover { + background: #6d6d6d; + } + + QStatusBar { + background-color: #3d3d3d; + color: #f0f0f0; + } + + QToolBar { + background-color: #3d3d3d; + border-bottom: 1px solid #5d5d5d; + } + """ + + # 应用样式表到应用程序 + app = self.window().parent() + if app: + app.setStyleSheet(style_sheet) \ No newline at end of file