├── .github └── workflows │ └── build.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── api ├── add.go ├── chat.go ├── delete.go ├── html.go ├── info.go ├── post.go ├── query.go ├── scan.go ├── set.go └── user.go ├── assets ├── dist │ ├── favicon.ico │ ├── index.css │ ├── index.html │ └── index.js └── templates │ └── index.html ├── config.toml ├── docker-compose.yaml ├── go.mod ├── go.sum ├── main.go ├── middleware ├── auth.go ├── cors.go └── limit.go ├── model ├── config.go ├── items.go ├── posts.go └── wp_posts.go ├── router └── routers.go └── utils ├── cache.go ├── config.go ├── crontab.go ├── helper.go ├── log.go ├── test.go.bak ├── validation.go └── version.go /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and push Docker image with CGO 2 | 3 | on: 4 | workflow_dispatch: # 手动触发 workflow 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@v3 13 | 14 | - name: Set up Go 15 | uses: actions/setup-go@v3 16 | with: 17 | go-version: '1.23.2' # 或者您需要的 Go 版本 18 | 19 | - name: Install CGO dependencies 20 | run: | 21 | sudo apt-get update 22 | sudo apt-get install -y build-essential upx 23 | 24 | - name: Build with CGO 25 | run: | 26 | export CGO_ENABLED=1 27 | go build -o wp2ai -ldflags -w main.go 28 | upx -9 wp2ai 29 | 30 | - name: Set up Docker Buildx 31 | uses: docker/setup-buildx-action@v2 32 | 33 | - name: Login to Docker Hub 34 | uses: docker/login-action@v2 35 | with: 36 | username: ${{ secrets.DOCKERHUB_USERNAME }} 37 | password: ${{ secrets.DOCKERHUB_TOKEN }} 38 | 39 | - name: Build and push Docker image 40 | id: docker_build 41 | uses: docker/build-push-action@v3 42 | with: 43 | context: . 44 | push: true 45 | tags: ${{ secrets.DOCKERHUB_USERNAME }}/wp2ai:latest -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | data/* 2 | package.sh 3 | wp2ai 4 | wp2ai.* -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:12-slim 2 | RUN mkdir -p /opt/wp2ai/data && apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* 3 | WORKDIR /opt/wp2ai 4 | COPY wp2ai config.toml /opt/wp2ai/ 5 | COPY assets /opt/wp2ai/assets 6 | # 暴露文件夹和端口 7 | EXPOSE 2080 8 | # 启动程序 9 | CMD ["./wp2ai", "start"] -------------------------------------------------------------------------------- /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 | # WP2AI 2 | 3 | WP2AI可以将您的WordPress文章变成智能知识库,并通过AI智能匹配和解读,使其更准确的回答问题。 4 | 5 | > 演示地址:[https://ai.xiaoz.top/](https://ai.xiaoz.top/) 6 | 7 | ### 功能特点 8 | 9 | - [x] 扫描WordPress文章 10 | - [x] 向量化WordPress文章数据 11 | - [x] AI问答搜索 12 | - [x] 后台管理 13 | - [x] API接口 14 | - [ ] WordPress插件(用于自动添加、更新、删除文章索引) 15 | - [ ] 后台文章管理支持状态分类和重试 16 | - [ ] 自动翻译文章 17 | - [ ] 记录用户问答记录 18 | 19 | 20 | ### 适用场景 21 | 22 | * 需要提升站内搜索效率的博客网站 23 | * 拥有大量专业知识内容的在线平台 24 | * 希望为用户提供更优质搜索服务的企业网站 25 | 26 | ### 部分截图 27 | 28 | ![0771f4d41f551d81.png](https://img.rss.ink/imgs/2025/03/02/0771f4d41f551d81.png) 29 | 30 | ![ba02206bb4893bce.png](https://img.rss.ink/imgs/2025/03/02/ba02206bb4893bce.png) 31 | 32 | ![0127483b258c677c.png](https://img.rss.ink/imgs/2025/03/02/0127483b258c677c.png) 33 | 34 | ![dfd708b02006a65b.png](https://img.rss.ink/imgs/2025/03/02/dfd708b02006a65b.png) 35 | 36 | ### 安装 37 | 38 | 目前仅支持Docker安装,请确保您已经安装Docker环境。 39 | 40 | **方式一:Docker Compose安装** 41 | 42 | `docker-compose.yaml`内容如下: 43 | 44 | ```yaml 45 | version: '3' 46 | services: 47 | wp2ai: 48 | container_name: wp2ai 49 | volumes: 50 | - '/opt/wp2ai/data:/opt/wp2ai/data' 51 | network_mode: "host" 52 | restart: always 53 | image: 'helloz/wp2ai' 54 | ``` 55 | 56 | 注意上面使用了HOST网络模式,安装完毕后您需要在防火墙或安全组放行`2080`端口。如果WP2AI和WordPress不在同一服务器,也可以使用`bridge`网络模式,只需要注释掉`network_mode`并自定义端口,比如: 57 | 58 | ```yaml 59 | version: '3' 60 | services: 61 | wp2ai: 62 | container_name: wp2ai 63 | volumes: 64 | - '/opt/wp2ai/data:/opt/wp2ai/data' 65 | ports: 66 | - '2080:2080' 67 | image: 'helloz/wp2ai' 68 | restart: always 69 | ``` 70 | 71 | **方式二:Docker命令行安装** 72 | 73 | 使用HOST网络模式,需要自行放行`2080`端口! 74 | 75 | ```bash 76 | docker run -d \ 77 | --name wp2ai \ 78 | -v /opt/wp2ai/data:/opt/wp2ai/data \ 79 | --network host \ 80 | --restart always \ 81 | helloz/wp2ai 82 | ``` 83 | 84 | 使用`network_mode`模式,可自定义访问端口: 85 | 86 | ```bash 87 | docker run -d \ 88 | --name wp2ai \ 89 | -v /opt/wp2ai/data:/opt/wp2ai/data \ 90 | -p 2080:2080 \ 91 | --restart always \ 92 | helloz/wp2ai 93 | ``` 94 | 95 | > 注意:如果您无法从Docker拉取镜像,可以使用我们提供的镜像加速地址:`pub.tcp.mk/helloz/wp2ai` 96 | 97 | ### 使用 98 | 99 | 1. 安装完毕后访问 `http://IP:2080` 根据提示完成初始化 100 | 2. 在后台【参数设置】,填写WordPress数据、向量模型、AI模型等信息 101 | 3. 在后台【文章数据 - 批量扫描】,将WrdPress扫描入库,期间系统会自动向量化数据(1分钟大约处理15条) 102 | 4. 等等数据处理完毕,在【后台 - AI检索】或者网站首页进行问答测试 103 | 104 | **相关地址:** 105 | 106 | * 登录:`/login` 107 | * 后台管理:`/admin` 108 | 109 | ### 其他产品 110 | 111 | 如果您有兴趣,还可以了解我们的其他产品。 112 | 113 | * [Zdir](https://www.zdir.pro/zh/) - 一款轻量级、多功能的文件分享程序。 114 | * [OneNav](https://www.onenav.top/) - 高效的浏览器书签管理工具,将您的书签集中式管理。 115 | * [ImgURL](https://www.imgurl.org/) - 2017年上线的免费图床。 116 | 117 | ### 安装服务 118 | 119 | WP2AI目前是免费开源的,但是我们也提供付费安装服务,如果需要我们协助部署,请联系微信:`xiaozme`,收费为`80元/次` 120 | 121 | ### 联系我们 122 | 123 | QQ交流群:`964597848` 124 | 125 | ![ba55b32730f40f20.jpg](https://img.rss.ink/imgs/2025/02/28/ba55b32730f40f20.jpg) 126 | 127 | 微信交流群 128 | 129 | ![a2d8db876cf58e15.jpg](https://img.rss.ink/imgs/2025/03/03/a2d8db876cf58e15.jpg) -------------------------------------------------------------------------------- /api/add.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "strconv" 5 | "wp2ai/model" 6 | 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | // 添加单个数据 11 | func AddPost(c *gin.Context) { 12 | // 通过POST获取id 13 | id := c.PostForm("id") 14 | // 将id转为utint 15 | idUint64, err := strconv.ParseUint(id, 10, 0) 16 | idUint := uint(idUint64) 17 | if err != nil { 18 | c.JSON(200, gin.H{ 19 | "code": -1000, 20 | "msg": "Invalid id", 21 | "data": "", 22 | }) 23 | c.Abort() 24 | return 25 | } 26 | 27 | // 获取文章 28 | wpPost, _ := model.GetWpPostById(idUint) 29 | // 如果post为空 30 | if wpPost == nil { 31 | c.JSON(200, gin.H{ 32 | "code": -1000, 33 | "msg": "Post not found", 34 | "data": "", 35 | }) 36 | c.Abort() 37 | return 38 | } 39 | 40 | var post model.Post 41 | post.PostID = wpPost.ID 42 | post.PostTitle = wpPost.PostTitle 43 | post.PostDate = wpPost.PostDate 44 | post.PostContent = wpPost.PostContent 45 | post.Status = 0 46 | 47 | // 插入数据库 48 | err = model.InsertPost(post) 49 | // 如果出错 50 | if err != nil { 51 | c.JSON(200, gin.H{ 52 | "code": 500, 53 | "msg": "Insert failed", 54 | "data": "", 55 | }) 56 | c.Abort() 57 | return 58 | } 59 | // 成功了 60 | c.JSON(200, gin.H{ 61 | "code": 200, 62 | "msg": "success", 63 | "data": "", 64 | }) 65 | } 66 | -------------------------------------------------------------------------------- /api/chat.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "strconv" 10 | "wp2ai/model" 11 | "wp2ai/utils" 12 | 13 | "github.com/gin-gonic/gin" 14 | "github.com/sashabaranov/go-openai" 15 | "github.com/spf13/viper" 16 | ) 17 | 18 | // json结构体 19 | type Input struct { 20 | Type string `json:"type"` 21 | Msg string `json:"msg"` 22 | } 23 | 24 | var ChatClient *openai.Client 25 | 26 | func Chat(c *gin.Context) { 27 | var inputs []Input 28 | // 绑定json数据 29 | if err := c.ShouldBindJSON(&inputs); err != nil { 30 | // 返回错误信息 31 | c.JSON(200, gin.H{ 32 | "code": 500, 33 | "msg": "Incorrect format!", 34 | "data": "", 35 | }) 36 | c.Abort() 37 | return 38 | } 39 | var extMsg []openai.ChatCompletionMessage 40 | // 遍历inputs 41 | for _, input := range inputs { 42 | // 判断type是否为user 43 | if input.Type == "user" { 44 | // 添加到extMsg中 45 | extMsg = append(extMsg, openai.ChatCompletionMessage{ 46 | Role: openai.ChatMessageRoleUser, 47 | Content: input.Msg, 48 | }) 49 | } else if input.Type == "ai" { 50 | // 添加到extMsg中 51 | extMsg = append(extMsg, openai.ChatCompletionMessage{ 52 | Role: openai.ChatMessageRoleAssistant, 53 | Content: input.Msg, 54 | }) 55 | 56 | } 57 | } 58 | // 取出最后一个元素(用户的输入) 59 | input := extMsg[len(extMsg)-1].Content 60 | // 删除extMsg最后一个元素 61 | // extMsg = extMsg[:len(extMsg)-1] 62 | // 通过Post获取用户输入 63 | // input := c.PostForm("input") 64 | // fmt.Println(input) 65 | 66 | modelName := viper.GetString("openai.model") 67 | // 初始化客户端 68 | InitChatClient() 69 | 70 | // 将用户最后输入的内容向量化 71 | embedding, err := utils.DataEmbedding(input) 72 | // fmt.Println(embedding) 73 | // 如果出现错误 74 | if err != nil { 75 | // 返回错误信息 76 | c.JSON(200, gin.H{ 77 | "code": 500, 78 | "msg": "Data embedding failed", 79 | "data": "", 80 | }) 81 | // 终止 82 | c.Abort() 83 | return 84 | } 85 | // 查询出匹配的数据 86 | results, err := model.GetDocument(embedding) 87 | 88 | // 写入日志 89 | utils.WriteLog(fmt.Sprintf("GetDocument error: %v", err)) 90 | // 如果出现错误 91 | if err != nil { 92 | // 返回错误信息 93 | c.JSON(200, gin.H{ 94 | "code": 500, 95 | "msg": "Get document failed", 96 | "data": "", 97 | }) 98 | // 终止 99 | c.Abort() 100 | return 101 | } 102 | var messages []openai.ChatCompletionMessage 103 | messages = append(messages, openai.ChatCompletionMessage{ 104 | Role: openai.ChatMessageRoleSystem, 105 | Content: "你是一名AI助手,名字叫WP2AI,以下是一些资料,你需要先理解并掌握。然后根据掌握的资料来回答问题,如果用户的问题不在资料中,你需要拒绝回答。", 106 | }) 107 | // 引用结果 108 | quotes := " \n \n> **引用内容:** \n " 109 | // fmt.Println(results) 110 | // 遍历结果 111 | allDistancesLarge := true // 标记是否所有 Distance 都大于等于 1.0 112 | 113 | // 检查是否所有 Distance 都大于等于 1.0 114 | for _, result := range results { 115 | if result.Distance < 1.0 { 116 | allDistancesLarge = false 117 | break 118 | } 119 | } 120 | // 部分向量模型数值原因,暂时停用这个功能 121 | allDistancesLarge = false 122 | 123 | // 如果所有allDistancesLarge都大于1.0,则去掉results最后2行 124 | if allDistancesLarge { 125 | results = results[:len(results)-2] 126 | } 127 | 128 | domain := viper.GetString("wordpress.domain") 129 | 130 | for index, result := range results { 131 | // fmt.Println(result.Distance) 132 | // 添加前缀 133 | prefix := fmt.Sprintf("资料%d:", index+1) 134 | // 添加到messages中 135 | messages = append(messages, openai.ChatCompletionMessage{ 136 | Role: openai.ChatMessageRoleSystem, 137 | Content: prefix + result.Content, 138 | }) 139 | quotes += fmt.Sprintf("> %v. [%v](%v/?p=%v) \n ", index+1, result.Title, domain, result.PostID) 140 | } 141 | // 组合消息,已经学习的内容 + 前端传递的内容 142 | // messages = append(messages, extMsg...) 143 | // 最后一次用户输入的内容 144 | messages = append(messages, openai.ChatCompletionMessage{ 145 | Role: openai.ChatMessageRoleUser, 146 | Content: input, 147 | }) 148 | 149 | // fmt.Println(messages) 150 | 151 | // 设置响应header头 152 | c.Writer.Header().Set("Content-Type", "text/event-stream") 153 | c.Writer.Header().Set("Cache-Control", "no-cache") 154 | c.Writer.Header().Set("Connection", "keep-alive") 155 | 156 | ctx := context.Background() 157 | req := openai.ChatCompletionRequest{ 158 | Model: modelName, 159 | Messages: messages, 160 | Stream: true, 161 | } 162 | // fmt.Println(messages) 163 | stream, err := ChatClient.CreateChatCompletionStream(ctx, req) 164 | if err != nil { 165 | fmt.Println(err) 166 | c.SSEvent("data", toJsonStr(fmt.Sprintf("ChatCompletionStream error: %v", err))) 167 | c.Writer.Flush() // 添加这一行来刷新缓冲区 168 | c.SSEvent("close", "[DONE]") 169 | c.Writer.Flush() // 添加这一行来刷新缓冲区 170 | c.Abort() 171 | return 172 | } 173 | 174 | // fmt.Println("dsdsd") 175 | // 输出消息 176 | for { 177 | response, err := stream.Recv() 178 | if errors.Is(err, io.EOF) { 179 | c.SSEvent("data", toJsonStr(quotes)) 180 | c.Writer.Flush() // 添加这一行来刷新缓冲区 181 | c.SSEvent("close", "[DONE]") 182 | c.Writer.Flush() // 添加这一行来刷新缓冲区 183 | // 请求次数+1 184 | ChatCount(c) 185 | return 186 | } 187 | 188 | if err != nil { 189 | c.SSEvent("data", toJsonStr(fmt.Sprintf("Stream error: %v", err))) 190 | c.Writer.Flush() // 添加这一行来刷新缓冲区 191 | c.SSEvent("close", "[DONE]") 192 | c.Writer.Flush() // 添加这一行来刷新缓冲区 193 | c.Abort() 194 | return 195 | } 196 | 197 | // 获得接口返回的内容 198 | content := response.Choices[0].Delta.Content 199 | // 追加流消息 200 | // data += content 201 | c.SSEvent("data", toJsonStr(content)) 202 | c.Writer.Flush() // 添加这一行来刷新缓冲区 203 | } 204 | // 可选:发送完成标志 205 | // c.SSEvent("close", "[DONE]") 206 | // c.Writer.Flush() // 添加这一行来刷新缓冲区 207 | 208 | } 209 | 210 | // 初始化AI客户端 211 | func InitChatClient() { 212 | config := openai.DefaultConfig(viper.GetString("openai.key")) 213 | apiURL := viper.GetString("openai.url") 214 | // modelName := viper.GetString("openai.model") 215 | config.BaseURL = apiURL 216 | // 判断ChatClient是否为空 217 | if ChatClient == nil { 218 | // 初始化ChatClient 219 | ChatClient = openai.NewClientWithConfig(config) 220 | // 初始化成功提示 221 | fmt.Printf("ChatClient connection succeeded!\n") 222 | } 223 | } 224 | 225 | // 将字符串转为json字符串输出 226 | func toJsonStr(input string) string { 227 | data := struct { 228 | V string `json:"v"` 229 | }{ 230 | V: input, 231 | } 232 | 233 | jsonData, err := json.Marshal(data) 234 | if err != nil { 235 | return "" 236 | } 237 | 238 | return string(jsonData) 239 | } 240 | 241 | // 让对话次数+1 242 | func ChatCount(c *gin.Context) { 243 | // 获取访客的IP 244 | ip := utils.GetClientIP(c) 245 | // 设置一个key 246 | key := fmt.Sprintf("limit_chat:%s", ip) 247 | // key转为[]byte 248 | keyByte := []byte(key) 249 | // 从内存中获取 250 | value, _ := utils.Cache.Get(keyByte) 251 | // 如果为空 252 | if value == nil { 253 | return 254 | } 255 | // 如果不为空,则把value转为int 256 | valueStr := string(value) 257 | count, _ := strconv.Atoi(valueStr) 258 | // 打印次数 259 | // fmt.Println(count) 260 | // 次数+1 261 | count++ 262 | // 设置一个值 263 | err := utils.Cache.Set(keyByte, []byte(strconv.Itoa(count)), 60*60*24) 264 | if err != nil { 265 | // 写入日志 266 | utils.WriteLog(fmt.Sprintf("%s", err)) 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /api/delete.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "strconv" 5 | "wp2ai/model" 6 | 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | // 清空所有数据 11 | func DeleteAll(c *gin.Context) { 12 | // 清空posts表 13 | err := model.TruncatePosts() 14 | // 如果出错 15 | if err != nil { 16 | c.JSON(200, gin.H{ 17 | "code": 500, 18 | "msg": "Delete posts failed", 19 | "data": "", 20 | }) 21 | c.Abort() 22 | return 23 | } 24 | // 继续清空 25 | err = model.TruncateItems() 26 | // 如果出错 27 | if err != nil { 28 | c.JSON(200, gin.H{ 29 | "code": 500, 30 | "msg": "Delete embedding failed", 31 | "data": "", 32 | }) 33 | c.Abort() 34 | return 35 | } 36 | 37 | // 返回结果 38 | c.JSON(200, gin.H{ 39 | "code": 200, 40 | "msg": "success", 41 | "data": "", 42 | }) 43 | 44 | } 45 | 46 | // 删除单个数据 47 | func DeletePost(c *gin.Context) { 48 | // 通过POST获取id 49 | id := c.PostForm("id") 50 | // 将id转为utint 51 | idUint64, err := strconv.ParseUint(id, 10, 0) 52 | idUint := uint(idUint64) 53 | if err != nil { 54 | c.JSON(200, gin.H{ 55 | "code": -1000, 56 | "msg": "Invalid id", 57 | "data": "", 58 | }) 59 | c.Abort() 60 | return 61 | } 62 | 63 | err = model.DeletePost(idUint) 64 | // 如果出错 65 | if err != nil { 66 | c.JSON(200, gin.H{ 67 | "code": 500, 68 | "msg": "Delete failed", 69 | "data": "", 70 | }) 71 | c.Abort() 72 | return 73 | } 74 | 75 | // 继续删除,只管删除,不管是否成功 76 | err = model.DeleteItem(id) 77 | 78 | // 返回结果 79 | c.JSON(200, gin.H{ 80 | "code": 200, 81 | "msg": "success", 82 | "data": "", 83 | }) 84 | 85 | } 86 | -------------------------------------------------------------------------------- /api/html.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "net/http" 5 | "wp2ai/utils" 6 | 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func Home(c *gin.Context) { 11 | c.HTML(http.StatusOK, "index.html", gin.H{ 12 | "version": utils.Version, 13 | "date": utils.VersionDate, 14 | }) 15 | } 16 | -------------------------------------------------------------------------------- /api/info.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "wp2ai/utils" 5 | 6 | "github.com/gin-gonic/gin" 7 | "github.com/spf13/viper" 8 | ) 9 | 10 | // 需要授权,给管理员使用 11 | func AppInfo(c *gin.Context) { 12 | var data = map[string]string{ 13 | "app.doc_limit": viper.GetString("app.doc_limit"), 14 | "app.chat_limit": viper.GetString("app.chat_limit"), 15 | "wordpress.domain": viper.GetString("wordpress.domain"), 16 | "embedding.key": viper.GetString("embedding.key"), 17 | "embedding.url": viper.GetString("embedding.url"), 18 | "embedding.model": viper.GetString("embedding.model"), 19 | "openai.key": viper.GetString("openai.key"), 20 | "openai.url": viper.GetString("openai.url"), 21 | "openai.model": viper.GetString("openai.model"), 22 | "wordpress.db_host": viper.GetString("wordpress.db_host"), 23 | "wordpress.db_name": viper.GetString("wordpress.db_name"), 24 | "wordpress.db_password": viper.GetString("wordpress.db_password"), 25 | "wordpress.db_username": viper.GetString("wordpress.db_username"), 26 | "version": utils.Version, 27 | "email": viper.GetString("auth.email"), 28 | } 29 | 30 | c.JSON(200, gin.H{ 31 | "code": 200, 32 | "msg": "success", 33 | "data": data, 34 | }) 35 | } 36 | 37 | // 无需授权,给访客使用 38 | func SiteInfo(c *gin.Context) { 39 | isInit := "yes" 40 | // 检查系统是否初始化 41 | email := viper.GetString("auth.email") 42 | password := viper.GetString("auth.password") 43 | // 如果两个都为空,则系统未初始化 44 | if email == "" && password == "" { 45 | isInit = "no" 46 | } 47 | var data = map[string]string{ 48 | "wp_domain": viper.GetString("wordpress.domain"), 49 | "is_init": isInit, 50 | } 51 | 52 | c.JSON(200, gin.H{ 53 | "code": 200, 54 | "msg": "success", 55 | "data": data, 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /api/post.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "strconv" 5 | "wp2ai/model" 6 | 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | // 声明一个结构体,用于返回信息 11 | type RePost struct { 12 | Posts []model.Post `json:"posts"` 13 | Count int `json:"count"` 14 | Page int `json:"page"` 15 | Limit int `json:"limit"` 16 | } 17 | 18 | // 显示所有文章 19 | func PostList(c *gin.Context) { 20 | // 获取页码 21 | page := c.DefaultQuery("page", "1") 22 | // 获取每页数量 23 | limit := c.DefaultQuery("limit", "10") 24 | // 转为int 25 | pageInt, _ := strconv.Atoi(page) 26 | limitInt, _ := strconv.Atoi(limit) 27 | 28 | // fmt.Println(pageInt, limitInt) 29 | var rePost RePost 30 | // 查询数据 31 | posts, err := model.GetPostsByPage(pageInt, limitInt) 32 | 33 | // fmt.Println("dsd", posts) 34 | 35 | if err != nil { 36 | c.JSON(500, gin.H{ 37 | "code": 500, 38 | "msg": "Query failed", 39 | "data": "", 40 | }) 41 | c.Abort() 42 | return 43 | } 44 | 45 | rePost.Posts = posts 46 | rePost.Count = model.CountPosts(-1) 47 | rePost.Page = pageInt 48 | rePost.Limit = limitInt 49 | 50 | // 返回结果 51 | c.JSON(200, gin.H{ 52 | "code": 200, 53 | "msg": "success", 54 | "data": rePost, 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /api/query.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "wp2ai/model" 6 | "wp2ai/utils" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func Query(c *gin.Context) { 12 | // 通过GET获取keywords 13 | keywords := c.Query("keywords") 14 | 15 | // 向量化 16 | input, err := utils.DataEmbedding(keywords) 17 | if err != nil { 18 | utils.WriteLog(err.Error()) 19 | c.JSON(500, gin.H{ 20 | "code": 500, 21 | "msg": "Data embedding failed", 22 | "data": "", 23 | }) 24 | c.Abort() 25 | return 26 | } 27 | // 查询数据 28 | result, err := model.GetDocument(input) 29 | fmt.Println(err) 30 | if err != nil { 31 | utils.WriteLog(err.Error()) 32 | c.JSON(500, gin.H{ 33 | "code": 500, 34 | "msg": "Query failed", 35 | "data": "", 36 | }) 37 | c.Abort() 38 | return 39 | } 40 | // 返回结果 41 | c.JSON(200, gin.H{ 42 | "code": 200, 43 | "msg": "success", 44 | "data": result, 45 | }) 46 | } 47 | -------------------------------------------------------------------------------- /api/scan.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "wp2ai/model" 6 | "wp2ai/utils" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func Index(c *gin.Context) { 12 | c.JSON(200, gin.H{ 13 | "code": 200, 14 | "msg": "Hello World", 15 | "data": "", 16 | }) 17 | } 18 | 19 | // 批量扫描WordPress中的文章ID,然后入库 20 | func BatchScan(c *gin.Context) { 21 | // 再次初始化一次 22 | model.InitWPDB() 23 | // 获取现有行数 24 | count := model.CountPosts(-1) 25 | // 如果行数大于0,说明已经扫描过了,不需要再扫描 26 | if count > 0 { 27 | c.JSON(200, gin.H{ 28 | "code": -1000, 29 | "msg": "已经扫描过了,请勿重复扫描!", 30 | "data": "", 31 | }) 32 | c.Abort() 33 | return 34 | } 35 | postIds := model.GetPostIds() 36 | 37 | var posts []model.Post 38 | var post model.Post 39 | // 遍历postIds,把所有id全部给posts 40 | for _, postId := range postIds { 41 | post.PostID = postId.ID 42 | posts = append(posts, post) 43 | } 44 | // 插入到数据库中 45 | err := model.InsertPosts(posts) 46 | if err != nil { 47 | utils.WriteLog(fmt.Sprintf("批量插入文章ID失败:%v", err)) 48 | c.JSON(200, gin.H{ 49 | "code": 500, 50 | "msg": "Scan failed", 51 | "data": "", 52 | }) 53 | c.Abort() 54 | return 55 | } 56 | // 返回结果 57 | c.JSON(200, gin.H{ 58 | "code": 200, 59 | "msg": "success", 60 | "data": len(posts), 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /api/set.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "wp2ai/model" 5 | 6 | "github.com/gin-gonic/gin" 7 | "github.com/spf13/viper" 8 | ) 9 | 10 | // 设置配置 11 | func SetConfig(c *gin.Context) { 12 | var data map[string]interface{} 13 | if err := c.ShouldBindJSON(&data); err != nil { 14 | c.JSON(200, gin.H{ 15 | "code": 500, 16 | "msg": "Incorrect format!", 17 | "data": "", 18 | }) 19 | c.Abort() 20 | return 21 | } 22 | 23 | // 遍历 JSON 数据 24 | for key, value := range data { 25 | // 设置配置 26 | viper.Set(key, value) 27 | // 写入配置 28 | err := viper.WriteConfig() 29 | if err != nil { 30 | c.JSON(200, gin.H{ 31 | "code": 500, 32 | "msg": "Failed to write config!", 33 | "data": "", 34 | }) 35 | c.Abort() 36 | return 37 | } 38 | 39 | // 如果key == db_name 40 | if key == "wordpress.db_name" { 41 | // 清空WP 42 | model.WP = nil 43 | // 重新初始化 44 | go model.InitWPDB() 45 | } 46 | 47 | // 如果key ==openai.key 48 | if key == "openai.key" { 49 | // 清空ChatClient 50 | ChatClient = nil 51 | // 重新初始化 52 | go InitChatClient() 53 | } 54 | } 55 | c.JSON(200, gin.H{ 56 | "code": 200, 57 | "msg": "success", 58 | "data": "", 59 | }) 60 | } 61 | -------------------------------------------------------------------------------- /api/user.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "strings" 5 | "wp2ai/utils" 6 | 7 | "github.com/gin-gonic/gin" 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | // 初始化用户名 12 | func InitUser(c *gin.Context) { 13 | // 通过POST获取用户名 14 | email := c.PostForm("email") 15 | // 转为小写 16 | email = strings.ToLower(email) 17 | // 通过POST获取密码 18 | password := c.PostForm("password") 19 | 20 | // 获取配置文件中的邮箱和密码 21 | configEmail := viper.GetString("auth.email") 22 | configPassword := viper.GetString("auth.password") 23 | 24 | // 如果邮箱和密码其中一个不为空,则不允许初始化 25 | if configEmail != "" || configPassword != "" { 26 | c.JSON(200, gin.H{ 27 | "code": -1000, 28 | "msg": "The system has been initialized", 29 | "data": "", 30 | }) 31 | c.Abort() 32 | return 33 | } 34 | 35 | // 验证邮箱是否有效 36 | if !utils.IsEmail(email) { 37 | c.JSON(200, gin.H{ 38 | "code": -1000, 39 | "msg": "Invalid email address", 40 | "data": "", 41 | }) 42 | c.Abort() 43 | return 44 | } 45 | 46 | // 验证密码是否有效 47 | if !utils.IsPassword(password) { 48 | c.JSON(200, gin.H{ 49 | "code": -1000, 50 | "msg": "Invalid password", 51 | "data": "", 52 | }) 53 | c.Abort() 54 | return 55 | } 56 | 57 | passTxt := email + password + "wp2ai" 58 | // 生成MD5哈希 59 | passHash := utils.MD5(passTxt) 60 | 61 | // 写入配置文件 62 | if !utils.SetConfigStr("auth.email", email) { 63 | c.JSON(200, gin.H{ 64 | "code": -1000, 65 | "msg": "Failed to write configuration file", 66 | "data": "", 67 | }) 68 | c.Abort() 69 | return 70 | } 71 | // 写入密码 72 | if !utils.SetConfigStr("auth.password", passHash) { 73 | c.JSON(200, gin.H{ 74 | "code": -1000, 75 | "msg": "Failed to write configuration file", 76 | "data": "", 77 | }) 78 | c.Abort() 79 | return 80 | } 81 | // 提示成功 82 | c.JSON(200, gin.H{ 83 | "code": 200, 84 | "msg": "success", 85 | "data": "", 86 | }) 87 | } 88 | 89 | // 用户登录 90 | func Login(c *gin.Context) { 91 | // 通过POST获取用户名 92 | email := c.PostForm("email") 93 | // 转为小写 94 | email = strings.ToLower(email) 95 | // 通过POST获取密码 96 | password := c.PostForm("password") 97 | 98 | // 获取配置文件中的邮箱和密码 99 | configEmail := viper.GetString("auth.email") 100 | configPassword := viper.GetString("auth.password") 101 | 102 | // 如果配置文件中的邮箱或者密码任意一个为空,则提示应该初始化 103 | if configEmail == "" || configPassword == "" { 104 | c.JSON(200, gin.H{ 105 | "code": -1000, 106 | "msg": "Please initialize the system", 107 | "data": "", 108 | }) 109 | c.Abort() 110 | return 111 | } 112 | 113 | // 验证邮箱是否有效 114 | if !utils.IsEmail(email) { 115 | c.JSON(200, gin.H{ 116 | "code": -1000, 117 | "msg": "Invalid email address", 118 | "data": "", 119 | }) 120 | c.Abort() 121 | return 122 | } 123 | 124 | // 验证密码是否有效 125 | if !utils.IsPassword(password) { 126 | c.JSON(200, gin.H{ 127 | "code": -1000, 128 | "msg": "Invalid password", 129 | "data": "", 130 | }) 131 | c.Abort() 132 | return 133 | } 134 | 135 | // 验证邮箱和密码是否正确 136 | if email != configEmail { 137 | c.JSON(200, gin.H{ 138 | "code": -1000, 139 | "msg": "Username or password is incorrect", 140 | "data": "", 141 | }) 142 | c.Abort() 143 | return 144 | } 145 | 146 | passTxt := email + password + "wp2ai" 147 | // 生成MD5哈希 148 | passHash := utils.MD5(passTxt) 149 | 150 | if passHash != configPassword { 151 | c.JSON(200, gin.H{ 152 | "code": -1000, 153 | "msg": "Username or password is incorrect", 154 | "data": "", 155 | }) 156 | c.Abort() 157 | return 158 | } 159 | 160 | // 生成一个token 161 | token := "web-" + utils.RandStr(28) 162 | // 取出前8位作为key 163 | key := token[:8] 164 | keyByte := []byte(key) 165 | valueByte := []byte(token) 166 | 167 | // 设置过期时间为 30 天 168 | expireTime := 30 * 24 * 60 * 60 // 30 天的秒数 169 | // 存储到缓存中 170 | err := utils.Cache.Set(keyByte, valueByte, expireTime) 171 | 172 | if err != nil { 173 | c.JSON(200, gin.H{ 174 | "code": 500, 175 | "msg": "Failed to write cache", 176 | "data": "", 177 | }) 178 | c.Abort() 179 | return 180 | } 181 | 182 | // 提示成功 183 | c.JSON(200, gin.H{ 184 | "code": 200, 185 | "msg": "success", 186 | "data": token, 187 | }) 188 | } 189 | 190 | // 检测用户是否登录 191 | func IsLogin(c *gin.Context) { 192 | c.JSON(200, gin.H{ 193 | "code": 200, 194 | "msg": "success", 195 | "data": "", 196 | }) 197 | } 198 | -------------------------------------------------------------------------------- /assets/dist/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helloxz/wp2ai/891a6eae259eb8a3c564be60331ca796097611fa/assets/dist/favicon.ico -------------------------------------------------------------------------------- /assets/dist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite App 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /assets/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | WP2AI 8 | 9 | 10 | 11 | 12 | 13 | {{ .header }} 14 | 15 | 16 | 17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /config.toml: -------------------------------------------------------------------------------- 1 | [app] 2 | chat_limit = '10' 3 | doc_limit = '5' 4 | min_process = 15 5 | 6 | [auth] 7 | email = '' 8 | password = '' 9 | token = '' 10 | username = '' 11 | 12 | [embedding] 13 | key = '' 14 | model = '' 15 | url = '' 16 | 17 | [openai] 18 | key = '' 19 | model = '' 20 | url = '' 21 | 22 | [server] 23 | mode = 'release' 24 | port = 2080 25 | 26 | [wordpress] 27 | db_host = '' 28 | db_name = '' 29 | db_password = '' 30 | db_username = '' 31 | domain = '' 32 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | wp2ai: 4 | container_name: wp2ai 5 | volumes: 6 | - '/opt/wp2ai/data:/opt/wp2ai/data' 7 | ports: 8 | - '2080:2080' 9 | restart: always 10 | image: 'pub.tcp.mk/helloz/wp2ai' -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module wp2ai 2 | 3 | go 1.23.2 4 | 5 | require ( 6 | github.com/asg017/sqlite-vec-go-bindings v0.1.6 7 | github.com/gin-gonic/gin v1.10.0 8 | github.com/glebarez/sqlite v1.11.0 9 | github.com/go-resty/resty/v2 v2.16.5 10 | github.com/mattn/go-sqlite3 v1.14.24 11 | github.com/ncruces/go-sqlite3 v0.23.0 12 | github.com/robfig/cron/v3 v3.0.0 13 | github.com/spf13/viper v1.19.0 14 | github.com/tidwall/gjson v1.18.0 15 | gorm.io/driver/mysql v1.5.7 16 | gorm.io/gorm v1.25.12 17 | ) 18 | 19 | require ( 20 | filippo.io/edwards25519 v1.1.0 // indirect 21 | github.com/bytedance/sonic v1.12.9 // indirect 22 | github.com/bytedance/sonic/loader v0.2.3 // indirect 23 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 24 | github.com/cloudwego/base64x v0.1.5 // indirect 25 | github.com/coocood/freecache v1.2.4 // indirect 26 | github.com/dustin/go-humanize v1.0.1 // indirect 27 | github.com/fsnotify/fsnotify v1.7.0 // indirect 28 | github.com/gabriel-vasile/mimetype v1.4.8 // indirect 29 | github.com/gin-contrib/sse v1.0.0 // indirect 30 | github.com/glebarez/go-sqlite v1.22.0 // indirect 31 | github.com/go-playground/locales v0.14.1 // indirect 32 | github.com/go-playground/universal-translator v0.18.1 // indirect 33 | github.com/go-playground/validator/v10 v10.25.0 // indirect 34 | github.com/go-sql-driver/mysql v1.9.0 // indirect 35 | github.com/goccy/go-json v0.10.5 // indirect 36 | github.com/google/uuid v1.6.0 // indirect 37 | github.com/hashicorp/hcl v1.0.0 // indirect 38 | github.com/jinzhu/inflection v1.0.0 // indirect 39 | github.com/jinzhu/now v1.1.5 // indirect 40 | github.com/json-iterator/go v1.1.12 // indirect 41 | github.com/klauspost/cpuid/v2 v2.2.9 // indirect 42 | github.com/leodido/go-urn v1.4.0 // indirect 43 | github.com/magiconair/properties v1.8.7 // indirect 44 | github.com/mattn/go-isatty v0.0.20 // indirect 45 | github.com/mitchellh/mapstructure v1.5.0 // indirect 46 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 47 | github.com/modern-go/reflect2 v1.0.2 // indirect 48 | github.com/ncruces/go-strftime v0.1.9 // indirect 49 | github.com/ncruces/julianday v1.0.0 // indirect 50 | github.com/pelletier/go-toml/v2 v2.2.3 // indirect 51 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect 52 | github.com/sagikazarmark/locafero v0.4.0 // indirect 53 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect 54 | github.com/sashabaranov/go-openai v1.37.0 // indirect 55 | github.com/sourcegraph/conc v0.3.0 // indirect 56 | github.com/spf13/afero v1.11.0 // indirect 57 | github.com/spf13/cast v1.6.0 // indirect 58 | github.com/spf13/pflag v1.0.5 // indirect 59 | github.com/subosito/gotenv v1.6.0 // indirect 60 | github.com/tetratelabs/wazero v1.9.0 // indirect 61 | github.com/tidwall/match v1.1.1 // indirect 62 | github.com/tidwall/pretty v1.2.1 // indirect 63 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 64 | github.com/ugorji/go/codec v1.2.12 // indirect 65 | go.uber.org/atomic v1.9.0 // indirect 66 | go.uber.org/multierr v1.9.0 // indirect 67 | golang.org/x/arch v0.14.0 // indirect 68 | golang.org/x/crypto v0.33.0 // indirect 69 | golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa // indirect 70 | golang.org/x/net v0.35.0 // indirect 71 | golang.org/x/sys v0.30.0 // indirect 72 | golang.org/x/text v0.22.0 // indirect 73 | google.golang.org/protobuf v1.36.5 // indirect 74 | gopkg.in/ini.v1 v1.67.0 // indirect 75 | gopkg.in/yaml.v3 v3.0.1 // indirect 76 | modernc.org/libc v1.61.13 // indirect 77 | modernc.org/mathutil v1.7.1 // indirect 78 | modernc.org/memory v1.8.2 // indirect 79 | modernc.org/sqlite v1.35.0 // indirect 80 | ) 81 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= 2 | filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= 3 | github.com/asg017/sqlite-vec-go-bindings v0.1.6 h1:Nx0jAzyS38XpkKznJ9xQjFXz2X9tI7KqjwVxV8RNoww= 4 | github.com/asg017/sqlite-vec-go-bindings v0.1.6/go.mod h1:A8+cTt/nKFsYCQF6OgzSNpKZrzNo5gQsXBTfsXHXY0Q= 5 | github.com/bytedance/sonic v1.12.9 h1:Od1BvK55NnewtGaJsTDeAOSnLVO2BTSLOe0+ooKokmQ= 6 | github.com/bytedance/sonic v1.12.9/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8= 7 | github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= 8 | github.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0= 9 | github.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= 10 | github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 11 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= 12 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 13 | github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4= 14 | github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= 15 | github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= 16 | github.com/coocood/freecache v1.2.4 h1:UdR6Yz/X1HW4fZOuH0Z94KwG851GWOSknua5VUbb/5M= 17 | github.com/coocood/freecache v1.2.4/go.mod h1:RBUWa/Cy+OHdfTGFEhEuE1pMCMX51Ncizj7rthiQ3vk= 18 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 19 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 20 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 21 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 22 | github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= 23 | github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= 24 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 25 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 26 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= 27 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= 28 | github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= 29 | github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= 30 | github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E= 31 | github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0= 32 | github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= 33 | github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= 34 | github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ= 35 | github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc= 36 | github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= 37 | github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= 38 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 39 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 40 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 41 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 42 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 43 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 44 | github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8= 45 | github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus= 46 | github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM= 47 | github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA= 48 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 49 | github.com/go-sql-driver/mysql v1.9.0 h1:Y0zIbQXhQKmQgTp44Y1dp3wTXcn804QoTptLZT1vtvo= 50 | github.com/go-sql-driver/mysql v1.9.0/go.mod h1:pDetrLJeA3oMujJuvXc8RJoasr589B6A9fwzD3QMrqw= 51 | github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= 52 | github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= 53 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 54 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 55 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 56 | github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= 57 | github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= 58 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 59 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 60 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 61 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 62 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= 63 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= 64 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= 65 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= 66 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 67 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 68 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 69 | github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= 70 | github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= 71 | github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= 72 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 73 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 74 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 75 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 76 | github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= 77 | github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= 78 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= 79 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= 80 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 81 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 82 | github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= 83 | github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= 84 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 85 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 86 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 87 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 88 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 89 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 90 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 91 | github.com/ncruces/go-sqlite3 v0.23.0 h1:90j/ar8Ywu2AtsfDl5WhO9sgP/rNk76BcKGIzAHO8AQ= 92 | github.com/ncruces/go-sqlite3 v0.23.0/go.mod h1:gq2nriHSczOs11SqGW5+0X+SgLdkdj4K+j4F/AhQ+8g= 93 | github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= 94 | github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= 95 | github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M= 96 | github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g= 97 | github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= 98 | github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= 99 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 100 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 101 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 102 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= 103 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 104 | github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E= 105 | github.com/robfig/cron/v3 v3.0.0/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 106 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 107 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 108 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= 109 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= 110 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= 111 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= 112 | github.com/sashabaranov/go-openai v1.37.0 h1:hQQowgYm4OXJ1Z/wTrE+XZaO20BYsL0R3uRPSpfNZkY= 113 | github.com/sashabaranov/go-openai v1.37.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= 114 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= 115 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= 116 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= 117 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= 118 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= 119 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 120 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 121 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 122 | github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= 123 | github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= 124 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 125 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 126 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 127 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 128 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 129 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 130 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 131 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 132 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 133 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 134 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 135 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 136 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= 137 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 138 | github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= 139 | github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM= 140 | github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= 141 | github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 142 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= 143 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= 144 | github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 145 | github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= 146 | github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 147 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 148 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 149 | github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= 150 | github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 151 | go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= 152 | go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= 153 | go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= 154 | go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= 155 | golang.org/x/arch v0.14.0 h1:z9JUEZWr8x4rR0OU6c4/4t6E6jOZ8/QBS2bBYBm4tx4= 156 | golang.org/x/arch v0.14.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= 157 | golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= 158 | golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= 159 | golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa h1:t2QcU6V556bFjYgu4L6C+6VrCPyJZ+eyRsABUPs1mz4= 160 | golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa/go.mod h1:BHOTPb3L19zxehTsLoJXVaTktb06DFgmdW6Wb9s8jqk= 161 | golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM= 162 | golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= 163 | golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= 164 | golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= 165 | golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= 166 | golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 167 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 168 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= 169 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 170 | golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= 171 | golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= 172 | golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U= 173 | golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= 174 | golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY= 175 | golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY= 176 | google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= 177 | google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 178 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 179 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 180 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 181 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= 182 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 183 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 184 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 185 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 186 | gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= 187 | gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= 188 | gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= 189 | gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= 190 | gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= 191 | modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0= 192 | modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= 193 | modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo= 194 | modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo= 195 | modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= 196 | modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= 197 | modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw= 198 | modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= 199 | modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8= 200 | modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= 201 | modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= 202 | modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= 203 | modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI= 204 | modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU= 205 | modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= 206 | modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= 207 | modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= 208 | modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= 209 | modernc.org/sqlite v1.35.0 h1:yQps4fegMnZFdphtzlfQTCNBWtS0CZv48pRpW3RFHRw= 210 | modernc.org/sqlite v1.35.0/go.mod h1:9cr2sicr7jIaWTBKQmAxQLfBv9LL0su4ZTEV+utt3ic= 211 | modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= 212 | modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= 213 | modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= 214 | modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= 215 | nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= 216 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "wp2ai/router" 7 | "wp2ai/utils" 8 | ) 9 | 10 | func main() { 11 | //获取命令行参数 12 | args := os.Args 13 | //获取切片长度 14 | args_len := len(args) 15 | 16 | //如果参数是1,则没有额外参数 17 | if args_len == 1 { 18 | fmt.Printf("Please enter the parameters!\n") 19 | os.Exit(0) 20 | } else if args_len == 2 { 21 | //启动程序 22 | if args[1] == "start" { 23 | utils.InitConfig() 24 | //启动Gin 25 | router.Start() 26 | } else { 27 | fmt.Printf("Please enter the correct parameters!\n") 28 | os.Exit(0) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "wp2ai/utils" 5 | 6 | "github.com/gin-gonic/gin" 7 | "github.com/spf13/viper" 8 | ) 9 | 10 | // 写一个认证中间件,从header的Authorization中获取Bearer token,然后解析token,如果token合法,则继续执行后续的逻辑,否则返回401 11 | func Auth() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // 从header中获取Authorization 14 | bearer := c.GetHeader("Authorization") 15 | // 如果token为空 16 | if bearer == "" { 17 | // 返回401 18 | c.JSON(200, gin.H{ 19 | "code": 401, 20 | "msg": "Unauthorized", 21 | "data": "", 22 | }) 23 | c.Abort() 24 | return 25 | } 26 | // 如果长度小于7 27 | if len(bearer) <= 7 { 28 | // 返回401 29 | c.JSON(200, gin.H{ 30 | "code": 401, 31 | "msg": "Unauthorized", 32 | "data": "", 33 | }) 34 | c.Abort() 35 | return 36 | } 37 | // 从bearer中获取token 38 | token := bearer[7:] 39 | // 打印token 40 | // fmt.Println(token) 41 | // 如果token 为空 42 | if token == "" { 43 | // 返回401 44 | c.JSON(200, gin.H{ 45 | "code": 401, 46 | "msg": "Unauthorized", 47 | "data": "", 48 | }) 49 | c.Abort() 50 | return 51 | } 52 | // 获取配置文件里面的token 53 | configToken := viper.GetString("auth.token") 54 | if token == configToken { 55 | // 继续执行后续的逻辑 56 | c.Next() 57 | return 58 | } 59 | // 这里还在执行,说明与配置文件里面的token不匹配,则需要从内存获取 60 | key := token[:8] 61 | keyByte := []byte(key) 62 | // 通过内存获取 63 | valueByte, err := utils.Cache.Get(keyByte) 64 | // 如果获取失败 65 | if err != nil { 66 | // 返回401 67 | c.JSON(200, gin.H{ 68 | "code": 401, 69 | "msg": "Unauthorized", 70 | "data": "", 71 | }) 72 | c.Abort() 73 | return 74 | } 75 | // 将valueByte转为字符串 76 | value := string(valueByte) 77 | // 如果token不匹配 78 | if token != value { 79 | // 返回401 80 | c.JSON(200, gin.H{ 81 | "code": 401, 82 | "msg": "Unauthorized", 83 | "data": "", 84 | }) 85 | c.Abort() 86 | return 87 | } 88 | 89 | // 上面全部通过了,继续执行后续的逻辑 90 | c.Next() 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /middleware/cors.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/gin-gonic/gin" 7 | ) 8 | 9 | func CORSMiddleware() gin.HandlerFunc { 10 | return func(c *gin.Context) { 11 | c.Writer.Header().Set("Access-Control-Allow-Origin", "*") 12 | c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") 13 | c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With") 14 | c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE") 15 | 16 | if c.Request.Method == "OPTIONS" { 17 | c.AbortWithStatus(http.StatusNoContent) 18 | return 19 | } 20 | 21 | c.Next() 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /middleware/limit.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "wp2ai/utils" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/spf13/viper" 10 | ) 11 | 12 | func LimitChat() gin.HandlerFunc { 13 | return func(c *gin.Context) { 14 | // 获取访客的IP 15 | ip := utils.GetClientIP(c) 16 | // 设置一个key 17 | key := fmt.Sprintf("limit_chat:%s", ip) 18 | // key转为[]byte 19 | keyByte := []byte(key) 20 | // 从内存中获取 21 | value, _ := utils.Cache.Get(keyByte) 22 | // 如果为空 23 | if value == nil { 24 | // 设置一个值 25 | utils.Cache.Set(keyByte, []byte("0"), 60*60*24) 26 | // 继续执行后续的逻辑 27 | c.Next() 28 | return 29 | } 30 | // 如果不为空,则把value转为int 31 | valueStr := string(value) 32 | count, _ := strconv.Atoi(valueStr) 33 | // 获取配置中的限制 34 | limitNum := viper.GetInt("app.chat_limit") 35 | // 如果超过限制 36 | if count >= limitNum { 37 | // 返回错误信息 38 | c.JSON(200, gin.H{ 39 | "code": 429, 40 | "msg": "Too many requests", 41 | "data": "", 42 | }) 43 | c.Abort() 44 | return 45 | } 46 | // 如果没有超过限制,则继续执行后续的逻辑 47 | c.Next() 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /model/config.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "log" 7 | "os" 8 | "time" 9 | 10 | sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo" 11 | "github.com/glebarez/sqlite" 12 | _ "github.com/mattn/go-sqlite3" 13 | "github.com/spf13/viper" 14 | "gorm.io/driver/mysql" 15 | "gorm.io/gorm" 16 | ) 17 | 18 | var WP *gorm.DB 19 | 20 | func InitWPDB() { 21 | host := viper.GetString("wordpress.db_host") 22 | name := viper.GetString("wordpress.db_name") 23 | username := viper.GetString("wordpress.db_username") 24 | password := viper.GetString("wordpress.db_password") 25 | dsn := username + ":" + password + "@tcp(" + host + ")/" + name + "?charset=utf8mb4&parseTime=True&loc=Local" 26 | // dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" 27 | var err error 28 | if WP == nil { 29 | WP, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) 30 | 31 | if err != nil { 32 | // log.Fatalf("failed to connect database: %v", err) 33 | // 写入日志 34 | // 打印错误消息 35 | fmt.Printf("failed to connect database: %v\n", err) 36 | } else { 37 | // 打印连接成功 38 | fmt.Printf("WordPress database connection succeeded!\n") 39 | } 40 | } 41 | 42 | } 43 | 44 | // 全局数据库连接 45 | var DB *gorm.DB 46 | 47 | // 初始化数据库连接 48 | func InitDB() { 49 | var err error 50 | //如果数据库文件不存在,会自动创建 51 | DB, err = gorm.Open(sqlite.Open("data/db/wp2db.db3"), &gorm.Config{}) 52 | //如果出现错误,抛出错误并终止执行 53 | if err != nil { 54 | // 打印错误 55 | fmt.Println("Database connection failed!") 56 | // 写入日志 57 | // helper.WriteLog(fmt.Sprintf("%s", err)) 58 | // 终止执行 59 | os.Exit(1) 60 | } else { 61 | // 显式启用 WAL 模式 62 | if err := DB.Exec("PRAGMA journal_mode=WAL;").Error; err != nil { 63 | log.Fatalf("Failed to enable WAL mode: %v", err) 64 | } 65 | // 调整 SQLite 参数 66 | DB.Exec("PRAGMA synchronous=NORMAL;") 67 | //自动迁移数据库表结构 68 | // 迁移多个表 69 | err = DB.AutoMigrate(&Post{}) 70 | if err != nil { 71 | fmt.Println("failed to migrate database!") 72 | // 写入错误日志 73 | // helper.WriteLog(fmt.Sprintf("%s", err)) 74 | } 75 | fmt.Print("Database connection succeeded!\n") 76 | } 77 | 78 | sqlDB, err := DB.DB() 79 | if err != nil { 80 | fmt.Println("failed to get database connection pool!") 81 | os.Exit(1) 82 | } 83 | // 设置最大打开连接数 84 | sqlDB.SetMaxOpenConns(25) 85 | // 设置最大空闲连接数 86 | sqlDB.SetMaxIdleConns(5) 87 | // 设置连接的最大生命周期 88 | sqlDB.SetConnMaxLifetime(30 * time.Minute) 89 | 90 | } 91 | 92 | var VecDB *sql.DB 93 | 94 | func InitVecDB() { 95 | sqlite_vec.Auto() 96 | var err error 97 | // Open persistent database 98 | VecDB, err = sql.Open("sqlite3", "data/db/embedding.db3") 99 | if err != nil { 100 | log.Fatal(err) 101 | } 102 | // defer VecDB.Close() 103 | 104 | var sqliteVersion, vecVersion string 105 | err = VecDB.QueryRow("select sqlite_version(), vec_version()").Scan(&sqliteVersion, &vecVersion) 106 | if err != nil { 107 | log.Fatal("failed to prepare statement!") 108 | } 109 | 110 | fmt.Printf("sqlite_version=%s, vec_version=%s\n", sqliteVersion, vecVersion) 111 | 112 | // Create table "items" with specified fields 113 | _, err = VecDB.Exec(` 114 | CREATE TABLE IF NOT EXISTS items ( 115 | id INTEGER PRIMARY KEY, 116 | post_id TEXT NOT NULL UNIQUE, 117 | embedding BLOB NOT NULL, 118 | title TEXT NOT NULL, 119 | content TEXT NOT NULL, 120 | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 121 | updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 122 | ); 123 | `) 124 | if err != nil { 125 | log.Fatal("failed to create table items!") 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /model/items.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "time" 5 | 6 | sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo" 7 | "github.com/spf13/viper" 8 | ) 9 | 10 | // 声明一个符合标准的结构体 11 | type Item struct { 12 | PostID string 13 | Embedding []float32 14 | Title string 15 | Content string 16 | CreatedAt string 17 | UpdatedAt string 18 | Distance float64 19 | } 20 | 21 | // 插入向量数据 22 | func InsertDocument(item Item) error { 23 | sqlite_vec.Auto() 24 | 25 | // 进行blob序列化 26 | v, err := sqlite_vec.SerializeFloat32(item.Embedding) 27 | if err != nil { 28 | return err 29 | } 30 | now := time.Now().Format(time.RFC3339) 31 | _, err = VecDB.Exec("INSERT INTO items(post_id, embedding, title,content, created_at, updated_at) VALUES (?, ?, ?,?, ?, ?)", 32 | item.PostID, v, item.Title, item.Content, now, now) 33 | if err != nil { 34 | return err 35 | } 36 | return nil 37 | } 38 | 39 | // 查询向量数据 40 | // 查询向量数据 41 | func GetDocument(input []float32) ([]Item, error) { 42 | sqlite_vec.Auto() 43 | query, err := sqlite_vec.SerializeFloat32(input) 44 | if err != nil { 45 | return nil, err 46 | } 47 | 48 | doc_limit := viper.GetInt("app.doc_limit") 49 | 50 | rows, err := VecDB.Query(` 51 | SELECT 52 | post_id, 53 | title, 54 | content, 55 | vec_distance_L2(embedding, ?) AS distance 56 | FROM items 57 | WHERE embedding IS NOT NULL 58 | ORDER BY distance 59 | LIMIT ? 60 | `, query, doc_limit) 61 | 62 | if err != nil { 63 | return nil, err 64 | } 65 | defer rows.Close() 66 | 67 | // 数据列表 68 | var items []Item 69 | for rows.Next() { 70 | var post_id string 71 | var title string 72 | var content string 73 | var distance float64 74 | err = rows.Scan(&post_id, &title, &content, &distance) 75 | if err != nil { 76 | return nil, err 77 | } 78 | items = append(items, Item{PostID: post_id, Title: title, Content: content, Distance: distance}) 79 | } 80 | 81 | err = rows.Err() 82 | if err != nil { 83 | return nil, err 84 | } 85 | 86 | return items, nil 87 | } 88 | 89 | // 清空整个表 90 | func TruncateItems() error { 91 | _, err := VecDB.Exec("DELETE FROM items") 92 | if err != nil { 93 | return err 94 | } 95 | return nil 96 | } 97 | 98 | // 根据postid删除单行数据 99 | func DeleteItem(post_id string) error { 100 | _, err := VecDB.Exec("DELETE FROM items WHERE post_id = ?", post_id) 101 | if err != nil { 102 | return err 103 | } 104 | return nil 105 | } 106 | -------------------------------------------------------------------------------- /model/posts.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | type Post struct { 9 | ID uint `gorm:"primaryKey;autoIncrement" json:"id"` 10 | PostID uint `gorm:"not null;uniqueIndex" json:"post_id"` // 添加 uniqueIndex 11 | PostDate string `gorm:"type:TEXT" json:"post_date"` // 使用 *time.Time 处理 TEXT 类型 12 | PostContent string `gorm:"type:TEXT" json:"post_content"` 13 | PostTitle string `gorm:"type:TEXT" json:"post_title"` 14 | Status int `gorm:"not null;default:0" json:"status"` // 默认0:未处理,1:处理中,2:待更新,3:已处理,4:存在错误 15 | CreatedAt time.Time `gorm:"not null" json:"created_at"` 16 | UpdatedAt time.Time `json:"updated_at"` 17 | } 18 | 19 | // TableName sets the insert table name for struct 20 | func (Post) TableName() string { 21 | return "posts" 22 | } 23 | 24 | // 写一个函数,得到一批postid,然后一次性插入到数据库中 25 | func InsertPosts(posts []Post) error { 26 | return DB.Create(&posts).Error 27 | } 28 | 29 | // 插入单个数据 30 | func InsertPost(post Post) error { 31 | return DB.Create(&post).Error 32 | } 33 | 34 | // 写一个函数,函数指定查询的数量,然后查询出status=0的数据 35 | func GetPosts(limit int) []Post { 36 | var posts []Post 37 | DB.Where("status = ?", 0).Limit(limit).Find(&posts) 38 | return posts 39 | } 40 | 41 | // 写一个函数,函数接收一批postid,然后批量更新status=1 42 | func UpdatePostsStatus(ids []uint, status int) error { 43 | return DB.Model(&Post{}).Where("post_id IN (?)", ids).Update("status", status).Error 44 | } 45 | 46 | // 根据postid,更新单行数据 47 | func UpdatePost(post Post) error { 48 | return DB.Model(&Post{}).Where("post_id = ?", post.PostID).Updates(&post).Error 49 | } 50 | 51 | // 写一个函数,根据页码和每页数量,查询出所有的数据 52 | func GetPostsByPage(page, limitInt int) ([]Post, error) { 53 | var posts []Post 54 | err := DB.Offset((page - 1) * limitInt).Limit(limitInt).Order("post_id desc").Find(&posts).Error 55 | if err != nil { 56 | fmt.Println(err) 57 | return nil, err 58 | } 59 | // fmt.Println("db", posts) 60 | return posts, nil 61 | } 62 | 63 | // 根据状态统计所有文章数量,如果状态为-1,则统计全部文章 64 | func CountPosts(status int) int { 65 | var count int64 66 | if status == -1 { 67 | DB.Model(&Post{}).Count(&count) 68 | } else { 69 | DB.Model(&Post{}).Where("status = ?", status).Count(&count) 70 | } 71 | return int(count) 72 | } 73 | 74 | // 清空posts整个表 75 | func TruncatePosts() error { 76 | return DB.Exec("DELETE FROM posts").Error 77 | } 78 | 79 | // 根据postid删除单行数据 80 | func DeletePost(postId uint) error { 81 | return DB.Where("post_id = ?", postId).Delete(&Post{}).Error 82 | } 83 | -------------------------------------------------------------------------------- /model/wp_posts.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | // 声明wp_posts结构体 4 | type WpPost struct { 5 | ID uint `gorm:"primaryKey" json:"id"` 6 | PostDate string `gorm:"column:post_date" json:"post_date"` 7 | PostContent string `gorm:"column:post_content;type:longtext" json:"post_content"` 8 | PostTitle string `gorm:"column:post_title" json:"post_title"` 9 | PostStatus string `gorm:"column:post_status" json:"post_status"` 10 | } 11 | 12 | // TableName 设置表名,如果你的表名不是默认的Post的复数形式 13 | func (WpPost) TableName() string { 14 | return "wp_posts" 15 | } 16 | 17 | // 写一个函数,查询出所有post_status='publish'的文章,只查询ID字段即可 18 | func GetPostIds() []WpPost { 19 | var posts []WpPost 20 | err := WP.Select("ID"). 21 | Where("post_status = ?", "publish"). 22 | Where("post_type = ?", "post"). 23 | Where("post_password = ?", ""). 24 | Order("id desc").Find(&posts).Error 25 | if err != nil { 26 | return []WpPost{} 27 | } 28 | return posts 29 | } 30 | 31 | // 根据一批ID,查询出匹配ID的数据 32 | func GetPostsByIds(ids []uint) []WpPost { 33 | var posts []WpPost 34 | err := WP.Where("id IN (?)", ids).Find(&posts).Error 35 | if err != nil { 36 | return []WpPost{} 37 | } 38 | return posts 39 | } 40 | 41 | // 根据ID,和where条件,检查是否存在 42 | func GetWpPostById(id uint) (*WpPost, error) { 43 | var post *WpPost 44 | err := WP.Where("id = ?", id). 45 | Where("post_status = ?", "publish"). 46 | Where("post_type = ?", "post"). 47 | Where("post_password = ?", "").First(&post).Error 48 | if err != nil { 49 | return nil, err 50 | } 51 | return post, nil 52 | } 53 | -------------------------------------------------------------------------------- /router/routers.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "wp2ai/api" 5 | "wp2ai/middleware" 6 | 7 | "github.com/gin-gonic/gin" 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | func Start() { 12 | //gin运行模式 13 | RunMode := viper.GetString("server.mode") 14 | // 设置运行模式 15 | gin.SetMode(RunMode) 16 | //运行gin 17 | r := gin.Default() 18 | // 全局跨域中间件 19 | r.Use(middleware.CORSMiddleware()) 20 | 21 | //前台首页 22 | r.LoadHTMLFiles("assets/templates/index.html") 23 | r.GET("/", api.Home) 24 | r.GET("/index.html", api.Home) 25 | r.Static("/assets", "assets") 26 | r.NoRoute(api.Home) 27 | 28 | r.GET("/api/batch-scan", middleware.Auth(), api.BatchScan) 29 | r.GET("/api/query", api.Query) 30 | r.POST("/api/chat", middleware.LimitChat(), api.Chat) 31 | r.GET("/api/post/list", middleware.Auth(), api.PostList) 32 | r.GET("/api/get/appinfo", middleware.Auth(), api.AppInfo) 33 | r.GET("/api/get/siteinfo", api.SiteInfo) 34 | // 设置配置 35 | r.POST("/api/set/config", middleware.Auth(), api.SetConfig) 36 | // 清空整个表 37 | r.POST("/api/delete/all", middleware.Auth(), api.DeleteAll) 38 | // 插入数据 39 | r.POST("/api/add/post", middleware.Auth(), api.AddPost) 40 | r.POST("/api/delete/post", middleware.Auth(), api.DeletePost) 41 | 42 | // 初始化 43 | r.POST("/api/init", api.InitUser) 44 | // 管理员登录 45 | r.POST("/api/login", api.Login) 46 | // 检测用户是否登录 47 | r.GET("/api/user/is_login", middleware.Auth(), api.IsLogin) 48 | 49 | //获取服务端配置 50 | port := ":" + viper.GetString("server.port") 51 | // 运行服务 52 | r.Run(port) 53 | } 54 | -------------------------------------------------------------------------------- /utils/cache.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "github.com/coocood/freecache" 4 | 5 | var Cache *freecache.Cache 6 | 7 | func InitCache() { 8 | // 设置 5MB 的缓存大小 9 | cacheSize := 5 * 1024 * 1024 10 | Cache = freecache.NewCache(cacheSize) 11 | } 12 | -------------------------------------------------------------------------------- /utils/config.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "math/rand" 7 | "os" 8 | "strings" 9 | "sync" 10 | "time" 11 | "wp2ai/model" 12 | 13 | "github.com/spf13/viper" 14 | ) 15 | 16 | var ( 17 | once sync.Once 18 | ) 19 | 20 | // 全局就一个init函数,避免其它地方再次声明,以免逻辑容易出错 21 | func InitConfig() { 22 | once.Do(func() { 23 | // 创建必要的目录 24 | CreateDir("data/config") 25 | CreateDir("data/db") 26 | CreateDir("data/logs") 27 | 28 | //默认配置文件 29 | config_file := "data/config/config.toml" 30 | // 检查配置文件是否存在,不存在则复制一份 31 | if _, err := os.Stat(config_file); os.IsNotExist(err) { 32 | // 创建目录 33 | os.MkdirAll("data/config", os.ModePerm) 34 | // 复制配置文件 35 | err := CopyFile("config.toml", config_file) 36 | if err != nil { 37 | fmt.Println("Failed to copy config file:", err) 38 | os.Exit(1) 39 | } 40 | } 41 | 42 | viper.SetConfigFile(config_file) // 指定配置文件路径 43 | //指定ini类型的文件 44 | viper.SetConfigType("toml") 45 | err := viper.ReadInConfig() // 读取配置信息 46 | if err != nil { // 读取配置信息失败 47 | // 写入日志 48 | fmt.Println("Failed to read config:", err) 49 | os.Exit(1) 50 | } 51 | }) 52 | 53 | // 连接内存缓存 54 | InitCache() 55 | 56 | // 连接数据库 57 | model.InitDB() 58 | model.InitVecDB() 59 | // Test() 60 | go model.InitWPDB() 61 | // 异步执行定时任务 62 | go InitCrontab() 63 | 64 | // 初始化密钥 65 | go InitToken() 66 | } 67 | 68 | // 初始化密钥 69 | func InitToken() { 70 | // 获取密钥 71 | token := viper.GetString("auth.token") 72 | // 如果密钥为空 73 | if token == "" { 74 | tokenStr := "sk-" + RandString(29) 75 | // 设置密钥 76 | viper.Set("auth.token", tokenStr) 77 | // 写入配置 78 | err := viper.WriteConfig() 79 | if err != nil { 80 | fmt.Println("Failed to init token:", err) 81 | } 82 | } 83 | } 84 | 85 | // 生成一个随机字符串 86 | func RandString(length int) string { 87 | // 定义字符集 88 | charset := "abcdefghijklmnopqrstuvwxyz0123456789" 89 | // 将字符集转换为 rune 切片,以便随机选择字符 90 | charsetRunes := []rune(charset) 91 | 92 | // 创建一个 strings.Builder,用于高效构建字符串 93 | var sb strings.Builder 94 | // 设置 strings.Builder 的初始容量,避免频繁扩容 95 | sb.Grow(length) 96 | 97 | // 使用当前时间作为随机数种子,确保每次运行生成不同的随机字符串 98 | rand.Seed(time.Now().UnixNano()) 99 | 100 | // 循环生成随机字符,并添加到 strings.Builder 中 101 | for i := 0; i < length; i++ { 102 | // 从字符集中随机选择一个字符 103 | randomIndex := rand.Intn(len(charsetRunes)) 104 | randomChar := charsetRunes[randomIndex] 105 | // 将随机字符添加到 strings.Builder 中 106 | sb.WriteRune(randomChar) 107 | } 108 | 109 | // 返回生成的随机字符串 110 | return sb.String() 111 | } 112 | 113 | // copyFile 复制文件内容 114 | func CopyFile(src, dst string) error { 115 | sourceFile, err := os.Open(src) 116 | if err != nil { 117 | return err 118 | } 119 | defer sourceFile.Close() 120 | 121 | destFile, err := os.Create(dst) 122 | if err != nil { 123 | return err 124 | } 125 | defer destFile.Close() 126 | 127 | _, err = io.Copy(destFile, sourceFile) 128 | return err 129 | } 130 | 131 | // 接收一个路径作为参数,判断路径是否存在,不存在则创建 132 | func CreateDir(path string) error { 133 | if _, err := os.Stat(path); os.IsNotExist(err) { 134 | err := os.MkdirAll(path, 0755) 135 | if err != nil { 136 | return fmt.Errorf("无法创建目录:%w", err) 137 | } 138 | } 139 | return nil 140 | } 141 | -------------------------------------------------------------------------------- /utils/crontab.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "time" 7 | "wp2ai/model" 8 | 9 | "github.com/go-resty/resty/v2" 10 | "github.com/robfig/cron/v3" 11 | "github.com/spf13/viper" 12 | "github.com/tidwall/gjson" 13 | ) 14 | 15 | func InitCrontab() { 16 | // 创建一个定时任务的实例,带上cron.WithSeconds()则精确到秒级别 17 | c := cron.New() 18 | // 添加定时任务,每隔5分钟探测一次所有节点 19 | c.AddFunc("*/1 * * * *", Vectorization) 20 | 21 | // 启动定时任务 22 | c.Start() 23 | 24 | // 这里使用select{}可以使主程序持续运行,否则主程序可能会结束,导致定时任务未能执行 25 | select {} 26 | } 27 | 28 | // 每次获取10条数据 29 | func Vectorization() { 30 | minProcess := viper.GetInt("app.min_process") 31 | // fmt.Println("minProcess:", minProcess) 32 | // 获取文章数据 33 | posts := model.GetPosts(minProcess) 34 | // 如果没有数据,则直接返回 35 | if len(posts) == 0 { 36 | return 37 | } 38 | // 遍历posts,得到文章IDS 39 | var ids []uint 40 | for _, post := range posts { 41 | ids = append(ids, post.PostID) 42 | } 43 | // 批量更新这批文章的状态为1:处理中 44 | err := model.UpdatePostsStatus(ids, 1) 45 | if err != nil { 46 | // 写入日志 47 | WriteLog(fmt.Sprintf("批量更新文章状态失败:%v", err)) 48 | return 49 | } 50 | // 查询出这些文章 51 | wpPosts := model.GetPostsByIds(ids) 52 | // 遍历wpPosts,然后做向量化处理 53 | for _, wpPost := range wpPosts { 54 | go SingleVectorization(wpPost) 55 | time.Sleep(time.Millisecond * 500) // 休眠 0.5 秒,避免并发过高 56 | } 57 | } 58 | 59 | // 单个处理数据 60 | func SingleVectorization(wpPost model.WpPost) { 61 | var post model.Post 62 | post.PostID = wpPost.ID 63 | post.Status = 1 64 | // 如果文章标题或者内容是空的,则跳过不要处理 65 | if wpPost.PostTitle == "" || wpPost.PostContent == "" { 66 | return 67 | } 68 | // 更新文章状态为1:处理中 69 | err := model.UpdatePost(post) 70 | if err != nil { 71 | // 写入日志 72 | WriteLog(fmt.Sprintf("post_id:%v更新文章状态失败:%v", post.PostID, err)) 73 | return 74 | } 75 | // 获取文章内容 76 | content := wpPost.PostContent 77 | // 获取向量化数据 78 | embedding, err := DataEmbedding(content) 79 | if err != nil { 80 | // 写入日志 81 | WriteLog(fmt.Sprintf("post_id:%v,文章向量化失败:%v", post.PostID, err)) 82 | // 更新文章状态为4:存在错误 83 | post.Status = 4 84 | // 更新文章 85 | model.UpdatePost(post) 86 | return 87 | } 88 | // 更新文章状态为3:已处理 89 | post.Status = 3 90 | post.PostTitle = wpPost.PostTitle 91 | // post.PostDate = wpPost.PostDate 92 | // post.UpdatedAt = &wpPost.PostDate 93 | post.PostContent = content 94 | post.PostDate = wpPost.PostDate 95 | 96 | err = model.UpdatePost(post) 97 | if err != nil { 98 | // 写入日志 99 | WriteLog(fmt.Sprintf("post_id:%v更新文章状态失败:%v", post.PostID, err)) 100 | return 101 | } 102 | // 插入到items表中 103 | item := model.Item{ 104 | PostID: strconv.FormatUint(uint64(post.PostID), 10), 105 | Embedding: embedding, 106 | Title: wpPost.PostTitle, 107 | Content: content, 108 | } 109 | // 插入到vector数据库中 110 | err = model.InsertDocument(item) 111 | if err != nil { 112 | // 写入日志 113 | WriteLog(fmt.Sprintf("post_id:%v,插入向量数据失败:%v", post.PostID, err)) 114 | // 更新文章状态为4:存在错误 115 | post.Status = 4 116 | // 更新文章 117 | model.UpdatePost(post) 118 | return 119 | } 120 | } 121 | 122 | // 数据向量化 123 | func DataEmbedding(input string) ([]float32, error) { 124 | client := resty.New() 125 | 126 | // 请求的URL和headers 127 | url := viper.GetString("embedding.url") // 从配置文件中获取 128 | headers := map[string]string{ 129 | "Authorization": "Bearer " + viper.GetString("embedding.key"), // 替换为你的 API Key 130 | "Content-Type": "application/json", 131 | } 132 | 133 | // 请求的body 134 | body := map[string]interface{}{ 135 | "input": input, 136 | "model": viper.GetString("embedding.model"), // 替换为你的模型名称 137 | "encoding_format": "float", 138 | } 139 | 140 | // 发送POST请求 141 | resp, err := client.R(). 142 | SetHeaders(headers). 143 | SetBody(body). 144 | Post(url) 145 | 146 | if err != nil { 147 | // 写入日志 148 | WriteLog(fmt.Sprintf("请求向量化接口失败:%v", err)) 149 | return nil, err 150 | } 151 | 152 | // 获取响应数据 153 | resBody := resp.Body() 154 | // 转为字符串 155 | bodyStr := string(resBody) 156 | // 获取 "embedding" 数组 157 | embeddingStr := gjson.Get(bodyStr, "data.0.embedding") 158 | 159 | // 提取嵌套数组并将其转换为 []float32 160 | var embedding []float32 161 | for _, v := range embeddingStr.Array() { 162 | // 将字符串转为 float32 并添加到切片中 163 | f, err := strconv.ParseFloat(v.String(), 32) 164 | if err != nil { 165 | // log.Fatalf("Error parsing float: %v", err) 166 | // 写入日志 167 | WriteLog(fmt.Sprintf("Error parsing float: %v", err)) 168 | } 169 | embedding = append(embedding, float32(f)) 170 | } 171 | 172 | return embedding, nil 173 | 174 | } 175 | -------------------------------------------------------------------------------- /utils/helper.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/hex" 6 | "fmt" 7 | "math/rand" 8 | "net" 9 | "strings" 10 | "time" 11 | 12 | "github.com/gin-gonic/gin" 13 | "github.com/spf13/viper" 14 | ) 15 | 16 | func MD5(text string) string { 17 | hasher := md5.New() 18 | hasher.Write([]byte(text)) 19 | return hex.EncodeToString(hasher.Sum(nil)) 20 | } 21 | 22 | // 设置配置文件 23 | func SetConfigStr(key string, value string) bool { 24 | viper.Set(key, value) 25 | err := viper.WriteConfig() 26 | if err != nil { 27 | // 写入错误日志 28 | WriteLog(fmt.Sprintf("%s", err)) 29 | return false 30 | } else { 31 | return true 32 | } 33 | } 34 | 35 | // 生成一个随机字符串 36 | func RandStr(length int) string { 37 | // 定义字符集 38 | charset := "abcdefghijklmnopqrstuvwxyz0123456789" 39 | // 将字符集转换为 rune 切片,以便随机选择字符 40 | charsetRunes := []rune(charset) 41 | 42 | // 创建一个 strings.Builder,用于高效构建字符串 43 | var sb strings.Builder 44 | // 设置 strings.Builder 的初始容量,避免频繁扩容 45 | sb.Grow(length) 46 | 47 | // 使用当前时间作为随机数种子,确保每次运行生成不同的随机字符串 48 | rand.Seed(time.Now().UnixNano()) 49 | 50 | // 循环生成随机字符,并添加到 strings.Builder 中 51 | for i := 0; i < length; i++ { 52 | // 从字符集中随机选择一个字符 53 | randomIndex := rand.Intn(len(charsetRunes)) 54 | randomChar := charsetRunes[randomIndex] 55 | // 将随机字符添加到 strings.Builder 中 56 | sb.WriteRune(randomChar) 57 | } 58 | 59 | // 返回生成的随机字符串 60 | return sb.String() 61 | } 62 | 63 | // 获取客户端IP 64 | func GetClientIP(c *gin.Context) string { 65 | //尝试通过X-Forward-For获取 66 | ip := c.Request.Header.Get("X-Forward-For") 67 | //如果没获取到,则通过X-real-ip获取 68 | if ip == "" { 69 | ip = c.Request.Header.Get("X-real-ip") 70 | } 71 | if ip == "" { 72 | //依然没获取到,则通过gin自身方法获取 73 | ip = c.ClientIP() 74 | } 75 | //判断IP格式是否正确,避免伪造IP 76 | if net.ParseIP(ip) == nil { 77 | ip = "0.0.0.0" 78 | } 79 | return ip 80 | } 81 | -------------------------------------------------------------------------------- /utils/log.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "sync" 8 | ) 9 | 10 | var ( 11 | logger *log.Logger 12 | logFile *os.File 13 | nonce sync.Once 14 | ) 15 | 16 | // LogMessage 记录日志消息到指定文件 17 | func WriteLog(message string) { 18 | nonce.Do(func() { 19 | 20 | // 2. 指定日志文件位置 21 | logFilePath := "data/logs/error.log" 22 | // 检查目录是否存在,不存在则创建 23 | if _, err := os.Stat("data/logs"); os.IsNotExist(err) { 24 | os.Mkdir("data/logs", os.ModePerm) 25 | } 26 | 27 | // 3. 创建或打开日志文件 28 | var err error 29 | logFile, err = os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 30 | if err != nil { 31 | fmt.Printf("Failed to open log file: %v, logging to stderr\n", err) 32 | logFile = os.Stderr // 如果打开文件失败,则输出到标准错误 33 | } 34 | 35 | // 4. 创建 logger 实例 36 | logger = log.New(logFile, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) 37 | }) 38 | 39 | // 5. 写入日志消息 40 | logger.Println(message) 41 | } 42 | 43 | // CloseLogFile 关闭日志文件,正常来说应该在程序退出时调用 44 | func CloseLogFile() { 45 | if logFile != nil && logFile != os.Stderr { 46 | logFile.Close() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /utils/test.go.bak: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "log" 7 | 8 | sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo" 9 | _ "github.com/mattn/go-sqlite3" 10 | ) 11 | 12 | func Test() { 13 | sqlite_vec.Auto() 14 | db, err := sql.Open("sqlite3", "data/db/embeding.db3") 15 | if err != nil { 16 | log.Fatal(err) 17 | } 18 | defer db.Close() 19 | 20 | var sqliteVersion string 21 | var vecVersion string 22 | err = db.QueryRow("select sqlite_version(), vec_version()").Scan(&sqliteVersion, &vecVersion) 23 | if err != nil { 24 | log.Fatal(err) 25 | } 26 | fmt.Printf("sqlite_version=%s, vec_version=%s\n", sqliteVersion, vecVersion) 27 | 28 | _, err = db.Exec("CREATE VIRTUAL TABLE vec_items USING vec0(embedding float[4])") 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | 33 | items := map[int][]float32{ 34 | 1: {0.1, 0.1, 0.1, 0.1}, 35 | 2: {0.2, 0.2, 0.2, 0.2}, 36 | 3: {0.3, 0.3, 0.3, 0.3}, 37 | 4: {0.4, 0.4, 0.4, 0.4}, 38 | 5: {0.5, 0.5, 0.5, 0.5}, 39 | } 40 | q := []float32{0.3, 0.3, 0.3, 0.3} 41 | 42 | for id, values := range items { 43 | v, err := sqlite_vec.SerializeFloat32(values) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | _, err = db.Exec("INSERT INTO vec_items(rowid, embedding) VALUES (?, ?)", id, v) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | } 52 | 53 | query, err := sqlite_vec.SerializeFloat32(q) 54 | if err != nil { 55 | log.Fatal(err) 56 | } 57 | 58 | rows, err := db.Query(` 59 | SELECT 60 | rowid, 61 | distance 62 | FROM vec_items 63 | WHERE embedding MATCH ? 64 | ORDER BY distance 65 | LIMIT 3 66 | `, query) 67 | 68 | if err != nil { 69 | log.Fatal(err) 70 | } 71 | 72 | for rows.Next() { 73 | var rowid int64 74 | var distance float64 75 | err = rows.Scan(&rowid, &distance) 76 | if err != nil { 77 | log.Fatal(err) 78 | } 79 | fmt.Printf("rowid=%d, distance=%f\n", rowid, distance) 80 | } 81 | err = rows.Err() 82 | if err != nil { 83 | log.Fatal((err)) 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /utils/validation.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "net/mail" 5 | "regexp" 6 | ) 7 | 8 | // 接收一个字符串作为参数,然后验证它是否是一个有效的电子邮件地址。 9 | func IsEmail(email string) bool { 10 | // 验证电子邮件地址是否有效 11 | _, err := mail.ParseAddress(email) 12 | if err != nil { 13 | return false // 验证失败,返回 "false" 14 | } 15 | return true 16 | } 17 | 18 | // 验证密码 19 | func IsPassword(password string) bool { 20 | if len(password) < 6 { 21 | return false 22 | } 23 | 24 | // 定义正则表达式 25 | pattern := `^[A-Za-z0-9!@#$%^&\*\.]+$` 26 | regex := regexp.MustCompile(pattern) 27 | 28 | return regex.MatchString(password) 29 | } 30 | -------------------------------------------------------------------------------- /utils/version.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | var Version = "1.0.2" 4 | var VersionDate = "20250305" 5 | --------------------------------------------------------------------------------