├── .gitignore ├── LICENSE ├── README.md ├── conf.yaml ├── dataset_processor ├── __init__.py ├── data.py ├── filter.py ├── processor.py ├── tools │ ├── __init__.py │ ├── tagger.py │ └── upscale.py └── uitl.py ├── doc └── doc_cn.md ├── main.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | test.py 2 | \__pycache__ 3 | test.yaml 4 | tag_images_by_wd14_tagger.py 5 | \models 6 | \.idea 7 | \venv -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 一站式的图片数据集预处理工具包 2 | 3 | [说明文档](https://github.com/waterminer/SD-DatasetProcessor/blob/preview/doc/doc_cn.md) 4 | 5 | ✅批量处理图片 6 | 包括且不限于: 7 | 8 | * 批量翻转 9 | * 批量随机裁切 10 | * 图片对比度增强 11 | 12 | ✅批量处理标签 13 | 包括且不限于: 14 | 15 | * 批量删除标签 16 | * 批量插入标签 17 | * 批量修改标签 18 | 19 | ✅过滤机制 20 | 21 | ✅易于开发/维护 22 | 23 | ✅自动打标(试验性) 24 | 25 | ✅AI图片放大(试验性) 26 | 27 | ✅子处理(试验性) 28 | 29 | ## TODO 30 | 31 | 🚧智能裁切 32 | 33 | 🚧重构自动打标代码 34 | 35 | 🚧图形化界面 36 | 37 | ## CREADIT 38 | 39 | ### Upscale 40 | 41 | [Real ESRGAN](https://github.com/xinntao/Real-ESRGAN/):一种流行的AI放大方案 42 | 43 | [Real CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN):更加适合二次元的AI放大方案 44 | 45 | [Real CUGAN-ncnn](https://github.com/Tohrusky/realcugan-ncnn-py):感谢这位作者提供的RealCUGAN工具包 46 | 47 | ### Tagger 48 | 49 | [WD-1.4-Tagger From SmilingWolf](https://huggingface.co/SmilingWolf):自动打标模型 50 | 51 | --- 52 | 如果这个项目为您提供了帮助,不妨点一个⭐star,万分感谢! 53 | -------------------------------------------------------------------------------- /conf.yaml: -------------------------------------------------------------------------------- 1 | path: 2 | input: "" #输入路径 3 | output: "" #输出路径 4 | 5 | tagger: 6 | active: True #启用自动打标 7 | batch_size: 4 #批次大小 8 | max_data_loader_n_workers: 1 #越大越占内存 9 | 10 | conduct: 11 | - #处理组1 此处示意为将所有大于512的图片进行翻转 12 | filters: #用于定义过滤器 13 | - #过滤器1 14 | filter: img_size 15 | arg: [512,-1] 16 | processor: #用于定义处理器 17 | - #处理器1 18 | method: flip 19 | arg: 512 20 | 21 | #以下为进阶示范 22 | - #处理组2 此处示意为将1024~2048区间大小的图片进行缩放然后进行随机裁切 23 | repeat: 3 #用于循环执行 24 | filters: #用于定义过滤器 25 | - #过滤器1 26 | filter: img_size 27 | arg: [1024,2048] 28 | processor: #用于定义处理器 29 | - #处理器1 30 | method: resize 31 | arg: 0.5 32 | - #处理器2 33 | method: random_crop 34 | arg: 512 -------------------------------------------------------------------------------- /dataset_processor/__init__.py: -------------------------------------------------------------------------------- 1 | from .data import Data 2 | from .filter import Filter 3 | from .processor import Processor, ProcessorError 4 | from .uitl import * 5 | from .tools import * 6 | -------------------------------------------------------------------------------- /dataset_processor/data.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import os 3 | 4 | 5 | class Data: 6 | 7 | # 图片读取并初始化 8 | def __init__(self, path: str, name: str, ext: str): 9 | self.token: list[str] = [] 10 | self.conduct = "" 11 | self.repeat = 0 12 | self.id = 0 13 | self.name = name 14 | self.ext = ext 15 | self.path = path 16 | # 读取图片 17 | self.img = Image.open(os.path.join(path, name + ext)) 18 | self.size = self.img.size 19 | 20 | # 载入标签 21 | def input_token(self, file_name: str, option=None): 22 | clean_tag = False 23 | NO_CHECK = [ # 清洗排除标签 24 | ':)', ';)', ':(', '>:)', '>:(', '\\(^o^)/', # 括号相关 25 | '^_^', '@_@', '>_@', '+_+', '+_-', 'o_o', '0_0', '|_|', '._.', '>_<', '=_=', '_', '<|>_<|>' # 下划线相关 26 | ] 27 | if option.clean_tag: 28 | clean_tag = True 29 | with open(os.path.join(self.path, file_name), "r") as f: 30 | self.token = f.read(-1).split(",") 31 | for tag in self.token: 32 | tag = tag.strip() 33 | if clean_tag: 34 | if tag not in NO_CHECK: 35 | tag = tag.replace("_", " ") 36 | tag = tag.replace("(", "\\(") 37 | tag = tag.replace(")", "\\)") 38 | 39 | # 保存的方法 40 | def save(self, output_dir, option): 41 | # 默认命名方式:id_conduct_repeat.ext 比如"000001_r_0.jpg" 42 | save_name = str(self.id).zfill(6) + self.conduct 43 | if option: 44 | if option.save_source_name or option.save_conduct_id: 45 | save_name = str(self.id).zfill(6) 46 | if option.save_source_name: 47 | save_name = save_name.join('_' + self.name) 48 | if option.save_conduct_id: 49 | save_name = save_name.join(self.conduct) 50 | self.img.save(os.path.join(output_dir, save_name + self.ext)) 51 | # print(save_name) 52 | with open(os.path.join(output_dir, save_name + ".txt"), mode="w") as f: 53 | text = ",".join(self.token) 54 | f.write(text) 55 | self.img.close() 56 | -------------------------------------------------------------------------------- /dataset_processor/filter.py: -------------------------------------------------------------------------------- 1 | from .data import Data 2 | 3 | 4 | class Filter: 5 | """ 6 | 这是一个过滤器类,包含所有有关数据过滤的函数 7 | 编写规范如下: 8 | def 过滤器名(data:Data,arg)->bool: 9 | #代码块 10 | return bool 11 | 其中,True表示该数据会被过滤,False则会被保留 12 | """ 13 | 14 | def img_size(data: Data, size: list) -> bool: 15 | min, max = tuple(size) 16 | x, y = data.size 17 | if min != -1: 18 | if data.size[0] <= min or data.size[1] <= min: 19 | return True 20 | if max != -1: 21 | if data.size[0] > max and data.size[1] > max: 22 | return True 23 | else: 24 | return False 25 | 26 | def tag_filter(data: Data, tag) -> bool: 27 | if tag in data.token: 28 | return True 29 | else: 30 | return False 31 | 32 | def tag_selector(data: Data, tag) -> bool: 33 | if tag in data.token: 34 | return False 35 | else: 36 | return True 37 | 38 | def tag_is_not_none(data: Data) -> bool: 39 | if data.token: 40 | return False 41 | else: 42 | return True 43 | 44 | def tag_is_none(data: Data) -> bool: 45 | if data.token: 46 | return True 47 | else: 48 | return False 49 | -------------------------------------------------------------------------------- /dataset_processor/processor.py: -------------------------------------------------------------------------------- 1 | from random import randint as random 2 | from .data import Data 3 | from .tools.tagger import Tagger 4 | from .tools.upscale import UpscaleModel 5 | from PIL import Image 6 | from PIL import ImageEnhance 7 | import numpy as np 8 | 9 | 10 | class Processor: 11 | """ 12 | 这是一个处理器类,包含所有有关数据处理的函数 13 | 编写规范如下: 14 | def 处理名(data:Data,args)->Data: 15 | #代码块 16 | return data 17 | """ 18 | 19 | def random_crop(data: Data, size) -> Data: 20 | if not (data.size[0] <= size or data.size[1] <= size): 21 | x = random(1, data.size[0] - size) 22 | y = random(1, data.size[1] - size) 23 | box = (x, y, x + size, y + size) 24 | data.img = data.img.crop(box) 25 | data.conduct += f"_rc{data.repeat}" 26 | data.size = data.img.size 27 | else: 28 | raise ImageTooSmallError(data.name + data.ext) 29 | return data 30 | 31 | def flip(data: Data) -> Data: 32 | data.img = data.img.transpose(Image.FLIP_LEFT_RIGHT) 33 | data.conduct += f"_f{data.repeat}" 34 | return data 35 | 36 | def resize(data: Data, proportion: float) -> Data: 37 | size = (int(data.size[0] * proportion), int(data.size[1] * proportion)) 38 | data.img = data.img.resize(size) 39 | data.conduct += f"_r{data.repeat}" 40 | data.size = data.img.size 41 | return data 42 | 43 | def force_resize(data: Data, size: list) -> Data: 44 | data.img = data.img.resize(size) 45 | data.conduct += f"_fr{data.repeat}" 46 | data.size = data.img.size 47 | return data 48 | 49 | def offset(data: Data, offset: int) -> Data: 50 | data.img = data.img.offset(offset, 0) 51 | data.conduct += f"_off{data.repeat}" 52 | return data 53 | 54 | def rotation(data: Data, rot: int) -> Data: 55 | data.img = data.img.rotate(rot) 56 | data.conduct += f"_rot{data.repeat}" 57 | return data 58 | 59 | def contrast_enhancement(data: Data) -> Data: # 对比度增强 60 | image = data.img 61 | enh_con = ImageEnhance.Contrast(image) 62 | contrast = 1.5 63 | data.img = enh_con.enhance(contrast) 64 | data.conduct += f"_con_e{data.repeat}" 65 | return data 66 | 67 | def brightness_enhancement(data: Data) -> Data: # 亮度增强 68 | image = data.img 69 | enh_bri = ImageEnhance.Brightness(image) 70 | brightness = 1.5 71 | data.img = enh_bri.enhance(brightness) 72 | data.conduct += f"_bri_e{data.repeat}" 73 | return data 74 | 75 | def color_enhancement(data: Data) -> Data: # 颜色增强 76 | image = data.img 77 | enh_col = ImageEnhance.Color(image) 78 | color = 1.5 79 | data.img = enh_col.enhance(color) 80 | data.conduct += "_col_e" 81 | return data 82 | 83 | def random_enhancement(data: Data) -> Data: # 随机抖动 84 | image = data.img 85 | random_factor = np.random.randint(8, 31) / 10. # 随机因子 86 | color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度 87 | random_factor = np.random.randint(8, 10) / 10. # 随机因子 88 | brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度 89 | random_factor = np.random.randint(8, 10) / 10. # 随机因子 90 | contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # 调整图像对比度 91 | random_factor = np.random.randint(8, 20) / 10. # 随机因子 92 | data.img = ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度 93 | data.conduct += f"_ran_e{data.repeat}" 94 | return data 95 | 96 | def none(data: Data) -> Data: 97 | """ 98 | 无操作,主要用于一些特殊场景 99 | """ 100 | return data 101 | 102 | def append_tag(data: Data, tag: str) -> Data: 103 | data.token.append(tag) 104 | return data 105 | 106 | def remove_tag(data: Data, tag: str) -> Data: 107 | if tag in data.token: 108 | data.token.remove(tag) 109 | else: 110 | raise TagNotExistError(tag, data.name + data.ext) 111 | return data 112 | 113 | def insert_tag(data: Data, tag: str) -> Data: 114 | data.token.insert(0, tag) 115 | return data 116 | 117 | def tag_move_forward(data: Data, tag: str) -> Data: 118 | """ 119 | 将匹配项放到开头 120 | """ 121 | if tag in data.token: 122 | data.token.remove(tag) 123 | else: 124 | raise TagNotExistError(tag, data.name + data.ext) 125 | data.token.insert(0, tag) 126 | return data 127 | 128 | def rename_tag(data: Data, tags: list[str]) -> Data: 129 | """ 130 | 将Atag改名为Btag 131 | """ 132 | tag_a = tags[0] 133 | tag_b = tags[1] 134 | if tag_a in data.token: 135 | index = data.token.index(tag_a) 136 | data.token.insert(index, tag_b) 137 | data.token.remove(tag_a) 138 | else: 139 | raise TagNotExistError(tag_a, data.name + data.ext) 140 | return data 141 | 142 | def tag_image(data: Data, tagger: Tagger): 143 | return tagger.tag_data(data) 144 | 145 | def upscale_image(data: Data, upscale: UpscaleModel): 146 | data.img = upscale.upscale_data(data) 147 | data.size = data.img.size 148 | return data 149 | 150 | 151 | # 自定义异常 152 | class ProcessorError(RuntimeError): 153 | def __init__(self, *args: object) -> None: 154 | super().__init__(*args) 155 | 156 | 157 | class ImageTooSmallError(ProcessorError): 158 | def __init__(self, name: str): 159 | print("image " + name + " is too small!") 160 | 161 | 162 | class TagNotExistError(ProcessorError): 163 | def __init__(self, tag, name: str): 164 | print("Tag" + tag + "not exist in" + name + "!") 165 | -------------------------------------------------------------------------------- /dataset_processor/tools/__init__.py: -------------------------------------------------------------------------------- 1 | from .tagger import Tagger, TaggerOption 2 | from .upscale import UpscaleModel, UpcaleOption 3 | -------------------------------------------------------------------------------- /dataset_processor/tools/tagger.py: -------------------------------------------------------------------------------- 1 | from huggingface_hub import hf_hub_download 2 | from keras.models import load_model 3 | import torch 4 | from tqdm import tqdm 5 | import numpy as np 6 | import cv2 7 | 8 | 9 | from dataset_processor import Data 10 | from dataclasses import dataclass, field 11 | import os 12 | from enum import Enum 13 | import csv 14 | 15 | IMAGE_SIZE = 448 16 | 17 | class ModelType(Enum): 18 | WD14_MOAT = "wd-v1-4-moat-tagger-v2" 19 | WD14_VIT = "wd-v1-4-vit-tagger-v2" 20 | WD14_SWINV2 = "wd-v1-4-swinv2-tagger-v2" 21 | WD14_CONVNEXT = "wd-v1-4-convnext-tagger-v2" 22 | WD14_CONVNEXT2 = "wd-v1-4-convnextv2-tagger-v2" 23 | 24 | 25 | @dataclass 26 | class TaggerOption: 27 | force_download: bool = field(default=False) 28 | model_type: ModelType = field(default=ModelType.WD14_CONVNEXT) 29 | model_path: str = field(default="./models") 30 | undesired_tags: str = field(default="") 31 | batch_size:int = field(default=1) 32 | max_data_loader_n_workers: int = field(default=None) 33 | remove_underscore:bool = field(default=True) 34 | thresh:float = field(default=0.35) 35 | character_threshold:float = field(default=None) 36 | general_threshold:float = field(default=None) 37 | 38 | 39 | def preprocess_image(image): 40 | image = np.array(image) 41 | image = image[:, :, ::-1] # RGB->BGR 42 | 43 | # pad to square 44 | size = max(image.shape[0:2]) 45 | pad_x = size - image.shape[1] 46 | pad_y = size - image.shape[0] 47 | pad_l = pad_x // 2 48 | pad_t = pad_y // 2 49 | image = np.pad(image, 50 | ((pad_t, pad_y - pad_t), 51 | (pad_l, pad_x - pad_l), (0, 0)), 52 | mode="constant", 53 | constant_values=255) 54 | 55 | interp = cv2.INTER_AREA if size > IMAGE_SIZE else cv2.INTER_LANCZOS4 56 | image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE), interpolation=interp) 57 | 58 | image = image.astype(np.float32) 59 | return image 60 | 61 | def collate_fn_remove_corrupted(batch): 62 | """Collate function that allows to remove corrupted examples in the 63 | dataloader. It expects that the dataloader returns 'None' when that occurs. 64 | The 'None's in the batch are removed. 65 | """ 66 | # Filter out all the Nones (corrupted examples) 67 | batch = list(filter(lambda x: x is not None, batch)) 68 | return batch 69 | 70 | class ImageLoadingPrepDataset(torch.utils.data.Dataset): 71 | def __init__(self,data_list:list[Data]) -> None: 72 | self.dataset = [] 73 | for data in data_list: 74 | self.dataset.append({'img':data.img,'sorce_data':data}) 75 | def __len__(self): 76 | return len(self.dataset) 77 | 78 | def __getitem__(self,idx): 79 | sorce_data = self.dataset[idx]['sorce_data'] 80 | img = self.dataset[idx]['img'] 81 | img= preprocess_image(img) 82 | tensor = torch.tensor(img) 83 | return (tensor, sorce_data) 84 | 85 | class Tagger: 86 | 87 | FILES = ["keras_metadata.pb", "saved_model.pb", "selected_tags.csv"] 88 | SUB_DIR = "variables" 89 | SUB_DIR_FILES = ["variables.data-00000-of-00001", "variables.index"] 90 | CSV_FILE = FILES[-1] 91 | MODEL_AUTHOR_ID = "SmilingWolf/" 92 | 93 | 94 | def __init__ (self,option: TaggerOption | None = TaggerOption()): 95 | print("Init tagger...") 96 | self.repo_id = self.MODEL_AUTHOR_ID + option.model_type.value 97 | self.model_path = os.path.join(option.model_path, option.model_type.value) 98 | if not os.path.exists(self.model_path) or option.force_download: 99 | print("Downloading model from huggingface:" + self.repo_id) 100 | os.mkdir(self.model_path) 101 | for file in self.FILES: 102 | hf_hub_download( 103 | self.repo_id, 104 | filename=file, 105 | cache_dir=self.model_path, 106 | force_download=True, 107 | force_filename=file) 108 | for file in self.SUB_DIR_FILES: 109 | hf_hub_download( 110 | self.repo_id, 111 | filename=file, 112 | subfolder=self.SUB_DIR, 113 | cache_dir=os.path.join(self.model_path, self.SUB_DIR), 114 | force_download=True, 115 | force_filename=file, 116 | ) 117 | print("Loading model...") 118 | self.model = load_model(self.model_path) 119 | with open(os.path.join(self.model_path, self.CSV_FILE), "r", -1, "utf-8") as f: 120 | reader = csv.reader(f) 121 | line = [row for row in reader] 122 | header = line[0] 123 | rows = line[1:] 124 | assert header[0] == "tag_id" and header[1] == "name" and header[2] == "category", f"unexpected csv format: {header}" 125 | self.general_tags = [row[1] for row in rows[1:] if row[2] == "0"] 126 | self.character_tags = [row[1] for row in rows[1:] if row[2] == "4"] 127 | self.tag_freq = {} 128 | self.undesired_tags = set(option.undesired_tags.split(",")) 129 | self.batch_size = option.batch_size 130 | self.max_data_loader_n_workers = option.max_data_loader_n_workers 131 | self.remove_underscore = option.remove_underscore 132 | self.thresh = option.thresh 133 | if option.character_threshold is None: 134 | self.character_threshold = self.thresh 135 | else: 136 | self.character_threshold = option.character_threshold 137 | if option.general_threshold is None: 138 | self.general_threshold = self.thresh 139 | else: 140 | self.general_threshold = option.general_threshold 141 | self.debug = False 142 | 143 | 144 | def run_batch(self,batchs): 145 | imgs = np.array([im for _, im in batchs]) 146 | 147 | probs = self.model(imgs, training=False) 148 | probs = probs.numpy() 149 | 150 | for (sorce_data, _), prob in zip(batchs, probs): 151 | # 最初の4つはratingなので無視する 152 | # # First 4 labels are actually ratings: pick one with argmax 153 | # ratings_names = label_names[:4] 154 | # rating_index = ratings_names["probs"].argmax() 155 | # found_rating = ratings_names[rating_index: rating_index + 1][["name", "probs"]] 156 | 157 | # それ以降はタグなのでconfidenceがthresholdより高いものを追加する 158 | # Everything else is tags: pick any where prediction confidence > threshold 159 | combined_tags = [] 160 | general_tag_text = "" 161 | character_tag_text = "" 162 | for i, p in enumerate(prob[4:]): 163 | if i < len(self.general_tags) and p >= self.general_threshold: 164 | tag_name = self.general_tags[i] 165 | if self.remove_underscore and len(tag_name) > 3: # ignore emoji tags like >_< and ^_^ 166 | tag_name = tag_name.replace("_", " ") 167 | 168 | if tag_name not in self.undesired_tags: 169 | self.tag_freq[tag_name] = self.tag_freq.get(tag_name, 0) + 1 170 | general_tag_text += ", " + tag_name 171 | combined_tags.append(tag_name) 172 | elif i >= len(self.general_tags) and p >= self.character_threshold: 173 | tag_name = self.character_tags[i - len(self.general_tags)] 174 | if self.remove_underscore and len(tag_name) > 3: 175 | tag_name = tag_name.replace("_", " ") 176 | 177 | if tag_name not in self.undesired_tags: 178 | self.tag_freq[tag_name] = self.tag_freq.get(tag_name, 0) + 1 179 | character_tag_text += ", " + tag_name 180 | combined_tags.append(tag_name) 181 | 182 | # 先頭のカンマを取る 183 | if len(general_tag_text) > 0: 184 | general_tag_text = general_tag_text[2:] 185 | if len(character_tag_text) > 0: 186 | character_tag_text = character_tag_text[2:] 187 | tag_text = ", ".join(combined_tags) 188 | sorce_data.token = combined_tags 189 | if self.debug: 190 | print("Character tags: "+ 191 | character_tag_text+ 192 | "\n General tags: "+ 193 | general_tag_text) 194 | 195 | 196 | def tag_data_list(self,data_list:list[Data]): 197 | dataset = ImageLoadingPrepDataset(data_list) 198 | if self.max_data_loader_n_workers is not None: 199 | tensor_data = torch.utils.data.DataLoader( 200 | dataset, 201 | batch_size=self.batch_size, 202 | shuffle=False, 203 | num_workers=self.max_data_loader_n_workers, 204 | collate_fn=collate_fn_remove_corrupted, 205 | drop_last=False 206 | ) 207 | else: 208 | tensor_data = [[(None,data)] for data in data_list] 209 | b_imgs = [] 210 | for data_entry in tqdm(tensor_data,smoothing=0.0): 211 | for tensor_data in data_entry: 212 | if tensor_data is None: 213 | continue 214 | image, sorce_data = tensor_data 215 | for data in data_list: 216 | if sorce_data.name == data.name: 217 | sorce_data = data 218 | if image is not None: 219 | image = image.detach().numpy() 220 | else: 221 | image = sorce_data.img 222 | if image.mode != "RGB": 223 | image = image.convert("RGB") 224 | image = preprocess_image(image) 225 | b_imgs.append((sorce_data, image)) 226 | if len(b_imgs) >= self.batch_size: 227 | b_imgs = [(sorce_data, image) for sorce_data, image in b_imgs] # Convert image_path to string 228 | self.run_batch(b_imgs) 229 | b_imgs.clear() 230 | 231 | if len(b_imgs) > 0: 232 | b_imgs = [(sorce_data, image) for sorce_data, image in b_imgs] # Convert image_path to string 233 | self.run_batch(b_imgs) 234 | 235 | def tag_data(self,data:Data): 236 | img = preprocess_image(data.img) 237 | b_imgs = [(data,img)] 238 | self.run_batch(b_imgs) 239 | return data 240 | 241 | -------------------------------------------------------------------------------- /dataset_processor/tools/upscale.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from torch import nn as nn 3 | from PIL.Image import Image, fromarray 4 | from basicsr.archs.rrdbnet_arch import RRDBNet 5 | from basicsr.utils.download_util import load_file_from_url 6 | from huggingface_hub import hf_hub_download 7 | from realesrgan import RealESRGANer as RealESRGANModel 8 | from realcugan_ncnn_py import Realcugan as RealcuganModel 9 | 10 | from dataclasses import dataclass, field 11 | import os 12 | from enum import Enum, auto as enumauto 13 | 14 | from dataset_processor import Data 15 | 16 | 17 | class ModelType(Enum): 18 | R_ESRGAN_2X = enumauto() 19 | R_ESRGAN_4X = enumauto() 20 | R_ESRNET_4X = enumauto() 21 | R_ESRGAN_ANIME6B_4X = enumauto() 22 | R_CUGAN_2X_CON = enumauto() 23 | R_CUGAN_2X_ND = enumauto() 24 | R_CUGAN_2X_D1 = enumauto() 25 | R_CUGAN_2X_D2 = enumauto() 26 | R_CUGAN_2X_D3 = enumauto() 27 | R_CUGAN_3X_CON = enumauto() 28 | R_CUGAN_3X_ND = enumauto() 29 | R_CUGAN_3X_D3 = enumauto() 30 | R_CUGAN_4X_CON = enumauto() 31 | R_CUGAN_4X_ND = enumauto() 32 | R_CUGAN_4X_D3 = enumauto() 33 | CUSTOM = enumauto() 34 | 35 | 36 | @dataclass 37 | class UpcaleOption: 38 | force_download: bool = field(default=False) 39 | model_type: ModelType = field(default=ModelType.R_ESRGAN_2X) 40 | model_path: str = field(default="./models") 41 | custom_model_name: str = field(default="") 42 | custom_model: nn.Module = field(default=None) 43 | custom_scale: int = field(default=2) 44 | tile: int = field(default=512) 45 | tile_pad: int = field(default=10) 46 | pre_pad: int = field(default=10) 47 | half: bool = field(default=True) 48 | gpuid: int = field(default=0) 49 | 50 | 51 | class CustomModelError(RuntimeError): ... 52 | 53 | 54 | class UpscaleModel(): 55 | REAL_ESRGAN_MODEL = [ 56 | ModelType.R_ESRGAN_2X, 57 | ModelType.R_ESRGAN_4X, 58 | ModelType.R_ESRNET_4X, 59 | ModelType.R_ESRGAN_ANIME6B_4X 60 | ] 61 | REAL_CUGAN_MODEL = [ 62 | ModelType.R_CUGAN_2X_CON, 63 | ModelType.R_CUGAN_2X_ND, 64 | ModelType.R_CUGAN_2X_D1, 65 | ModelType.R_CUGAN_2X_D2, 66 | ModelType.R_CUGAN_2X_D3, 67 | ModelType.R_CUGAN_3X_CON, 68 | ModelType.R_CUGAN_3X_ND, 69 | ModelType.R_CUGAN_3X_D3, 70 | ModelType.R_CUGAN_4X_CON, 71 | ModelType.R_CUGAN_4X_ND, 72 | ModelType.R_CUGAN_4X_D3 73 | ] 74 | 75 | def __init__(self, option: UpcaleOption | None = UpcaleOption()): 76 | print("Init upscale...") 77 | self.realesrgan = None 78 | self.realcugan = None 79 | match option.model_type.value: 80 | case ModelType.R_ESRGAN_2X.value: 81 | url = 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth' 82 | file = "RealESRGAN_x2plus.pth" 83 | model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) 84 | scale = 2 85 | case ModelType.R_ESRGAN_4X.value: 86 | url = 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth' 87 | file = "RealESRGAN_x4plus.pth" 88 | model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) 89 | scale = 4 90 | case ModelType.R_ESRNET_4X.value: 91 | url = "'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth'" 92 | file = "RealESRNet_x4plus.pth" 93 | scale = 8 94 | model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) 95 | case ModelType.R_ESRGAN_ANIME6B_4X.value: 96 | url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth" 97 | file = "RealESRGAN_x4plus_anime_6B.pth" 98 | model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) 99 | scale = 4 100 | case ModelType.R_CUGAN_2X_CON.value: 101 | model = "models-se" 102 | noise = -1 103 | scale = 2 104 | case ModelType.R_CUGAN_2X_ND.value: 105 | model = "models-se" 106 | noise = 0 107 | scale = 2 108 | case ModelType.R_CUGAN_2X_D1.value: 109 | model = "models-se" 110 | noise = 1 111 | scale = 2 112 | case ModelType.R_CUGAN_2X_D2.value: 113 | model = "models-se" 114 | noise = 2 115 | scale = 2 116 | case ModelType.R_CUGAN_2X_D3.value: 117 | model = "models-se" 118 | noise = 3 119 | scale = 2 120 | case ModelType.R_CUGAN_3X_CON.value: 121 | model = "models-se" 122 | noise = -1 123 | scale = 3 124 | case ModelType.R_CUGAN_3X_ND.value: 125 | model = "models-se" 126 | noise = 0 127 | scale = 3 128 | case ModelType.R_CUGAN_3X_D3.value: 129 | model = "models-se" 130 | noise = 3 131 | scale = 3 132 | case ModelType.R_CUGAN_4X_CON.value: 133 | model = "models-se" 134 | noise = -1 135 | scale = 4 136 | case ModelType.R_CUGAN_4X_ND.value: 137 | model = "models-se" 138 | noise = 0 139 | scale = 4 140 | case ModelType.R_CUGAN_4X_D3.value: 141 | model = "models-se" 142 | noise = 3 143 | scale = 4 144 | case ModelType.CUSTOM.value: 145 | try: 146 | file = option.custom_model_name 147 | model = option.custom_model 148 | scale = option.custom_scale 149 | if not os.path.exists(os.path.join(option.model_path, file)): 150 | raise ChildProcessError 151 | except CustomModelError: 152 | print("UpcaleOption:custom_model is not exist!") 153 | exit(1) 154 | case _: 155 | raise RuntimeError 156 | print("Loading upscale model...") 157 | if option.model_type in self.REAL_ESRGAN_MODEL: # 这是一个过度办法,将来我会把这些源换成从抱脸下载 158 | if os.path.exists(os.path.join(option.model_path, file)): 159 | model_path = os.path.join(option.model_path, file) 160 | else: 161 | model_path = os.path.join(option.model_path, "real_esrgan") 162 | if option.model_type is not ModelType.CUSTOM.value and ( 163 | not os.path.exists(os.path.join(model_path, file)) or option.force_download): 164 | model_path = load_file_from_url( 165 | url=url, model_dir=option.model_path, progress=True, file_name=None) 166 | tile = option.tile 167 | tile_pad = option.tile_pad 168 | pre_pad = option.pre_pad 169 | half = option.half 170 | gpuid = option.gpuid 171 | self.realesrgan = RealESRGANModel( 172 | scale=scale, 173 | model_path=model_path, 174 | model=model, 175 | tile=tile, 176 | tile_pad=tile_pad, 177 | pre_pad=pre_pad, 178 | half=half, 179 | gpu_id=gpuid) 180 | if option.model_type in self.REAL_CUGAN_MODEL: 181 | tile_size = option.tile 182 | gpuid = option.gpuid 183 | self.realcugan = RealcuganModel(gpuid, noise=noise, scale=scale, model=model, tilesize=tile_size) 184 | 185 | def upscale_data(self, data: Data) -> Image: 186 | if self.realesrgan: 187 | np_img = np.array(data.img) 188 | np_img, _ = self.realesrgan.enhance(np_img) 189 | return fromarray(np_img) 190 | if self.realcugan: 191 | return self.realcugan.process_pil(data.img) 192 | -------------------------------------------------------------------------------- /dataset_processor/uitl.py: -------------------------------------------------------------------------------- 1 | from tqdm import tqdm 2 | 3 | from dataset_processor import Data 4 | from dataset_processor import Filter 5 | from dataset_processor import Processor, ProcessorError 6 | from .tools.tagger import Tagger, TaggerOption, ModelType as TaggerType 7 | from .tools.upscale import UpcaleOption, UpscaleModel, ModelType as UpscaleType 8 | import copy 9 | import os 10 | 11 | # 文件分类 12 | IMG_EXT = [".png", ".jpg"] # 支持的图片格式 13 | TEXT_EXT = [".txt"] # 支持的标签格式 14 | 15 | 16 | def tagger_builder(args: dict) -> Tagger: 17 | option = TaggerOption() 18 | if args.get('model_path'): 19 | option.model_path = args['model_path'] 20 | if args.get('model_type'): 21 | try: 22 | option.model_type = TaggerType[args['model_type']] 23 | except KeyError: 24 | print(f"Invalid type:{args['model_type']}") 25 | if args.get('force_download'): 26 | option.force_download = args['force_download'] 27 | if args.get('undesired_tags'): 28 | option.undesired_tags = args['undesired_tags'] 29 | if args.get('batch_size'): 30 | option.batch_size = args['batch_size'] 31 | if args.get('max_data_loader_n_workers'): 32 | option.max_data_loader_n_workers = args['max_data_loader_n_workers'] 33 | if args.get('remove_underscore'): 34 | option.remove_underscore = args['remove_underscore'] 35 | if args.get('thresh'): 36 | option.thresh = args['thresh'] 37 | if args.get('character_threshold'): 38 | option.character_threshold = args['character_threshold'] 39 | if args.get('general_threshold'): 40 | option.general_threshold = args['general_threshold'] 41 | return Tagger(option) 42 | 43 | 44 | def upscale_model_builder(args: dict) -> UpscaleModel: 45 | option = UpcaleOption() 46 | if args.get('model_path'): 47 | UpcaleOption.model_path = args['model_path'] 48 | if args.get('force_download'): 49 | UpcaleOption.force_download = args['force_download'] 50 | if args.get('model_type'): 51 | try: 52 | UpcaleOption.model_type = UpscaleType[args['model_type']] 53 | except KeyError: 54 | print(f"Invalid type:{args['model_type']}") 55 | if args.get('tile'): 56 | UpcaleOption.tile = args['tile'] 57 | if args.get('tile_pad'): 58 | UpcaleOption.tile_pad = args['tile_pad'] 59 | if args.get('pre_pad'): 60 | UpcaleOption.pre_pad = args['pre_pad'] 61 | if args.get('half'): 62 | UpcaleOption.half = args['half'] 63 | return UpscaleModel(option) 64 | 65 | 66 | class MainOption: 67 | def __init__(self, args={}): 68 | if args.get('save_source_name'): 69 | self.save_source_name = args.get('save_source_name') 70 | else: 71 | self.save_source_name = False 72 | 73 | if args.get('save_conduct_id'): 74 | self.save_conduct_id = args.get('save_conduct_id') 75 | else: 76 | self.save_conduct_id = False 77 | 78 | if args.get('save_sub'): 79 | self.save_sub = args.get('save_sub') 80 | else: 81 | self.save_sub = False 82 | 83 | if args.get('clean_tag'): 84 | self.clean_tag = args.get('clean_tag') 85 | else: 86 | self.clean_tag = True 87 | 88 | if args.get('tag_no_paired_data'): 89 | self.tag_no_paired_data = args.get('tag_no_paired_data') 90 | else: 91 | self.tag_no_paired_data = True 92 | 93 | if args.get('force_tag_all'): 94 | self.force_tag_all = args.get('force_tag_all') 95 | else: 96 | self.force_tag_all = False 97 | 98 | 99 | class DatasetProcessor: 100 | """ 101 | 构建DatasetProcessor对象以开始数据处理 102 | """ 103 | upscale: UpscaleModel = None 104 | tagger: Tagger = None 105 | option: MainOption = None 106 | 107 | def data_list_builder(self, input_dir: str) -> list[Data]: 108 | ... 109 | 110 | def pair_token(self, token_file_list: list, data_list: list[Data]): 111 | ... 112 | 113 | def __init__(self, 114 | input_dir: str, 115 | output_dir: str, 116 | conduct: dict, 117 | option: dict | None = None, 118 | tagger: dict | None = None, 119 | upscale: dict | None = None 120 | ): 121 | self.input_dir = input_dir 122 | self.conduct = conduct 123 | if not os.path.exists(output_dir): 124 | os.makedirs(output_dir) 125 | self.output_dir = output_dir 126 | if tagger and tagger.get('active'): self.tagger = tagger_builder(tagger) 127 | if upscale and upscale.get('active'): self.upscale = upscale_model_builder(upscale) 128 | if option: 129 | self.option = MainOption(option) 130 | else: 131 | self.option = MainOption() 132 | self.data_list = self.data_list_builder(input_dir) 133 | 134 | # 匹配标签 135 | def pair_token(self, token_file_list: list, data_list: list[Data]): 136 | no_paired_data_list = [] 137 | for data in data_list: 138 | for file_name in token_file_list: 139 | splitext = os.path.splitext(file_name) 140 | name = splitext[0] 141 | if name == data.name: 142 | data.input_token(file_name, self.option) 143 | token_file_list.remove(file_name) 144 | if not data.token: 145 | no_paired_data_list.append(data) 146 | return no_paired_data_list 147 | 148 | # 读取文件并建立列表 149 | def data_list_builder(self, input_dir: str) -> list[Data]: 150 | data_list: list[Data] = [] 151 | token_list = [] 152 | no_paired_data_list = [] 153 | count = 0 154 | print("load files...\n开始读取文件...") 155 | for file_name in tqdm(os.listdir(input_dir)): 156 | splitext = os.path.splitext(file_name) 157 | name = splitext[0] 158 | ext = splitext[1] 159 | if ext in IMG_EXT: 160 | img = Data(input_dir, name, ext) 161 | data_list.append(img) 162 | count += 1 163 | if ext in TEXT_EXT: 164 | token_list.append(file_name) 165 | no_paired_data_list = self.pair_token(token_list, data_list) 166 | token_list.clear() 167 | print( 168 | "一共读取" + str(count) + "张图片,其中有" + 169 | str(no_paired_data_list.__len__()) + "张图片没有配对的标签" 170 | ) 171 | if self.tagger: 172 | if self.option.tag_no_paired_data and no_paired_data_list != []: 173 | print("已启用对未标签的图片进行打标") 174 | self.tagger.tag_data_list(no_paired_data_list) 175 | if self.option.force_tag_all: 176 | print("已强制对所有图片进行机器标注") 177 | self.tagger.tag_data_list(data_list) 178 | return data_list 179 | 180 | # 过滤器管理 181 | def filter_manager(self, filter_list: list, data: Data) -> bool: 182 | flag = False 183 | for filter in filter_list: 184 | fun = getattr(Filter, filter.get('filter')) 185 | if filter.get('arg'): 186 | if fun(data, filter.get('arg')): return True 187 | else: 188 | if fun(data): return True 189 | return False 190 | 191 | # 处理器管理 192 | def processor_manager(self, processor_list: list, data: Data): 193 | for processor in processor_list: 194 | try: 195 | fun = getattr(Processor, processor.get('method')) 196 | if fun == Processor.tag_image: 197 | if self.tagger is None: 198 | raise NoneTaggerError('tag_image') 199 | data = fun(data, self.tagger) 200 | elif fun == Processor.upscale_image: 201 | if self.upscale is None: 202 | raise NoneUpscaleError('upscale_image') 203 | data = fun(data, self.upscale) 204 | elif bool(processor.get("arg")): 205 | data = fun(data, processor.get("arg")) 206 | else: 207 | data = fun(data) 208 | except ProcessorError: 209 | raise ProcessorError 210 | except AttributeError: 211 | print(f"\nError:Invalid method: {processor.get('method')}\nPlease check the config file") 212 | exit(1) 213 | except NoneUpscaleError as e: 214 | print(f"\nError:{e.name} is faild!") 215 | print("Upscale is not active!Please add this commit in config:") 216 | print("======================") 217 | print("upscale:\n active: True") 218 | print("======================") 219 | exit(1) 220 | except NoneTaggerError as e: 221 | print(f"\nError:{e.name} is faild!") 222 | print("Tagger is not active!Please add this commit in config:") 223 | print("======================") 224 | print("Tagger:\n active: True") 225 | print("======================") 226 | exit(1) 227 | return data 228 | 229 | def conduct_manager(self, conducts: list[dict], data_list: list[Data]) -> list[Data]: 230 | """ 231 | 处理行为管理函数,虽然可以接受data_list,但是存在文件名碰撞隐患 232 | 推荐只传入一个data对象 233 | """ 234 | return_list = [] 235 | output_dir = self.output_dir 236 | for conduct in conducts: 237 | if conduct.get('sub_conduct'): 238 | sub_data_list = [copy.copy(data) for data in data_list] 239 | for data in sub_data_list: 240 | data.conduct += "_sub[" 241 | sub_data_list = self.conduct_manager(conduct.get('sub_conduct'), sub_data_list) 242 | if sub_data_list: 243 | for data in sub_data_list: 244 | data.conduct += "]" 245 | data_list = copy.deepcopy(sub_data_list) 246 | if self.option.save_sub: 247 | sub_output = os.path.join(output_dir, "sub") 248 | if not (os.path.exists(sub_output)): 249 | os.mkdir(sub_output) 250 | for sub_data in sub_data_list: 251 | sub_data.save(sub_output, self.option) 252 | for data in data_list: 253 | filters = conduct.get('filters') 254 | if filters: 255 | if self.filter_manager(filters, data): continue 256 | if bool(conduct.get('repeat')): 257 | repeat = conduct.get('repeat') 258 | else: 259 | repeat = 1 260 | for j in range(0, repeat): 261 | data.repeat = j 262 | try: 263 | return_list.append(self.processor_manager(conduct.get('processor'), copy.deepcopy(data))) 264 | except ProcessorError: 265 | break 266 | return return_list 267 | 268 | def main(self): 269 | """ 270 | 主入口 271 | """ 272 | print("开始图片处理...") 273 | for i in tqdm(range(0, len(self.data_list))): 274 | data = self.data_list.pop() 275 | data.id = i 276 | data_list = self.conduct_manager(self.conduct, [data]) 277 | if data_list: 278 | for data in data_list: 279 | data.save(self.output_dir, self.option) 280 | 281 | 282 | class NoneTaggerError(RuntimeError): 283 | def __init__(self, name): 284 | self.name = name 285 | 286 | 287 | class NoneUpscaleError(RuntimeError): 288 | def __init__(self, name): 289 | self.name = name 290 | -------------------------------------------------------------------------------- /doc/doc_cn.md: -------------------------------------------------------------------------------- 1 | # 说明文档 2 | 3 | ## 安装 4 | 5 | 需要安装依赖 6 | 7 | ```txt 8 | python -m venv ./venv 9 | ./venv/Scripts/activate 10 | pip install -r ./requirements.txt 11 | ``` 12 | 13 | 注意:该版本会安装torch相关的一大堆依赖,如果不想要,可以选择激活别的地方的venv后再来运行 14 | *如果你不懂我说的是什么意思那你就照着上面指令用就行了* 15 | 16 | 你也可以选择安装不包含AI处理的[轻量版](https://github.com/waterminer/SD-DatasetProcessor/tree/lite) 17 | 18 | ## 使用方式 19 | 20 | 参考conf文件进行编写 21 | 22 | ```yaml 23 | path: 24 | input: "" #输入路径 25 | output: "" #输出路径 26 | 27 | tagger: #自动打标相关设置 28 | active: True #启用自动打标 29 | batch_size: 4 #批次大小 30 | max_data_loader_n_workers: 1 #越大越占内存 31 | 32 | conduct: 33 | - #处理组1 此处示意为将所有大于512的图片进行翻转 34 | filters: #用于定义过滤器 35 | - #过滤器1 36 | filter: img_filter 37 | arg: [512,-1] 38 | processor: #用于定义处理器 39 | - #处理器1 40 | method: flip 41 | arg: 512 42 | 43 | #以下为进阶示范 44 | - #处理组2 此处示意为将1024~2048区间大小的图片进行缩放然后进行随机裁切 45 | repeat: 3 #用于循环执行(可选) 46 | filters: #用于定义过滤器 47 | - #过滤器1 48 | filter: img_filter 49 | arg: [1024,2048] 50 | processor: #用于定义处理器 51 | - #处理器1 52 | method: resize 53 | arg: 0.5 54 | - #处理器2 55 | method: random_crop 56 | arg: 512 57 | ``` 58 | 59 | 在默认情况下,文件保存名称为:`id_处理id_重复次数.格式` 60 | 比如:`000001_f_0.jpg` 61 | 62 | ## 可选项 63 | 64 | 在yaml中加入option来自定义以下选项 65 | 66 | |名称|说明| 67 | |--|--| 68 | |save_source_name|保存原文件名称| 69 | |save_conduct_id|保存处理id| 70 | |save_sub|保存子处理| 71 | |clean_tag|清洗标签(将"_"换成空格,给括号加上"\"),默认开启| 72 | |tag_no_paired_data|自动对没有标签的图片进行打标,需要配置`tagger`,默认开启| 73 | |force_tag_all|强制对所有图片进行打标,需要配置`tagger`| 74 | 75 | 以下是示例: 76 | 77 | ```yaml 78 | option: 79 | save_sorce_name:True 80 | save_sub:True 81 | ``` 82 | 83 | ## 处理器说明 84 | 85 | ### 图片处理 86 | 87 | |名称|处理id|说明|参数| 88 | | -- | -- | -- | -- | 89 | |random_crop|_rc|随机裁切矩形图片|图片分辨率(整数)| 90 | |flip|_f|水平翻转图片| - | 91 | |resize|_r|按比例重新调整大小|比例(浮点数)| 92 | |force_resize|_fr|将图片缩放至特定大小|数组,输入格式为[x,y]| 93 | |offset|_off|将图片偏移n个像素|偏移量(整数)| 94 | |rotation|_rot|将图片选择n个角度|角度(整数)| 95 | |contrast_enhancement|_con_e|对比度增强|-| 96 | |brightness_enhancement|_bri_e|亮度增强|-| 97 | |color_enhancement|_col_e|饱和度增强|-| 98 | |random_enhancement|_ran_e|随机增强|-| 99 | |none|-|不做操作(用于特定场合)|-| 100 | |upscale_image|-|放大图片,要使用这个方法,请配置`upscale`|-| 101 | 102 | ### 标签处理 103 | 104 | |名称|说明|参数| 105 | | -- | -- | -- | 106 | |append_tag|在标签组末尾加上标签|标签(文本)| 107 | |remove_tag|删除标签组中符合条件的标签|标签(文本)| 108 | |insert_tag|在标签组开头插入标签|标签(文本)| 109 | |tag_move_forward|将选定标签移到开头|标签(文本)| 110 | |rename_tag|重命名标签,将`A标签`重命名为`B标签`|['A标签','B标签']| 111 | |tag_image|对图片进行打标并覆盖原来的标签,要使用这个方法,请配置`tagger`|-| 112 | 113 | ## 过滤器说明 114 | 115 | 负责过滤符合特定条件的数据 116 | 117 | |名称|说明|参数| 118 | | -- | -- | -- | 119 | |img_size|过虑特定尺寸的图片|数组,输入格式为[max,min],缺省填-1 | 120 | |tag_filter|过滤掉特定标签|标签(文本)| 121 | |tag_selector|须要包含特定标签|标签(文本)| 122 | |tag_is_not_none|只含有带标签的图片|-| 123 | |tag_is_none|只含有不带标签的图片|-| 124 | 125 | ## 子处理说明 126 | 127 | 在配置文件`conduct`项中可以添加`sub_conduct`子处理,在运行中会将子处理的结果作为输入返回主处理 128 | 129 | 子处理的编写方式与主处理的编写方式相同。 130 | 131 | 以下是一种子处理的使用示例: 132 | 133 | ```yaml 134 | conduct: 135 | - sub_conduct: #将图片进行随机裁切 136 | - 137 | filters: 138 | - filter: img_size 139 | arg: [1024,1536] 140 | processor: 141 | - method: random_crop 142 | arg: 1024 143 | - 144 | filters: 145 | - filter: img_size 146 | arg: [1536,2048] 147 | processor: 148 | - method: resize 149 | arg: 0.75 150 | - method: random_crop 151 | arg: 1024 152 | processor: 153 | - method: flip #将所有子处理进行翻转 154 | ``` 155 | 156 | 当然,如果你想要的话,你可以在子处理中嵌套子处理,这是完全合法的 157 | 158 | ## 自动打标设置说明 159 | 160 | 在配置中添加添加以下条目即可启用自动打标: 161 | 162 | ``` yaml 163 | Tagger: 164 | active: True 165 | ``` 166 | 167 | 如果你已经全部完成打标了,依旧打开此项会大大拖慢速度(花时间读取模型),所以请结合实际情况自行选择是否打开 168 | 169 | 你可以像这样来配置打标设置: 170 | 171 | ``` yaml 172 | Tagger: 173 | active: True 174 | model_type: WD14_MOAT 175 | ``` 176 | 177 | 如果你不清楚是什么,请保持默认 178 | 179 | ### 配置项说明 180 | 181 | |名称|说明|参数| 182 | |--|--|--| 183 | |active|启用自动打标|布尔值(True/False)| 184 | |model_path|模型路径,下载的模型都会放在此文件夹内|路径| 185 | |model_type|模型种类,具体看下一章|模型种类| 186 | |force_download|强制下载模型|布尔值| 187 | |undesired_tags|排除标签|标签,以英文半角逗号","分隔| 188 | |remove_underscore|以空格替代下划线"_"|布尔值| 189 | |batch_size|每批大小|整数| 190 | |max_data_loader_n_workers|数据读取大小,越大越占内存|整数| 191 | |thresh|置信度,会排除掉比这个值低的标签,默认是0.35|0~1浮点数| 192 | |character_threshold|角色置信度,如果启用,会以这个值单独设置角色标签的推断|0~1浮点数| 193 | |general_threshold|普通标签置信度,如果启用,会以这个值单独设置普通标签置的推断|0~1浮点数| 194 | 195 | ### 自动打标模型种类 196 | 197 | 默认参数为`WD14_CONVNEXT`可以按照喜好自行选择 198 | |值|链接|P=R: threshold|F1| 199 | |--|--|--|--| 200 | |WD14_MOAT|[链接](https://huggingface.co/SmilingWolf/wd-v1-4-moat-tagger-v2)|0.3771|0.6911| 201 | |WD14_VIT|[链接](https://huggingface.co/SmilingWolf/wd-v1-4-vit-tagger-v2)|0.3537|0.6770| 202 | |WD14_SWINV2|[链接](https://huggingface.co/SmilingWolf/wd-v1-4-swinv2-tagger-v2)|0.3771|0.6854| 203 | |WD14_CONVNEXT|[链接](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2)|0.3685|0.6810| 204 | |WD14_CONVNEXT2|[链接](https://huggingface.co/SmilingWolf/wd-v1-4-convnextv2-tagger-v2)|0.3710|0.6862| 205 | 206 | ## 图片放大说明 207 | 208 | 在配置中添加添加以下条目即可启用图片放大: 209 | 210 | ``` yaml 211 | upscale: 212 | active: True 213 | ``` 214 | 215 | 你可以像这样来配置打标设置: 216 | 217 | ``` yaml 218 | upscale: 219 | active: True 220 | model_type: R_CUGAN_2X_CON 221 | ``` 222 | 223 | 如果你不清楚是什么,请保持默认 224 | 225 | ### 配置项说明 226 | 227 | |名称|说明|参数| 228 | |--|--|--| 229 | |active|启用自动图片放大|布尔值| 230 | |model_path|模型路径,下载的模型都会放在此文件夹内(仅适用于Real_ESRGAN)|路径| 231 | |model_type|模型种类,具体看下一章|模型种类| 232 | |force_download|强制下载模型(仅适用于Real_ESRGAN)|布尔值| 233 | |tile|切分图片,减少显存占用,0为不裁切,默认是512|每块切片的分辨率(整型)| 234 | |tile_pad|切分pad尺寸,用于减轻合并伪影,默认是10(仅适用于Real_ESRGAN)|pad分辨率(整型)| 235 | |pre_pad|pad填充像素,用于减轻合并伪影,默认是10(仅适用于Real_ESRGAN)|pad填充像素(整型)| 236 | |half|半精度,如果您是20系或者更高,推荐打开来加速(仅适用于Real_ESRGAN)|布尔值| 237 | 238 | ### 放大模型种类 239 | 240 | 默认参数为`R_ESRGAN_2X`可以按照喜好自行选择 241 | 242 | |值|说明| 243 | |--|--| 244 | |R_ESRGAN_2X|Real_ESRGAN算法,2X代表2倍放大,下同| 245 | |R_ESRGAN_4X|-| 246 | |R_ESRGAN_8X|-| 247 | |R_ESRNET_4X|仅在Real_ESRGAN库中支持,作者尚未验证| 248 | |R_ESRGAN_ANIME6B_4X|Real_ESRGAN针对二次元训练的算法,仅有4X放大| 249 | |R_CUGAN_2X_CON|Real_CUGAN算法,针对二次元的AI放大算法,2X代表2倍放大,CON代表保守降噪策略,推荐原图清晰度较高下使用| 250 | |R_CUGAN_2X_ND|同上,ND代表不降噪,推荐原图清晰度非常高的情况下使用| 251 | |R_CUGAN_2X_D3|同上,D3代表3级降噪,等级越高降噪程度越高,仅有2X模型降噪分为三个等级,其余均只有3级降噪,推荐原图清晰度不高的情况下使用| 252 | |R_CUGAN_2X_D2|-| 253 | |R_CUGAN_2X_D1|-| 254 | |R_CUGAN_3X_CON|-| 255 | |R_CUGAN_3X_ND|-| 256 | |R_CUGAN_3X_D3|-| 257 | |R_CUGAN_4X_CON|-| 258 | |R_CUGAN_4X_ND|-| 259 | |R_CUGAN_4X_D3|-| 260 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from dataset_processor import * 2 | 3 | import yaml 4 | from argparse import ArgumentParser 5 | 6 | if __name__ == "__main__": 7 | parser = ArgumentParser() 8 | parser.add_argument( 9 | '--input_dir', 10 | default=None, 11 | type=str, 12 | help='input dir,if used,it will cover config ''input_dir''//数据集输入路径,如果指定则会覆盖配置文件中的''input_dir''' 13 | ) 14 | parser.add_argument( 15 | '--output_dir', 16 | default=None, 17 | type=str, 18 | help='output dir,if used,it will cover config ''output_dir''//数据集输入路径,如果指定则会覆盖配置文件中的''output_dir''' 19 | ) 20 | parser.add_argument( 21 | '--config', 22 | default='./conf.yaml', 23 | type=str, 24 | help='yaml config path,default to reading conf.yaml in the root directory//指定yaml配置文件,默认读取根目录下conf.yaml' 25 | ) 26 | args = parser.parse_args() 27 | with open(args.config, "r", encoding="utf-8") as f: 28 | config = yaml.load(f.read(), yaml.FullLoader) 29 | # 设置 30 | if args.input_dir: 31 | input_dir = args.input_dir 32 | else: 33 | input_dir = config.get('path').get('input') # 输入目录 34 | if args.input_dir: 35 | output_dir = args.output_dir 36 | else: 37 | output_dir = config.get('path').get('output') # 输出目录 38 | # 参数 39 | conducts = config.get('conduct') 40 | option = config.get('option') 41 | tagger = config.get('tagger') 42 | upscale = config.get('upscale') 43 | DatasetProcessor(input_dir,output_dir,conducts,option,tagger,upscale).main() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch~=2.0.1 2 | numpy~=1.24.3 3 | opencv-python~=4.8.0.74 4 | keras~=2.13.1 5 | tqdm~=4.65.0 6 | Pillow~=10.0.0 7 | PyYAML~=6.0.1 8 | huggingface_hub 9 | tensorflow 10 | realesrgan 11 | realcugan-ncnn-py -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | import os 3 | 4 | requires = [] 5 | with open('requirements.txt', encoding='utf8') as f: 6 | for x in f.readlines(): 7 | requires.append(f'{x.strip()}') 8 | 9 | data_files = [('conf',['conf.yaml'])] 10 | 11 | for f in os.listdir('./doc'): 12 | data_files.append(('doc',['doc/'+f])) 13 | 14 | setup( 15 | name='dataset_processor', 16 | version='0.3.0', 17 | packages=['dataset_processor', 'dataset_processor.tools'], 18 | url='https://github.com/waterminer/SD-DatasetProcessor', 19 | license='GPLv3', 20 | author='Water_miner', 21 | author_email='420773173@qq.com', 22 | description='A dataset preprocess toolkit', 23 | classifiers=[ 24 | 'Development Status :: 3 - Alpha', 25 | 'Environment :: GPU :: NVIDIA CUDA :: 11.8', 26 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 27 | 'Programming Language :: Python :: 3.10', 28 | ], 29 | install_requires=requires, 30 | data_files=data_files 31 | ) 32 | 33 | --------------------------------------------------------------------------------