├── .env.example ├── .gitignore ├── LICENSE ├── README.md ├── README_original.md ├── addon ├── bootstrap.js ├── chrome.manifest ├── chrome │ ├── content │ │ ├── icons │ │ │ ├── bronze.png │ │ │ ├── favicon.ico │ │ │ ├── favicon@0.5x.ico │ │ │ ├── gold.png │ │ │ ├── gpt.png │ │ │ ├── paperplane-fill.svg │ │ │ ├── papersgpt-logo.png │ │ │ ├── platinum.png │ │ │ ├── silver.png │ │ │ └── subscribe.png │ │ ├── md.css │ │ └── scripts │ │ │ └── index.js │ └── locale │ │ ├── en-US │ │ ├── addon.properties │ │ └── overlay.dtd │ │ └── zh-CN │ │ ├── addon.properties │ │ └── overlay.dtd ├── install.rdf ├── manifest.json ├── out ├── prefs.js └── updates.json ├── content └── icons │ └── stop-circle-fill.svg ├── docs └── teaser.png ├── package-lock.json ├── package.json ├── scripts ├── build.js ├── start.js ├── stop.js └── zotero-cmd.json ├── src ├── addon.ts ├── hooks.ts ├── index.ts ├── modules │ ├── Meet │ │ ├── BetterNotes.ts │ │ ├── Zotero.ts │ │ ├── api.ts │ │ ├── integratellms.ts │ │ └── papersgpt.ts │ ├── base.ts │ ├── base.ts.bak │ ├── localStorage.ts │ ├── locale.ts │ ├── prompts.ts │ ├── utils.ts │ ├── views.ts │ └── views_css.ts └── ztoolkit.ts ├── tags ├── Abstract2Introduction.txt ├── AddTags.txt ├── AskAbstract.txt ├── AskClipboard.txt ├── AskExperimentDetails.txt ├── AskJournal.txt ├── AskPDF.txt ├── Readme.md ├── SearchItems.txt └── Translate.txt ├── tsconfig.json ├── typing └── global.d.ts ├── typings └── prefs.d.ts ├── update-template.json ├── update-template.rdf ├── update.json ├── update.rdf ├── yarn.lock └── zotero-plugin.config.ts /.env.example: -------------------------------------------------------------------------------- 1 | # Path to the Zotero binary file. 2 | # For macOS, the path is typically `*/Zotero.app/Contents/MacOS/zotero`. 3 | ZOTERO_PLUGIN_ZOTERO_BIN_PATH=/Applications/Zotero.app/Contents/MacOS/zotero 4 | 5 | # Path to the profile used for development. 6 | # To create a profile for development, start the profile manager with `/path/to/zotero.exe -p`. 7 | # More info: https://www.zotero.org/support/kb/profile_directory 8 | ZOTERO_PLUGIN_PROFILE_PATH=/Users/daucloud/Library/Application Support/Zotero/Profiles/ni6u6dt3.dev -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | builds/ 2 | node_modules/ 3 | trash/ 4 | 5 | node_modules 6 | .env 7 | .scaffold -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📚 PapersGPT for Zotero - Modified Version by c7w 2 | 3 | ![teaser](docs/teaser.png) 4 | 5 | ## ✨ Features 6 | 7 | ### 🖥️ **Chatbot in the Sidebar** 8 | - The chatbot has been moved from the popup menu to the **sidebar** for a smoother, more integrated experience. 9 | 10 | ### ✋ **Drag-and-Query on the Fly** 11 | - Simply **drag and select** text within Zotero to instantly query the chatbot. No extra steps needed! ⚡ 12 | 13 | ### 🔒 **Customized LLM API Support** 14 | - All online authentication mechanisms of PapersGPT have been **disabled**. 15 | - Only supports LLMs of OpenAI API format with the following options: 16 | - `base_url` 17 | - `model_name` 18 | - `api_key` 19 | 20 | ### 🛠️ **Customizable Prompt Design** 21 | - Create and use your own **custom prompts** via the configuration settings. 🎨 22 | 23 | ## ⚙️ Configuration 24 | 25 | ### Install the Plugin 26 | 27 | To install a plugin in Zotero, download its .xpi file to your computer (from releases in the right panel). Then, in Zotero, click “Tools → Plugins” and drag the .xpi onto the Plugins window. 28 | 29 | ### 🔍 Where Can I Find the Configuration? 30 | 31 | The configuration file for this modified version of PapersGPT is located in Zotero's **profile directory**. You can find your Zotero profile directory in the following locations, depending on your operating system: 32 | 33 | | 🖥️ **Operating System** | 📂 **Path to Profile Directory** | 34 | |--------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 35 | | **Mac** | `/Users//Library/Application Support/Zotero/Profiles/`
**Note:** The `/Library` folder is hidden by default. To access it, click on your desktop, hold down the `Option` key, and click **Go > Library** in the menu. | 36 | | **Windows 11/10/8/7/Vista** | `C:\Users\\AppData\Roaming\Zotero\Zotero\Profiles\`
**Note:** If `AppData` is hidden, open the search bar (or Start menu in older versions), type `%appdata%`, and press Enter to navigate to the `AppData\Roaming` directory. | 37 | | **Windows XP/2000** | `C:\Documents and Settings\\Application Data\Zotero\Zotero\Profiles\` | 38 | | **Linux** | `~/.zotero/zotero/` | 39 | 40 | 41 | Locate `prefs.js` within that folder with random string. 42 | 43 | 44 | ### 🛠️ How to Modify the Configuration 45 | 46 | After installing the plugin and restart Zotero (you can look at the dev console to see a prompt like `Setting default values for custom model`), you can modify the user profile (located above). The following fields can be modified. **NOTE THAT THE FIRST THREE KEYS START WITH `custom`**, NOT `using`!!! 47 | 48 | 1. **API Key**: Set your custom API key for authentication. 49 | ```javascript 50 | user_pref("extensions.zotero.PapersGPT.customModelApiKey", "your-api-key-here"); 51 | ``` 52 | 53 | 2. **Model Name**: Specify the LLM model to use (e.g., `gpt-4o`). 54 | ```javascript 55 | user_pref("extensions.zotero.PapersGPT.customModelApiModel", "gpt-4o"); 56 | ``` 57 | 58 | 3. **API URL**: Define the endpoint of your custom LLM server. 59 | ```javascript 60 | user_pref("extensions.zotero.PapersGPT.customModelApiUrl", "http://your-server-url/v1/chat/completions"); 61 | ``` 62 | 63 | 4. **Custom Prompts**: Add or edit JSON-based prompts for tasks like summarization, translation, etc. 64 | ```javascript 65 | user_pref("extensions.zotero.PapersGPT.prompts", "[{\"name\":\"Summary\",\"prompt\":\"Summarize the text...\"}]"); 66 | ``` 67 | 68 | ### Customized Prompt in Detail 69 | 70 | The value must be a list of `interface Prompt`: 71 | 72 | ```typescript 73 | interface Prompt { 74 | name: string 75 | read_selection: boolean 76 | description: string 77 | prompt: string 78 | display: { 79 | color: string 80 | priority: number 81 | } 82 | } 83 | 84 | ``` 85 | 86 | Below is an example of a customized prompt designed to summarize the abstract of a research paper. This prompt provides detailed instructions for the chatbot's behavior. 87 | 88 | ```typescript 89 | { 90 | name: "Abstract", // Task name 91 | read_selection: true, // Reads selected text in Zotero. If this is false, only the prompt below will be sent to the GPT, and selection wont be considered. 92 | description: "Given abstract, summarize it.", // Brief description of the task 93 | prompt: `# 角色 94 | 你是文献摘要助手,具备快速阅读和理解机器学习文献的能力。 95 | # 工作任务 96 | 你的输入是文献的摘要部分,或简介部分,或两者均有。 97 | 1. 理解工作的背景与应用价值。 98 | 2. 分析之前方法的做法与挑战。 99 | 3. 概述采用的方法与对应的解决挑战。 100 | 4. 汇总实验过程与结论。 101 | 5. 归纳其他摘要中提到的点。 102 | 6. 输出完所有要点后,请根据你的理解,提出几个在这一部分还没有写清楚的问题,以及你认为可以进一步探讨的方向。 103 | # 注意事项 104 | - 确保文献内容准确无误。 105 | - 输出格式需遵循Markdown规范。 106 | - 分点作答,分点作答,分点作答!(把每一点放到四级标题里) 107 | - 保持英文输出。 108 | - 输出尽可能简洁明了,同一个点表达出意思即可,不必过多展开。 109 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $...$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。 110 | # 输入摘要`, 111 | display: { 112 | color: "#0EA293", // Display color in the UI 113 | priority: 10 // Priority for ordering in the interface (lower appears first) 114 | } 115 | } 116 | ``` 117 | 118 | Note that the `Send` button in sidebar can also be viewed as an instance of Prompt with prompt dynamically read from the input element. The `read_selection` can be regarded as set to true. 119 | 120 | ## Recommendation Usage 121 | 122 | - Select `Abstract + Introduction`, and Click `Abstract` to summarize 123 | - Select a subsection of `Method`, and Click `Bullet` to chunkize the text for faster reading 124 | - Select `Any Text`, and Type in the input area for querying 125 | 126 | 127 | ## Development 128 | 129 | 1. Install dependencies by running `npm install` 130 | 2. Configure your development environment by following the instructions in `.env.example`. We recommend creating a dedicated development profile as detailed in the comments. 131 | 3. Create your environment file by renaming `.env.example` to `.env` 132 | 4. Start the development server with `npm run start` or `pnpm run start` 133 | 134 | > Hot reloading functionality is provided by [zotero-plugin-template](https://github.com/windingwind/zotero-plugin-template), enabling real-time development 135 | 136 | Feel free to contribute, report issues, or suggest features! 😊 137 | 138 | -------------------------------------------------------------------------------- /README_original.md: -------------------------------------------------------------------------------- 1 | 2 | # Original README 3 |

4 | PapersGPT For Zotero 5 |

6 | It is a zotero AI plugin for improving your papers reading and research efficently with ChatGPT, Gemini, Claude, DeepSeek, Phi 4, Llama 3.2, Gemma and Mistral. It offers users the ability to ask questions, extract insights, and converse with PDFs directly, providing a powerful research assistant for scholars, researchers, and anyone who deals with large amounts of text in PDF format. 7 | 8 | ## Key Features 9 | 10 | **Lots of SOTA Business LLMs For Choosing:** 11 | 12 | - Powered by the smartest cutting-edge LLMs, offering high accuracy to assist you effectively reading papers. Now support the following latest SOTA models: 13 | *DeepSeek* Beats Claude 3.5 Sonnet + GPT-4o, now the price almost 1/20 of GPT-4o :sparkles: :fire: 14 | *gemini-2.0-flash-thinking* :sparkles: :fire: 15 | *gemini-2.0-flash-exp* :sparkles: :fire: 16 | *gemini-exp-1206* **#1 on Chatbot Arena** :sparkles: :fire: 17 | *gemini-exp-1121* 18 | *LearnLM-1.5* :fire: 19 | *gemini-1.5-pro* 20 | *gemini-1.5-flash* 21 | *gpt-4o-2024-11-20* :fire: 22 | *gpt-4o-mini* 23 | *claude-3.5-sonnet* 24 | *claude-3.5-haiku* 25 | 26 | **Lots of the Latest SOTA Open Source Freely Local LLMs For Mac Users:** 27 | 28 | - There are many SOTA free and open source models built in, Now support the following models: 29 | *Phi-4* :sparkles: :fire: 30 | *Llama3.2* 31 | *QwQ-32B-Preview* :fire: 32 | *Marco-o1* :fire: 33 | *Gemma2* 34 | *Mistral* 35 | After free registration, these models can be automatically downloaded, installed and used with just one click on the plugin page, models are all locally stored, ensuring not sending your data to remote LLMs. 36 | Of course, these models can be switched as your will, and smarter Open Source LLMs in the future would be accessed as soon as possible. 37 | - 100% Privacy and Safe of Your Personal Data. Besides local LLMs, the RAG modules of embeddings, vector database and rerank are all built and runned locally, There will be no data leakage and it can be used normally even on the plane when the internet can't be connected. 38 | - Notice: As reasoning models respond slowly, recommend just to use them to solve hard problems. If you choose QwQ-32B-Preview, ensure your Mac's memory at least 12G 39 | 40 | **Seamless Zotero Integration:** 41 | 42 | - Syncs directly with your Zotero library, making it easy to manage and chat your documents without leaving the Zotero interface. 43 | 44 | ## How to Use 45 | 46 | **Installation:** 47 | 48 | - First download papersgpt.xpi plugin [here](https://github.com/papersgpt/papersgpt-for-zotero/releases/download/papersgpt-v0.0.1/papersgpt.xpi). 49 | Open Zotero in the top menu bar, click on `Tools > Add-ons`. Click on the gear icon at the top right of the window. 50 | Click on `Install Add-on From File` and open the downloaded plugin file papersgpt.xpi. 51 | 52 | **Startup:** 53 | 54 | - In Zotero, press the keys to start the plugin, MacOS(command + enter), Windows(ctrl + enter). 55 | 56 | **Select LLM models:** 57 | 58 | - For Windows users, after registration the OpenAI, Claude, and Gemini models can all be accessed and switched by one click. 59 | - For Mac users, after registration besides the above excellent business models, Phi 4, Llama 3.2, Gemma 2 and Mistral can all be choosed by just one click in plugin without manualy installing many boring additional tools or softwares. 60 | - Now the registration is open and free! 61 | 62 | **Chat PDFs in Zotero:** 63 | 64 | - Open any PDF and start asking questions. PapersGPT will process the document and provide insightful responses. 65 | 66 | **Manage Insights:** 67 | 68 | - Save, export, or share the extracted insights, answers, and annotations from your conversations. 69 | 70 | **Quit:** 71 | 72 | - Press esc key to exit. 73 | 74 | 75 | ## Build the plugin 76 | 77 | If you like to build the plugin by yourself, do as the below commands: 78 | 79 | ```bash 80 | git clone https://github.com/papersgpt/papersgpt-for-zotero.git 81 | cd papersgpt-for-zotero 82 | npm install 83 | npm run build 84 | ``` 85 | The plugin file(papersgpt.xpi) will be built and generated into the build directory 86 | 87 | ## Use Cases 88 | 89 | **Research Assistance:** 90 | 91 | - Summarize research papers, identify key concepts, and quickly get answers to your questions. 92 | 93 | **Academic Writing:** 94 | 95 | - Generate insights for literature reviews or dive deep into specific sections of papers. 96 | 97 | **Collaborative Projects:** 98 | 99 | - Share annotated PDFs and responses with colleagues and teams for smoother collaboration. 100 | 101 | ## Contributions 102 | 103 | Contributions to PapersGPT are welcome! Please follow the standard GitHub process for submitting pull requests or reporting issues. 104 | 105 | ## Acknowledgements 106 | 107 | Inspired by [zotero-gpt](https://github.com/MuiseDestiny/zotero-gpt.git), PapersGPT for Zotero has developed lots of unique, significant features based on it. 108 | -------------------------------------------------------------------------------- /addon/bootstrap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Most of this code is from Zotero team's official Make It Red example[1] 3 | * or the Zotero 7 documentation[2]. 4 | * [1] https://github.com/zotero/make-it-red 5 | * [2] https://www.zotero.org/support/dev/zotero_7_for_developers 6 | */ 7 | 8 | if (typeof Zotero == "undefined") { 9 | var Zotero; 10 | } 11 | 12 | var chromeHandle; 13 | 14 | // In Zotero 6, bootstrap methods are called before Zotero is initialized, and using include.js 15 | // to get the Zotero XPCOM service would risk breaking Zotero startup. Instead, wait for the main 16 | // Zotero window to open and get the Zotero object from there. 17 | // 18 | // In Zotero 7, bootstrap methods are not called until Zotero is initialized, and the 'Zotero' is 19 | // automatically made available. 20 | async function waitForZotero() { 21 | if (typeof Zotero != "undefined") { 22 | await Zotero.initializationPromise; 23 | } 24 | 25 | var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); 26 | var windows = Services.wm.getEnumerator("navigator:browser"); 27 | var found = false; 28 | while (windows.hasMoreElements()) { 29 | let win = windows.getNext(); 30 | if (win.Zotero) { 31 | Zotero = win.Zotero; 32 | found = true; 33 | break; 34 | } 35 | } 36 | if (!found) { 37 | await new Promise((resolve) => { 38 | var listener = { 39 | onOpenWindow: function (aWindow) { 40 | // Wait for the window to finish loading 41 | let domWindow = aWindow 42 | .QueryInterface(Ci.nsIInterfaceRequestor) 43 | .getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow); 44 | domWindow.addEventListener( 45 | "load", 46 | function () { 47 | domWindow.removeEventListener("load", arguments.callee, false); 48 | if (domWindow.Zotero) { 49 | Services.wm.removeListener(listener); 50 | Zotero = domWindow.Zotero; 51 | resolve(); 52 | } 53 | }, 54 | false 55 | ); 56 | }, 57 | }; 58 | Services.wm.addListener(listener); 59 | }); 60 | } 61 | await Zotero.initializationPromise; 62 | } 63 | 64 | function install(data, reason) {} 65 | 66 | async function startup({ id, version, resourceURI, rootURI }, reason) { 67 | await waitForZotero(); 68 | 69 | // String 'rootURI' introduced in Zotero 7 70 | if (!rootURI) { 71 | rootURI = resourceURI.spec; 72 | } 73 | 74 | if (Zotero.platformMajorVersion >= 102) { 75 | var aomStartup = Components.classes[ 76 | "@mozilla.org/addons/addon-manager-startup;1" 77 | ].getService(Components.interfaces.amIAddonManagerStartup); 78 | var manifestURI = Services.io.newURI(rootURI + "manifest.json"); 79 | chromeHandle = aomStartup.registerChrome(manifestURI, [ 80 | ["content", "__addonRef__", rootURI + "chrome/content/"], 81 | ["locale", "__addonRef__", "en-US", rootURI + "chrome/locale/en-US/"], 82 | ["locale", "__addonRef__", "zh-CN", rootURI + "chrome/locale/zh-CN/"], 83 | ]); 84 | } else { 85 | setDefaultPrefs(rootURI); 86 | } 87 | 88 | /** 89 | * Global variables for plugin code. 90 | * The `_globalThis` is the global root variable of the plugin sandbox environment 91 | * and all child variables assigned to it is globally accessible. 92 | * See `src/index.ts` for details. 93 | */ 94 | const ctx = { 95 | rootURI, 96 | }; 97 | ctx._globalThis = ctx; 98 | 99 | Services.scriptloader.loadSubScript( 100 | `${rootURI}/chrome/content/scripts/index.js`, 101 | ctx 102 | ); 103 | } 104 | 105 | function shutdown({ id, version, resourceURI, rootURI }, reason) { 106 | if (reason === APP_SHUTDOWN) { 107 | return; 108 | } 109 | if (typeof Zotero === "undefined") { 110 | Zotero = Components.classes["@zotero.org/Zotero;1"].getService( 111 | Components.interfaces.nsISupports 112 | ).wrappedJSObject; 113 | } 114 | Zotero.__addonInstance__.hooks.onShutdown(); 115 | 116 | Cc["@mozilla.org/intl/stringbundle;1"] 117 | .getService(Components.interfaces.nsIStringBundleService) 118 | .flushBundles(); 119 | 120 | Cu.unload(`${rootURI}/chrome/content/scripts/index.js`); 121 | 122 | if (chromeHandle) { 123 | chromeHandle.destruct(); 124 | chromeHandle = null; 125 | } 126 | } 127 | 128 | function uninstall(data, reason) {} 129 | 130 | // Loads default preferences from defaults/preferences/prefs.js in Zotero 6 131 | function setDefaultPrefs(rootURI) { 132 | var branch = Services.prefs.getDefaultBranch(""); 133 | var obj = { 134 | pref(pref, value) { 135 | switch (typeof value) { 136 | case "boolean": 137 | branch.setBoolPref(pref, value); 138 | break; 139 | case "string": 140 | branch.setStringPref(pref, value); 141 | break; 142 | case "number": 143 | branch.setIntPref(pref, value); 144 | break; 145 | default: 146 | Zotero.logError(`Invalid type '${typeof value}' for pref '${pref}'`); 147 | } 148 | }, 149 | }; 150 | Zotero.getMainWindow().console.log(rootURI + "prefs.js"); 151 | Services.scriptloader.loadSubScript(rootURI + "prefs.js", obj); 152 | } 153 | -------------------------------------------------------------------------------- /addon/chrome.manifest: -------------------------------------------------------------------------------- 1 | content __addonRef__ chrome/content/ 2 | locale __addonRef__ en-US chrome/locale/en-US/ 3 | locale __addonRef__ zh-CN chrome/locale/zh-CN/ 4 | -------------------------------------------------------------------------------- /addon/chrome/content/icons/bronze.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/bronze.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/favicon.ico -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon@0.5x.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/favicon@0.5x.ico -------------------------------------------------------------------------------- /addon/chrome/content/icons/gold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/gold.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/gpt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/gpt.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/paperplane-fill.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /addon/chrome/content/icons/papersgpt-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/papersgpt-logo.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/platinum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/platinum.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/silver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/silver.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/subscribe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/chrome/content/icons/subscribe.png -------------------------------------------------------------------------------- /addon/chrome/content/md.css: -------------------------------------------------------------------------------- 1 | .markdown-body { 2 | --color-prettylights-syntax-comment: #6e7781; 3 | --color-prettylights-syntax-constant: #0550ae; 4 | --color-prettylights-syntax-entity: #8250df; 5 | --color-prettylights-syntax-storage-modifier-import: #24292f; 6 | --color-prettylights-syntax-entity-tag: #116329; 7 | --color-prettylights-syntax-keyword: #cf222e; 8 | --color-prettylights-syntax-string: #0a3069; 9 | --color-prettylights-syntax-variable: #953800; 10 | --color-prettylights-syntax-brackethighlighter-unmatched: #82071e; 11 | --color-prettylights-syntax-invalid-illegal-text: #f6f8fa; 12 | --color-prettylights-syntax-invalid-illegal-bg: #82071e; 13 | --color-prettylights-syntax-carriage-return-text: #f6f8fa; 14 | --color-prettylights-syntax-carriage-return-bg: #cf222e; 15 | --color-prettylights-syntax-string-regexp: #116329; 16 | --color-prettylights-syntax-markup-list: #3b2300; 17 | --color-prettylights-syntax-markup-heading: #0550ae; 18 | --color-prettylights-syntax-markup-italic: #24292f; 19 | --color-prettylights-syntax-markup-bold: #24292f; 20 | --color-prettylights-syntax-markup-deleted-text: #82071e; 21 | --color-prettylights-syntax-markup-deleted-bg: #ffebe9; 22 | --color-prettylights-syntax-markup-inserted-text: #116329; 23 | --color-prettylights-syntax-markup-inserted-bg: #dafbe1; 24 | --color-prettylights-syntax-markup-changed-text: #953800; 25 | --color-prettylights-syntax-markup-changed-bg: #ffd8b5; 26 | --color-prettylights-syntax-markup-ignored-text: #eaeef2; 27 | --color-prettylights-syntax-markup-ignored-bg: #0550ae; 28 | --color-prettylights-syntax-meta-diff-range: #8250df; 29 | --color-prettylights-syntax-brackethighlighter-angle: #57606a; 30 | --color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f; 31 | --color-prettylights-syntax-constant-other-reference-link: #0a3069; 32 | --color-fg-default: #24292f; 33 | --color-fg-muted: #57606a; 34 | --color-fg-subtle: #6e7781; 35 | --color-canvas-default: transparent; 36 | --color-canvas-subtle: rgba(89, 192, 188, .1); 37 | --color-border-default: #d0d7de; 38 | --color-border-muted: rgba(89, 192, 188, .2); 39 | --color-neutral-muted: rgba(89, 192, 188, .2); 40 | --color-accent-fg: #0969da; 41 | --color-accent-emphasis: #0969da; 42 | --color-attention-subtle: #fff8c5; 43 | --color-danger-fg: #cf222e 44 | } 45 | 46 | .markdown-body { 47 | -ms-text-size-adjust: 100%; 48 | -webkit-text-size-adjust: 100%; 49 | margin: 0; 50 | color: var(--color-fg-default); 51 | background-color: var(--color-canvas-default); 52 | font-family: -apple-system, BlinkMacSystemFont, segoe ui, noto sans, Helvetica, Arial, sans-serif, apple color emoji, segoe ui emoji; 53 | font-size: 16px; 54 | line-height: 1.5; 55 | word-wrap: break-word 56 | } 57 | 58 | .markdown-body .octicon { 59 | display: inline-block; 60 | fill: currentColor; 61 | vertical-align: text-bottom 62 | } 63 | 64 | .markdown-body h1:hover .anchor .octicon-link:before, 65 | .markdown-body h2:hover .anchor .octicon-link:before, 66 | .markdown-body h3:hover .anchor .octicon-link:before, 67 | .markdown-body h4:hover .anchor .octicon-link:before, 68 | .markdown-body h5:hover .anchor .octicon-link:before, 69 | .markdown-body h6:hover .anchor .octicon-link:before { 70 | width: 16px; 71 | height: 16px; 72 | content: ' '; 73 | display: inline-block; 74 | background-color: currentColor; 75 | -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=); 76 | mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=) 77 | } 78 | 79 | .markdown-body details, 80 | .markdown-body figcaption, 81 | .markdown-body figure { 82 | display: block 83 | } 84 | 85 | .markdown-body summary { 86 | display: list-item 87 | } 88 | 89 | .markdown-body [hidden] { 90 | display: none !important 91 | } 92 | 93 | .markdown-body a { 94 | background-color: transparent; 95 | color: var(--color-accent-fg); 96 | text-decoration: none 97 | } 98 | 99 | .markdown-body abbr[title] { 100 | border-bottom: none; 101 | text-decoration: underline dotted 102 | } 103 | 104 | .markdown-body b, 105 | .markdown-body strong { 106 | font-weight: var(--base-text-weight-semibold, 600) 107 | } 108 | 109 | .markdown-body dfn { 110 | font-style: italic 111 | } 112 | 113 | .markdown-body h1 { 114 | margin: .67em 0; 115 | font-weight: var(--base-text-weight-semibold, 600); 116 | padding-bottom: .3em; 117 | font-size: 2em; 118 | border-bottom: 1px solid var(--color-border-muted) 119 | } 120 | 121 | .markdown-body mark { 122 | background-color: var(--color-attention-subtle); 123 | color: var(--color-fg-default) 124 | } 125 | 126 | .markdown-body small { 127 | font-size: 90% 128 | } 129 | 130 | .markdown-body sub, 131 | .markdown-body sup { 132 | font-size: 75%; 133 | line-height: 0; 134 | position: relative; 135 | vertical-align: baseline 136 | } 137 | 138 | .markdown-body sub { 139 | bottom: -.25em 140 | } 141 | 142 | .markdown-body sup { 143 | top: -.5em 144 | } 145 | 146 | .markdown-body img { 147 | border-style: none; 148 | max-width: 100%; 149 | box-sizing: content-box; 150 | background-color: var(--color-canvas-default) 151 | } 152 | 153 | .markdown-body code, 154 | .markdown-body kbd, 155 | .markdown-body pre, 156 | .markdown-body samp { 157 | font-family: monospace; 158 | font-size: 1em 159 | } 160 | 161 | .markdown-body figure { 162 | margin: 1em 40px 163 | } 164 | 165 | .markdown-body hr { 166 | box-sizing: content-box; 167 | overflow: hidden; 168 | background: 0 0; 169 | border-bottom: 1px solid var(--color-border-muted); 170 | height: .25em; 171 | padding: 0; 172 | margin: 24px 0; 173 | background-color: var(--color-border-default); 174 | border: 0 175 | } 176 | 177 | .markdown-body input { 178 | font: inherit; 179 | margin: 0; 180 | overflow: visible; 181 | font-family: inherit; 182 | font-size: inherit; 183 | line-height: inherit 184 | } 185 | 186 | .markdown-body [type=button], 187 | .markdown-body [type=reset], 188 | .markdown-body [type=submit] { 189 | -webkit-appearance: button 190 | } 191 | 192 | .markdown-body [type=checkbox], 193 | .markdown-body [type=radio] { 194 | box-sizing: border-box; 195 | padding: 0 196 | } 197 | 198 | .markdown-body [type=number]::-webkit-inner-spin-button, 199 | .markdown-body [type=number]::-webkit-outer-spin-button { 200 | height: auto 201 | } 202 | 203 | .markdown-body [type=search]::-webkit-search-cancel-button, 204 | .markdown-body [type=search]::-webkit-search-decoration { 205 | -webkit-appearance: none 206 | } 207 | 208 | .markdown-body ::-webkit-input-placeholder { 209 | color: inherit; 210 | opacity: .54 211 | } 212 | 213 | .markdown-body ::-webkit-file-upload-button { 214 | -webkit-appearance: button; 215 | font: inherit 216 | } 217 | 218 | .markdown-body a:hover { 219 | text-decoration: underline 220 | } 221 | 222 | .markdown-body ::placeholder { 223 | color: var(--color-fg-subtle); 224 | opacity: 1 225 | } 226 | 227 | .markdown-body hr::before { 228 | display: table; 229 | content: "" 230 | } 231 | 232 | .markdown-body hr::after { 233 | display: table; 234 | clear: both; 235 | content: "" 236 | } 237 | 238 | .markdown-body table { 239 | border-spacing: 0; 240 | border-collapse: collapse; 241 | display: block; 242 | width: max-content; 243 | max-width: 100%; 244 | overflow: auto; 245 | } 246 | 247 | .markdown-body td, 248 | .markdown-body th { 249 | padding: 0 250 | } 251 | 252 | .markdown-body details summary { 253 | cursor: pointer 254 | } 255 | 256 | .markdown-body details:not([open])>*:not(summary) { 257 | display: none !important 258 | } 259 | 260 | .markdown-body a:focus, 261 | .markdown-body [role=button]:focus, 262 | .markdown-body input[type=radio]:focus, 263 | .markdown-body input[type=checkbox]:focus { 264 | outline: 2px solid var(--color-accent-fg); 265 | outline-offset: -2px; 266 | box-shadow: none 267 | } 268 | 269 | .markdown-body a:focus:not(:focus-visible), 270 | .markdown-body [role=button]:focus:not(:focus-visible), 271 | .markdown-body input[type=radio]:focus:not(:focus-visible), 272 | .markdown-body input[type=checkbox]:focus:not(:focus-visible) { 273 | outline: solid 1px transparent 274 | } 275 | 276 | .markdown-body a:focus-visible, 277 | .markdown-body [role=button]:focus-visible, 278 | .markdown-body input[type=radio]:focus-visible, 279 | .markdown-body input[type=checkbox]:focus-visible { 280 | outline: 2px solid var(--color-accent-fg); 281 | outline-offset: -2px; 282 | box-shadow: none 283 | } 284 | 285 | .markdown-body a:not([class]):focus, 286 | .markdown-body a:not([class]):focus-visible, 287 | .markdown-body input[type=radio]:focus, 288 | .markdown-body input[type=radio]:focus-visible, 289 | .markdown-body input[type=checkbox]:focus, 290 | .markdown-body input[type=checkbox]:focus-visible { 291 | outline-offset: 0 292 | } 293 | 294 | .markdown-body kbd { 295 | display: inline-block; 296 | padding: 3px 5px; 297 | font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; 298 | line-height: 10px; 299 | color: var(--color-fg-default); 300 | vertical-align: middle; 301 | background-color: var(--color-canvas-subtle); 302 | border: solid 1px var(--color-neutral-muted); 303 | border-bottom-color: var(--color-neutral-muted); 304 | border-radius: 6px; 305 | box-shadow: inset 0 -1px 0 var(--color-neutral-muted) 306 | } 307 | 308 | .markdown-body h1, 309 | .markdown-body h2, 310 | .markdown-body h3, 311 | .markdown-body h4, 312 | .markdown-body h5, 313 | .markdown-body h6 { 314 | margin-top: 24px; 315 | margin-bottom: 16px; 316 | font-weight: var(--base-text-weight-semibold, 600); 317 | line-height: 1.25 318 | } 319 | 320 | .markdown-body h2 { 321 | font-weight: var(--base-text-weight-semibold, 600); 322 | padding-bottom: .3em; 323 | font-size: 1.5em; 324 | border-bottom: 1px solid var(--color-border-muted) 325 | } 326 | 327 | .markdown-body h3 { 328 | font-weight: var(--base-text-weight-semibold, 600); 329 | font-size: 1.25em 330 | } 331 | 332 | .markdown-body h4 { 333 | font-weight: var(--base-text-weight-semibold, 600); 334 | font-size: 1em 335 | } 336 | 337 | .markdown-body h5 { 338 | font-weight: var(--base-text-weight-semibold, 600); 339 | font-size: .875em 340 | } 341 | 342 | .markdown-body h6 { 343 | font-weight: var(--base-text-weight-semibold, 600); 344 | font-size: .85em; 345 | color: var(--color-fg-muted) 346 | } 347 | 348 | .markdown-body p { 349 | margin-top: 0; 350 | margin-bottom: 10px 351 | } 352 | 353 | .markdown-body blockquote { 354 | margin: 0; 355 | padding: 0 1em; 356 | color: var(--color-fg-muted); 357 | border-left: .25em solid var(--color-border-default) 358 | } 359 | 360 | .markdown-body ul, 361 | .markdown-body ol { 362 | margin-top: 0; 363 | margin-bottom: 0; 364 | padding-left: 2em 365 | } 366 | 367 | .markdown-body ol ol, 368 | .markdown-body ul ol { 369 | list-style-type: lower-roman 370 | } 371 | 372 | .markdown-body ul ul ol, 373 | .markdown-body ul ol ol, 374 | .markdown-body ol ul ol, 375 | .markdown-body ol ol ol { 376 | list-style-type: lower-alpha 377 | } 378 | 379 | .markdown-body dd { 380 | margin-left: 0 381 | } 382 | 383 | .markdown-body tt, 384 | .markdown-body code, 385 | .markdown-body samp { 386 | font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; 387 | font-size: 12px 388 | } 389 | 390 | .markdown-body pre { 391 | margin-top: 0; 392 | margin-bottom: 0; 393 | font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; 394 | font-size: 12px; 395 | word-wrap: normal 396 | } 397 | 398 | .markdown-body .octicon { 399 | display: inline-block; 400 | overflow: visible !important; 401 | vertical-align: text-bottom; 402 | fill: currentColor 403 | } 404 | 405 | .markdown-body input::-webkit-outer-spin-button, 406 | .markdown-body input::-webkit-inner-spin-button { 407 | margin: 0; 408 | -webkit-appearance: none; 409 | appearance: none 410 | } 411 | 412 | .markdown-body::before { 413 | display: table; 414 | content: "" 415 | } 416 | 417 | .markdown-body::after { 418 | display: table; 419 | clear: both; 420 | content: "" 421 | } 422 | 423 | .markdown-body>*:first-child { 424 | margin-top: 0.25em !important 425 | } 426 | 427 | .markdown-body>*:last-child { 428 | margin-bottom: 0.25em !important 429 | } 430 | 431 | .markdown-body a:not([href]) { 432 | color: inherit; 433 | text-decoration: none 434 | } 435 | 436 | .markdown-body .absent { 437 | color: var(--color-danger-fg) 438 | } 439 | 440 | .markdown-body .anchor { 441 | float: left; 442 | padding-right: 4px; 443 | margin-left: -20px; 444 | line-height: 1 445 | } 446 | 447 | .markdown-body .anchor:focus { 448 | outline: none 449 | } 450 | 451 | .markdown-body p, 452 | .markdown-body blockquote, 453 | .markdown-body ul, 454 | .markdown-body ol, 455 | .markdown-body dl, 456 | .markdown-body table, 457 | .markdown-body pre, 458 | .markdown-body details { 459 | margin-top: 0; 460 | margin-bottom: 16px 461 | } 462 | 463 | .markdown-body blockquote>:first-child { 464 | margin-top: 0 465 | } 466 | 467 | .markdown-body blockquote>:last-child { 468 | margin-bottom: 0 469 | } 470 | 471 | .markdown-body h1 .octicon-link, 472 | .markdown-body h2 .octicon-link, 473 | .markdown-body h3 .octicon-link, 474 | .markdown-body h4 .octicon-link, 475 | .markdown-body h5 .octicon-link, 476 | .markdown-body h6 .octicon-link { 477 | color: var(--color-fg-default); 478 | vertical-align: middle; 479 | visibility: hidden 480 | } 481 | 482 | .markdown-body h1:hover .anchor, 483 | .markdown-body h2:hover .anchor, 484 | .markdown-body h3:hover .anchor, 485 | .markdown-body h4:hover .anchor, 486 | .markdown-body h5:hover .anchor, 487 | .markdown-body h6:hover .anchor { 488 | text-decoration: none 489 | } 490 | 491 | .markdown-body h1:hover .anchor .octicon-link, 492 | .markdown-body h2:hover .anchor .octicon-link, 493 | .markdown-body h3:hover .anchor .octicon-link, 494 | .markdown-body h4:hover .anchor .octicon-link, 495 | .markdown-body h5:hover .anchor .octicon-link, 496 | .markdown-body h6:hover .anchor .octicon-link { 497 | visibility: visible 498 | } 499 | 500 | .markdown-body h1 tt, 501 | .markdown-body h1 code, 502 | .markdown-body h2 tt, 503 | .markdown-body h2 code, 504 | .markdown-body h3 tt, 505 | .markdown-body h3 code, 506 | .markdown-body h4 tt, 507 | .markdown-body h4 code, 508 | .markdown-body h5 tt, 509 | .markdown-body h5 code, 510 | .markdown-body h6 tt, 511 | .markdown-body h6 code { 512 | padding: 0 .2em; 513 | font-size: inherit 514 | } 515 | 516 | .markdown-body summary h1, 517 | .markdown-body summary h2, 518 | .markdown-body summary h3, 519 | .markdown-body summary h4, 520 | .markdown-body summary h5, 521 | .markdown-body summary h6 { 522 | display: inline-block 523 | } 524 | 525 | .markdown-body summary h1 .anchor, 526 | .markdown-body summary h2 .anchor, 527 | .markdown-body summary h3 .anchor, 528 | .markdown-body summary h4 .anchor, 529 | .markdown-body summary h5 .anchor, 530 | .markdown-body summary h6 .anchor { 531 | margin-left: -40px 532 | } 533 | 534 | .markdown-body summary h1, 535 | .markdown-body summary h2 { 536 | padding-bottom: 0; 537 | border-bottom: 0 538 | } 539 | 540 | .markdown-body ul.no-list, 541 | .markdown-body ol.no-list { 542 | padding: 0; 543 | list-style-type: none 544 | } 545 | 546 | .markdown-body ol[type=a] { 547 | list-style-type: lower-alpha 548 | } 549 | 550 | .markdown-body ol[type=A] { 551 | list-style-type: upper-alpha 552 | } 553 | 554 | .markdown-body ol[type=i] { 555 | list-style-type: lower-roman 556 | } 557 | 558 | .markdown-body ol[type=I] { 559 | list-style-type: upper-roman 560 | } 561 | 562 | .markdown-body ol[type="1"] { 563 | list-style-type: decimal 564 | } 565 | 566 | .markdown-body div>ol:not([type]) { 567 | list-style-type: decimal 568 | } 569 | 570 | .markdown-body ul ul, 571 | .markdown-body ul ol, 572 | .markdown-body ol ol, 573 | .markdown-body ol ul { 574 | margin-top: 0; 575 | margin-bottom: 0 576 | } 577 | 578 | .markdown-body li>p { 579 | margin-top: 16px 580 | } 581 | 582 | .markdown-body li+li { 583 | margin-top: .25em 584 | } 585 | 586 | .markdown-body dl { 587 | padding: 0 588 | } 589 | 590 | .markdown-body dl dt { 591 | padding: 0; 592 | margin-top: 16px; 593 | font-size: 1em; 594 | font-style: italic; 595 | font-weight: var(--base-text-weight-semibold, 600) 596 | } 597 | 598 | .markdown-body dl dd { 599 | padding: 0 16px; 600 | margin-bottom: 16px 601 | } 602 | 603 | .markdown-body table th { 604 | font-weight: var(--base-text-weight-semibold, 600) 605 | } 606 | 607 | .markdown-body table th, 608 | .markdown-body table td { 609 | padding: 6px 13px; 610 | border: 1px solid var(--color-border-default) 611 | } 612 | 613 | .markdown-body table tr { 614 | background-color: var(--color-canvas-default); 615 | border-top: 1px solid var(--color-border-muted) 616 | } 617 | 618 | .markdown-body table tr:nth-child(2n) { 619 | background-color: var(--color-canvas-subtle) 620 | } 621 | 622 | .markdown-body table img { 623 | background-color: transparent 624 | } 625 | 626 | .markdown-body img[align=right] { 627 | padding-left: 20px 628 | } 629 | 630 | .markdown-body img[align=left] { 631 | padding-right: 20px 632 | } 633 | 634 | .markdown-body .emoji { 635 | max-width: none; 636 | vertical-align: text-top; 637 | background-color: transparent 638 | } 639 | 640 | .markdown-body span.frame { 641 | display: block; 642 | overflow: hidden 643 | } 644 | 645 | .markdown-body span.frame>span { 646 | display: block; 647 | float: left; 648 | width: auto; 649 | padding: 7px; 650 | margin: 13px 0 0; 651 | overflow: hidden; 652 | border: 1px solid var(--color-border-default) 653 | } 654 | 655 | .markdown-body span.frame span img { 656 | display: block; 657 | float: left 658 | } 659 | 660 | .markdown-body span.frame span span { 661 | display: block; 662 | padding: 5px 0 0; 663 | clear: both; 664 | color: var(--color-fg-default) 665 | } 666 | 667 | .markdown-body span.align-center { 668 | display: block; 669 | overflow: hidden; 670 | clear: both 671 | } 672 | 673 | .markdown-body span.align-center>span { 674 | display: block; 675 | margin: 13px auto 0; 676 | overflow: hidden; 677 | text-align: center 678 | } 679 | 680 | .markdown-body span.align-center span img { 681 | margin: 0 auto; 682 | text-align: center 683 | } 684 | 685 | .markdown-body span.align-right { 686 | display: block; 687 | overflow: hidden; 688 | clear: both 689 | } 690 | 691 | .markdown-body span.align-right>span { 692 | display: block; 693 | margin: 13px 0 0; 694 | overflow: hidden; 695 | text-align: right 696 | } 697 | 698 | .markdown-body span.align-right span img { 699 | margin: 0; 700 | text-align: right 701 | } 702 | 703 | .markdown-body span.float-left { 704 | display: block; 705 | float: left; 706 | margin-right: 13px; 707 | overflow: hidden 708 | } 709 | 710 | .markdown-body span.float-left span { 711 | margin: 13px 0 0 712 | } 713 | 714 | .markdown-body span.float-right { 715 | display: block; 716 | float: right; 717 | margin-left: 13px; 718 | overflow: hidden 719 | } 720 | 721 | .markdown-body span.float-right>span { 722 | display: block; 723 | margin: 13px auto 0; 724 | overflow: hidden; 725 | text-align: right 726 | } 727 | 728 | .markdown-body code, 729 | .markdown-body tt { 730 | padding: .2em .4em; 731 | margin: 0; 732 | font-size: 85%; 733 | white-space: break-spaces; 734 | background-color: var(--color-neutral-muted); 735 | border-radius: 6px 736 | } 737 | 738 | .markdown-body code br, 739 | .markdown-body tt br { 740 | display: none 741 | } 742 | 743 | .markdown-body del code { 744 | text-decoration: inherit 745 | } 746 | 747 | .markdown-body samp { 748 | font-size: 85% 749 | } 750 | 751 | .markdown-body pre code { 752 | font-size: 100% 753 | } 754 | 755 | .markdown-body pre>code { 756 | padding: 0; 757 | margin: 0; 758 | word-break: normal; 759 | white-space: pre; 760 | background: 0 0; 761 | border: 0 762 | } 763 | 764 | .markdown-body .highlight { 765 | margin-bottom: 16px 766 | } 767 | 768 | .markdown-body .highlight pre { 769 | margin-bottom: 0; 770 | word-break: normal 771 | } 772 | 773 | .markdown-body .highlight pre, 774 | .markdown-body pre { 775 | padding: 16px; 776 | overflow: auto; 777 | font-size: 85%; 778 | line-height: 1.45; 779 | background-color: var(--color-canvas-subtle); 780 | border-radius: 6px 781 | } 782 | 783 | .markdown-body pre code, 784 | .markdown-body pre tt { 785 | display: inline; 786 | max-width: auto; 787 | padding: 0; 788 | margin: 0; 789 | overflow: visible; 790 | line-height: inherit; 791 | word-wrap: normal; 792 | background-color: transparent; 793 | border: 0 794 | } 795 | 796 | .markdown-body .csv-data td, 797 | .markdown-body .csv-data th { 798 | padding: 5px; 799 | overflow: hidden; 800 | font-size: 12px; 801 | line-height: 1; 802 | text-align: left; 803 | white-space: nowrap 804 | } 805 | 806 | .markdown-body .csv-data .blob-num { 807 | padding: 10px 8px 9px; 808 | text-align: right; 809 | background: var(--color-canvas-default); 810 | border: 0 811 | } 812 | 813 | .markdown-body .csv-data tr { 814 | border-top: 0 815 | } 816 | 817 | .markdown-body .csv-data th { 818 | font-weight: var(--base-text-weight-semibold, 600); 819 | background: var(--color-canvas-subtle); 820 | border-top: 0 821 | } 822 | 823 | .markdown-body [data-footnote-ref]::before { 824 | content: "[" 825 | } 826 | @-webkit-keyframes blink { 827 | to { 828 | visibility: hidden; 829 | } 830 | } 831 | @keyframes blink { 832 | to { 833 | visibility: hidden; 834 | } 835 | } 836 | 837 | .markdown-body math { 838 | display: none; 839 | } 840 | .markdown-body svg { 841 | margin-left: 0.25em; 842 | margin-right: 0.25em; 843 | } 844 | 845 | .streaming>span:after, 846 | .streaming>ul:last-child li:last-child:after, 847 | .streaming>pre:last-child code:after, 848 | .streaming>ol:last-child li:last-child:after, 849 | .streaming>:not(ol):not(ul):not(pre):last-child:after { 850 | -webkit-animation: blink 1s steps(5, start) infinite !important; 851 | animation: blink 1s steps(5, start) infinite !important; 852 | content: "▋"; 853 | margin-left: .25rem; 854 | vertical-align: baseline 855 | } 856 | 857 | .markdown-body [data-footnote-ref]::after { 858 | content: "]" 859 | } 860 | 861 | .markdown-body .footnotes { 862 | font-size: 12px; 863 | color: var(--color-fg-muted); 864 | border-top: 1px solid var(--color-border-default) 865 | } 866 | 867 | .markdown-body .footnotes ol { 868 | padding-left: 16px 869 | } 870 | 871 | .markdown-body .footnotes ol ul { 872 | display: inline-block; 873 | padding-left: 16px; 874 | margin-top: 16px 875 | } 876 | 877 | .markdown-body .footnotes li { 878 | position: relative 879 | } 880 | 881 | .markdown-body .footnotes li:target::before { 882 | position: absolute; 883 | top: -8px; 884 | right: -8px; 885 | bottom: -8px; 886 | left: -24px; 887 | pointer-events: none; 888 | content: ""; 889 | border: 2px solid var(--color-accent-emphasis); 890 | border-radius: 6px 891 | } 892 | 893 | .markdown-body .footnotes li:target { 894 | color: var(--color-fg-default) 895 | } 896 | 897 | .markdown-body .footnotes .data-footnote-backref g-emoji { 898 | font-family: monospace 899 | } 900 | 901 | .markdown-body .pl-c { 902 | color: var(--color-prettylights-syntax-comment) 903 | } 904 | 905 | .markdown-body .pl-c1, 906 | .markdown-body .pl-s .pl-v { 907 | color: var(--color-prettylights-syntax-constant) 908 | } 909 | 910 | .markdown-body .pl-e, 911 | .markdown-body .pl-en { 912 | color: var(--color-prettylights-syntax-entity) 913 | } 914 | 915 | .markdown-body .pl-smi, 916 | .markdown-body .pl-s .pl-s1 { 917 | color: var(--color-prettylights-syntax-storage-modifier-import) 918 | } 919 | 920 | .markdown-body .pl-ent { 921 | color: var(--color-prettylights-syntax-entity-tag) 922 | } 923 | 924 | .markdown-body .pl-k { 925 | color: var(--color-prettylights-syntax-keyword) 926 | } 927 | 928 | .markdown-body .pl-s, 929 | .markdown-body .pl-pds, 930 | .markdown-body .pl-s .pl-pse .pl-s1, 931 | .markdown-body .pl-sr, 932 | .markdown-body .pl-sr .pl-cce, 933 | .markdown-body .pl-sr .pl-sre, 934 | .markdown-body .pl-sr .pl-sra { 935 | color: var(--color-prettylights-syntax-string) 936 | } 937 | 938 | .markdown-body .pl-v, 939 | .markdown-body .pl-smw { 940 | color: var(--color-prettylights-syntax-variable) 941 | } 942 | 943 | .markdown-body .pl-bu { 944 | color: var(--color-prettylights-syntax-brackethighlighter-unmatched) 945 | } 946 | 947 | .markdown-body .pl-ii { 948 | color: var(--color-prettylights-syntax-invalid-illegal-text); 949 | background-color: var(--color-prettylights-syntax-invalid-illegal-bg) 950 | } 951 | 952 | .markdown-body .pl-c2 { 953 | color: var(--color-prettylights-syntax-carriage-return-text); 954 | background-color: var(--color-prettylights-syntax-carriage-return-bg) 955 | } 956 | 957 | .markdown-body .pl-sr .pl-cce { 958 | font-weight: 700; 959 | color: var(--color-prettylights-syntax-string-regexp) 960 | } 961 | 962 | .markdown-body .pl-ml { 963 | color: var(--color-prettylights-syntax-markup-list) 964 | } 965 | 966 | .markdown-body .pl-mh, 967 | .markdown-body .pl-mh .pl-en, 968 | .markdown-body .pl-ms { 969 | font-weight: 700; 970 | color: var(--color-prettylights-syntax-markup-heading) 971 | } 972 | 973 | .markdown-body .pl-mi { 974 | font-style: italic; 975 | color: var(--color-prettylights-syntax-markup-italic) 976 | } 977 | 978 | .markdown-body .pl-mb { 979 | font-weight: 700; 980 | color: var(--color-prettylights-syntax-markup-bold) 981 | } 982 | 983 | .markdown-body .pl-md { 984 | color: var(--color-prettylights-syntax-markup-deleted-text); 985 | background-color: var(--color-prettylights-syntax-markup-deleted-bg) 986 | } 987 | 988 | .markdown-body .pl-mi1 { 989 | color: var(--color-prettylights-syntax-markup-inserted-text); 990 | background-color: var(--color-prettylights-syntax-markup-inserted-bg) 991 | } 992 | 993 | .markdown-body .pl-mc { 994 | color: var(--color-prettylights-syntax-markup-changed-text); 995 | background-color: var(--color-prettylights-syntax-markup-changed-bg) 996 | } 997 | 998 | .markdown-body .pl-mi2 { 999 | color: var(--color-prettylights-syntax-markup-ignored-text); 1000 | background-color: var(--color-prettylights-syntax-markup-ignored-bg) 1001 | } 1002 | 1003 | .markdown-body .pl-mdr { 1004 | font-weight: 700; 1005 | color: var(--color-prettylights-syntax-meta-diff-range) 1006 | } 1007 | 1008 | .markdown-body .pl-ba { 1009 | color: var(--color-prettylights-syntax-brackethighlighter-angle) 1010 | } 1011 | 1012 | .markdown-body .pl-sg { 1013 | color: var(--color-prettylights-syntax-sublimelinter-gutter-mark) 1014 | } 1015 | 1016 | .markdown-body .pl-corl { 1017 | text-decoration: underline; 1018 | color: var(--color-prettylights-syntax-constant-other-reference-link) 1019 | } 1020 | 1021 | .markdown-body g-emoji { 1022 | display: inline-block; 1023 | min-width: 1ch; 1024 | font-family: apple color emoji, segoe ui emoji, segoe ui symbol; 1025 | font-size: 1em; 1026 | font-style: normal !important; 1027 | font-weight: var(--base-text-weight-normal, 400); 1028 | line-height: 1; 1029 | vertical-align: -.075em 1030 | } 1031 | 1032 | .markdown-body g-emoji img { 1033 | width: 1em; 1034 | height: 1em 1035 | } 1036 | 1037 | .markdown-body .task-list-item { 1038 | list-style-type: none 1039 | } 1040 | 1041 | .markdown-body .task-list-item label { 1042 | font-weight: var(--base-text-weight-normal, 400) 1043 | } 1044 | 1045 | .markdown-body .task-list-item.enabled label { 1046 | cursor: pointer 1047 | } 1048 | 1049 | .markdown-body .task-list-item+.task-list-item { 1050 | margin-top: 4px 1051 | } 1052 | 1053 | .markdown-body .task-list-item .handle { 1054 | display: none 1055 | } 1056 | 1057 | .markdown-body .task-list-item-checkbox { 1058 | margin: 0 .2em .25em -1.4em; 1059 | vertical-align: middle 1060 | } 1061 | 1062 | .markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox { 1063 | margin: 0 -1.6em .25em .2em 1064 | } 1065 | 1066 | .markdown-body .contains-task-list { 1067 | position: relative 1068 | } 1069 | 1070 | .markdown-body .contains-task-list:hover .task-list-item-convert-container, 1071 | .markdown-body .contains-task-list:focus-within .task-list-item-convert-container { 1072 | display: block; 1073 | width: auto; 1074 | height: 24px; 1075 | overflow: visible; 1076 | clip: auto 1077 | } 1078 | 1079 | .markdown-body ::-webkit-calendar-picker-indicator { 1080 | filter: invert(50%) 1081 | } 1082 | -------------------------------------------------------------------------------- /addon/chrome/locale/en-US/addon.properties: -------------------------------------------------------------------------------- 1 | startup.begin=Addon is loading 2 | startup.finish=Addon is ready 3 | menuitem.label=Addon Template: Helper Examples 4 | menupopup.label=Addon Template: Menupopup 5 | menuitem.submenulabel=Addon Template 6 | menuitem.filemenulabel=Addon Template: File Menuitem 7 | prefs.title=Template 8 | prefs.table.title=Title 9 | prefs.table.detail=Detail 10 | tabpanel.lib.tab.label=Lib Tab 11 | tabpanel.reader.tab.label=Reader Tab -------------------------------------------------------------------------------- /addon/chrome/locale/en-US/overlay.dtd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /addon/chrome/locale/zh-CN/addon.properties: -------------------------------------------------------------------------------- 1 | startup.begin=插件加载中 2 | startup.finish=插件已就绪 3 | menuitem.label=插件模板: 帮助工具样例 4 | menupopup.label=插件模板: 弹出菜单 5 | menuitem.submenulabel=插件模板:子菜单 6 | menuitem.filemenulabel=插件模板: 文件菜单 7 | prefs.title=插件模板 8 | prefs.table.title=标题 9 | prefs.table.detail=详情 10 | tabpanel.lib.tab.label=库标签 11 | tabpanel.reader.tab.label=阅读器标签 -------------------------------------------------------------------------------- /addon/chrome/locale/zh-CN/overlay.dtd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /addon/install.rdf: -------------------------------------------------------------------------------- 1 | 2 | 6 | 20 | 21 | 22 | zotero@chnm.gmu.edu 23 | 5.0 24 | * 25 | 26 | 27 | 28 | 29 | juris-m@juris-m.github.io 30 | 5.0 31 | * 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /addon/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "papersgpt", 4 | "version": "0.0.8", 5 | "description": "Chat PDF in Zotero with ChatGPT, Gemini, Claude, DeepSeek, Phi-4, Llama 3.2, QwQ-32B-Preview, Gemma, Mistral", 6 | "author": "Vincent", 7 | "icons": { 8 | "48": "chrome/content/icons/favicon@0.5x.ico", 9 | "96": "chrome/content/icons/favicon.ico" 10 | }, 11 | "applications": { 12 | "zotero": { 13 | "id": "papersgpt@papersgpt.com", 14 | "update_url": "https://github.com/papersgpt/papersgpt-for-zotero/addon/updates.json", 15 | "strict_min_version": "6.999", 16 | "strict_max_version": "7.0.*" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /addon/out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/addon/out -------------------------------------------------------------------------------- /addon/prefs.js: -------------------------------------------------------------------------------- 1 | pref("extensions.zotero.__addonRef__.enable", true); 2 | pref("extensions.zotero.__addonRef__.tags", "[]"); 3 | pref("extensions.zotero.__addonRef__.languages", "[\"Arabic\", \"Bengali\", \"Bulgarian\", \"Chinese\", \"Croatian\", \"Czech\", \"Danish\", \"Dutch\", \"English\", \"Estonian\", \"Finnish\", \"French\", \"German\", \"Greek\", \"Hebrew\", \"Hindi\", \"Hungarian\", \"Italian\", \"Indonesian\", \"Japanese\", \"Korean\", \"Latvian\", \"Norwegian\", \"Polish\", \"Portuguese\", \"Romanian\", \"Russian\", \"Serbian\", \"Slovak\", \"Slovenian\", \"Spanish\", \"Swahili\", \"Swedish\", \"Thai\", \"Turkish\", \"Ukrainian\", \"Vietnamese\"]"); 4 | pref("extensions.zotero.__addonRef__.papersgptState", "Offline"); 5 | pref("extensions.zotero.__addonRef__.startLocalServer", false); 6 | pref("extensions.zotero.__addonRef__.email", ""); 7 | pref("extensions.zotero.__addonRef__.token", ""); 8 | pref("extensions.zotero.__addonRef__.isLicenseActivated", false); 9 | pref("extensions.zotero.__addonRef__.grade", ""); 10 | pref("extensions.zotero.__addonRef__.supportedLLMs", ""); 11 | pref("extensions.zotero.__addonRef__.usingLanguage", ""); 12 | pref("extensions.zotero.__addonRef__.usingPublisher", "Customized"); 13 | pref("extensions.zotero.__addonRef__.usingModel", "gpt-4o"); 14 | pref("extensions.zotero.__addonRef__.usingAPIKEY", ""); 15 | pref("extensions.zotero.__addonRef__.usingAPIURL", "https://api.openai.com/v1/chat/completions"); 16 | pref("extensions.zotero.__addonRef__.openaiApiKey", ""); 17 | pref("extensions.zotero.__addonRef__.geminiApiKey", ""); 18 | pref("extensions.zotero.__addonRef__.claudeApiKey", ""); 19 | pref("extensions.zotero.__addonRef__.customModelApiUrl", ""); 20 | pref("extensions.zotero.__addonRef__.customModelApiKey", ""); 21 | pref("extensions.zotero.__addonRef__.customModelApiModel", ""); 22 | pref("extensions.zotero.__addonRef__.secretKey", ""); 23 | pref("extensions.zotero.__addonRef__.model", "gpt-4o"); 24 | pref("extensions.zotero.__addonRef__.api", "https://api.openai.com"); 25 | pref("extensions.zotero.__addonRef__.prompts", ""); 26 | pref("extensions.zotero.__addonRef__.temperature", "1.0"); 27 | pref("extensions.zotero.__addonRef__.deltaTime", 10); 28 | pref("extensions.zotero.__addonRef__.width", "32%"); 29 | pref("extensions.zotero.__addonRef__.tagsMore", "expand"); 30 | pref("extensions.zotero.__addonRef__.chatNumber", 3); 31 | pref("extensions.zotero.__addonRef__.relatedNumber", 5); 32 | pref("extensions.zotero.__addonRef__.embeddingBatchNum", 10); 33 | -------------------------------------------------------------------------------- /addon/updates.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "papersgpt@papersgpt.com": { 4 | "updates": [ 5 | { 6 | "version": "0.0.8", 7 | "update_link": "", 8 | "applications": { 9 | "gecko": { 10 | "strict_min_version": "60.9", 11 | "strict_max_version": "60.9" 12 | } 13 | } 14 | }, 15 | { 16 | "version": "0.0.8", 17 | "update_link": "", 18 | "applications": { 19 | "zotero": { 20 | "strict_min_version": "6.999", 21 | "strict_max_version": "7.0.*" 22 | } 23 | } 24 | } 25 | ] 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /content/icons/stop-circle-fill.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /docs/teaser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c7w/papersgpt-for-zotero-sidebar/f819c3af67dbdb724f8992828400cd001c74ef6c/docs/teaser.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "papersgpt", 3 | "version": "0.0.8", 4 | "description": "Chat PDF in Zotero with ChatGPT, Gemini, Claude, DeepSeek, Phi-4, Llama 3.2, QwQ-32B-Preview, Gemma, Mistral", 5 | "config": { 6 | "addonName": "PapersGPT", 7 | "addonID": "papersgpt@papersgpt.com", 8 | "addonRef": "PapersGPT", 9 | "addonInstance": "PapersGPT", 10 | "releasepage": "", 11 | "updaterdf": "" 12 | }, 13 | "main": "src/index.ts", 14 | "scripts": { 15 | "build-dev": "cross-env NODE_ENV=development node scripts/build.js", 16 | "build-prod": "cross-env NODE_ENV=production node scripts/build.js", 17 | "tsc": "tsc --noEmit", 18 | "start-z6": "node scripts/start.js --z 6", 19 | "start-z7": "node scripts/start.js --z 7", 20 | "stop": "node scripts/stop.js", 21 | "restart-dev": "npm run build-dev && npm run stop && npm run start", 22 | "restart-prod": "npm run build-prod && npm run stop && npm run start", 23 | "restart": "npm run restart-dev", 24 | "test": "echo \"Error: no test specified\" && exit 1", 25 | "start": "node scripts/build.js && zotero-plugin serve", 26 | "build": "zotero-plugin build", 27 | "release": "zotero-plugin release" 28 | }, 29 | "repository": { 30 | "type": "git", 31 | "url": "git+https://github.com/papersgpt/papersgpt-for-zotero.git" 32 | }, 33 | "author": "Vincent", 34 | "license": "AGPL-3.0-or-later", 35 | "bugs": { 36 | "url": "https://github.com/papersgpt/papersgpt-for-zotero/issues" 37 | }, 38 | "homepage": "", 39 | "dependencies": { 40 | "@dqbd/tiktoken": "^1.0.6", 41 | "@iktakahiro/markdown-it-katex": "^4.0.1", 42 | "@pinecone-database/pinecone": "^0.0.14", 43 | "ansi-styles": "^6.2.1", 44 | "blueimp-md5": "^2.19.0", 45 | "chromadb": "^1.3.1", 46 | "compute-cosine-similarity": "^1.0.0", 47 | "crypto": "^1.0.1", 48 | "crypto-js": "^4.1.1", 49 | "dotenv": "^16.0.3", 50 | "fs": "^0.0.1-security", 51 | "gpt-3-encoder": "^1.1.4", 52 | "highlight": "^0.2.4", 53 | "highlight.js": "^11.7.0", 54 | "htmldiff-js": "^1.0.5", 55 | "langchain": "^0.0.66", 56 | "lighten-darken-color": "^1.0.0", 57 | "markdown-it": "^13.0.1", 58 | "markdown-it-katex": "^2.0.3", 59 | "markdown-it-latex": "^0.2.0", 60 | "markdown-it-math": "^4.1.1", 61 | "markdown-it-mathjax3": "^4.3.2", 62 | "node-fetch": "^3.3.2", 63 | "pdf-parse": "^1.1.1", 64 | "pdfreader": "^3.0.0", 65 | "proxy-agent": "^5.0.0", 66 | "react-markdown": "^8.0.6", 67 | "showdown": "^2.1.0", 68 | "terser": "^5.17.1", 69 | "turndown": "^7.2.0", 70 | "zotero-adv-installer": "file:..", 71 | "zotero-plugin-toolkit": "4.0.11", 72 | "esbuild": "0.25.0" 73 | }, 74 | "devDependencies": { 75 | "@types/crypto-js": "^4.1.1", 76 | "@types/markdown-it": "^12.2.3", 77 | "@types/node": "^18.11.17", 78 | "compressing": "^1.6.3", 79 | "concurrently": "^8.0.1", 80 | "cross-env": "^7.0.3", 81 | "esbuild-plugin-wasm": "^1.0.0", 82 | "minimist": "^1.2.7", 83 | "punycode": "^2.3.0", 84 | "release-it": "^17.7.0", 85 | "replace-in-file": "^6.3.5", 86 | "typescript": "^5.6.2", 87 | "uglify-js": "^3.17.4", 88 | "zotero-types": "^2.2.0" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | const esbuild = require("esbuild"); 2 | const compressing = require("compressing"); 3 | const path = require("path"); 4 | const fs = require("fs"); 5 | const process = require("process"); 6 | const replace = require("replace-in-file"); 7 | const UglifyJS = require("terser"); 8 | const { 9 | name, 10 | author, 11 | description, 12 | homepage, 13 | version, 14 | config, 15 | } = require("../package.json"); 16 | 17 | function copyFileSync(source, target) { 18 | var targetFile = target; 19 | 20 | // If target is a directory, a new file with the same name will be created 21 | if (fs.existsSync(target)) { 22 | if (fs.lstatSync(target).isDirectory()) { 23 | targetFile = path.join(target, path.basename(source)); 24 | } 25 | } 26 | 27 | fs.writeFileSync(targetFile, fs.readFileSync(source)); 28 | } 29 | 30 | function copyFolderRecursiveSync(source, target) { 31 | var files = []; 32 | 33 | // Check if folder needs to be created or integrated 34 | var targetFolder = path.join(target, path.basename(source)); 35 | if (!fs.existsSync(targetFolder)) { 36 | fs.mkdirSync(targetFolder); 37 | } 38 | 39 | // Copy 40 | if (fs.lstatSync(source).isDirectory()) { 41 | files = fs.readdirSync(source); 42 | files.forEach(function (file) { 43 | var curSource = path.join(source, file); 44 | if (fs.lstatSync(curSource).isDirectory()) { 45 | copyFolderRecursiveSync(curSource, targetFolder); 46 | } else { 47 | copyFileSync(curSource, targetFolder); 48 | } 49 | }); 50 | } 51 | } 52 | 53 | function clearFolder(target) { 54 | if (fs.existsSync(target)) { 55 | fs.rmSync(target, { recursive: true, force: true }); 56 | } 57 | 58 | fs.mkdirSync(target, { recursive: true }); 59 | } 60 | 61 | function dateFormat(fmt, date) { 62 | let ret; 63 | const opt = { 64 | "Y+": date.getFullYear().toString(), 65 | "m+": (date.getMonth() + 1).toString(), 66 | "d+": date.getDate().toString(), 67 | "H+": date.getHours().toString(), 68 | "M+": date.getMinutes().toString(), 69 | "S+": date.getSeconds().toString(), 70 | }; 71 | for (let k in opt) { 72 | ret = new RegExp("(" + k + ")").exec(fmt); 73 | if (ret) { 74 | fmt = fmt.replace( 75 | ret[1], 76 | ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0") 77 | ); 78 | } 79 | } 80 | return fmt; 81 | } 82 | 83 | async function main() { 84 | const t = new Date(); 85 | const buildTime = dateFormat("YYYY-mm-dd HH:MM:SS", t); 86 | const buildDir = "builds"; 87 | 88 | console.log( 89 | `[Build] BUILD_DIR=${buildDir}, VERSION=${version}, BUILD_TIME=${buildTime}, ENV=${[ 90 | process.env.NODE_ENV, 91 | ]}` 92 | ); 93 | 94 | clearFolder(buildDir); 95 | 96 | copyFolderRecursiveSync("addon", buildDir); 97 | 98 | copyFileSync("update-template.json", "update.json"); 99 | copyFileSync("update-template.rdf", "update.rdf"); 100 | 101 | const outfile = path.join(buildDir, "addon/chrome/content/scripts/index.js"); 102 | await esbuild 103 | .build({ 104 | entryPoints: ["src/index.ts"], 105 | define: { 106 | __env__: `"${process.env.NODE_ENV}"`, 107 | }, 108 | bundle: true, 109 | minify: false, // 不进行代码混淆 110 | minifyIdentifiers: false, // 禁用标识符混淆 111 | minifySyntax: false, // 禁用语法压缩 112 | minifyWhitespace: false, // 禁用空白压缩 113 | sourcemap: true, // 启用 Source Maps 114 | outfile, 115 | // Don't turn minify on 116 | // minify: true, 117 | target: "firefox60", 118 | }) 119 | .catch(() => process.exit(1)); 120 | 121 | //! Temporarily disable the uglify step 122 | // const indexJsContent = fs.readFileSync(outfile, "utf-8"); 123 | // const result = await UglifyJS.minify(indexJsContent, { 124 | // output: { ascii_only: true }, 125 | // }); 126 | // if (result.error) { 127 | // console.log("UglifyJS error", result.error); 128 | // process.exit(1); 129 | // } 130 | // fs.writeFileSync(outfile, result.code, "utf-8"); 131 | 132 | const replaceFrom = [ 133 | /__author__/g, 134 | /__description__/g, 135 | /__homepage__/g, 136 | /__buildVersion__/g, 137 | /__buildTime__/g, 138 | ]; 139 | 140 | const replaceTo = [author, description, homepage, version, buildTime]; 141 | 142 | replaceFrom.push( 143 | ...Object.keys(config).map((k) => new RegExp(`__${k}__`, "g")) 144 | ); 145 | replaceTo.push(...Object.values(config)); 146 | 147 | const optionsAddon = { 148 | files: [ 149 | path.join(buildDir, "**/*.rdf"), 150 | path.join(buildDir, "**/*.dtd"), 151 | path.join(buildDir, "**/*.xul"), 152 | path.join(buildDir, "**/*.xhtml"), 153 | path.join(buildDir, "**/*.json"), 154 | path.join(buildDir, "addon/prefs.js"), 155 | path.join(buildDir, "addon/chrome.manifest"), 156 | path.join(buildDir, "addon/manifest.json"), 157 | path.join(buildDir, "addon/bootstrap.js"), 158 | "update.json", 159 | "update.rdf", 160 | ], 161 | from: replaceFrom, 162 | to: replaceTo, 163 | countMatches: true, 164 | }; 165 | 166 | _ = replace.sync(optionsAddon); 167 | console.log( 168 | "[Build] Run replace in ", 169 | _.filter((f) => f.hasChanged).map( 170 | (f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}` 171 | ) 172 | ); 173 | 174 | console.log("[Build] Replace OK"); 175 | 176 | console.log("[Build] Addon prepare OK"); 177 | 178 | await compressing.zip.compressDir( 179 | path.join(buildDir, "addon"), 180 | path.join(buildDir, `${name}.xpi`), 181 | { 182 | ignoreBase: true, 183 | } 184 | ); 185 | 186 | console.log("[Build] Addon pack OK"); 187 | console.log( 188 | `[Build] Finished in ${(new Date().getTime() - t.getTime()) / 1000} s.` 189 | ); 190 | } 191 | 192 | main().catch((err) => { 193 | console.log(err); 194 | process.exit(1); 195 | }); 196 | -------------------------------------------------------------------------------- /scripts/start.js: -------------------------------------------------------------------------------- 1 | const { execSync } = require("child_process"); 2 | const { exit } = require("process"); 3 | const { exec } = require("./zotero-cmd.json"); 4 | 5 | // Run node start.js -h for help 6 | const args = require("minimist")(process.argv.slice(2)); 7 | 8 | if (args.help || args.h) { 9 | console.log("Start Zotero Args:"); 10 | console.log( 11 | "--zotero(-z): Zotero exec key in zotero-cmd.json. Default the first one." 12 | ); 13 | console.log("--profile(-p): Zotero profile name."); 14 | exit(0); 15 | } 16 | 17 | const zoteroPath = exec[args.zotero || args.z || Object.keys(exec)[0]]; 18 | const profile = args.profile || args.p; 19 | 20 | const startZotero = `${zoteroPath} -ZoteroDebugText -jsdebugger --debugger --purgecaches ${ 21 | profile ? `-p ${profile}` : "" 22 | }`; 23 | 24 | console.log("hello hello hello....") 25 | execSync(startZotero); 26 | exit(0); 27 | -------------------------------------------------------------------------------- /scripts/stop.js: -------------------------------------------------------------------------------- 1 | const { execSync } = require("child_process"); 2 | const { killZoteroWindows, killZoteroUnix } = require("./zotero-cmd.json"); 3 | 4 | try { 5 | if (process.platform === "win32") { 6 | execSync(killZoteroWindows); 7 | } else { 8 | execSync(killZoteroUnix); 9 | } 10 | } catch (e) {} 11 | -------------------------------------------------------------------------------- /scripts/zotero-cmd.json: -------------------------------------------------------------------------------- 1 | { 2 | "usage": "Copy and rename this file to zotero-cmd.json. Edit the cmd.", 3 | "killZoteroWindows": "taskkill /f /im zotero.exe", 4 | "killZoteroUnix": "kill -9 $(ps -x | grep zotero)", 5 | "exec": { 6 | "6": "/Applications/Zotero.app/Contents/MacOS/zotero", 7 | "7": "/Applications/Zotero.app/Contents/MacOS/zotero" 8 | } 9 | } -------------------------------------------------------------------------------- /src/addon.ts: -------------------------------------------------------------------------------- 1 | //import { ZoteroToolkit } from "zotero-plugin-toolkit"; 2 | import { ColumnOptions } from "zotero-plugin-toolkit/dist/helpers/virtualizedTable"; 3 | import hooks from "./hooks"; 4 | import { createZToolkit } from "./ztoolkit" 5 | 6 | class Addon { 7 | public data: { 8 | alive: boolean; 9 | // Env type, see build.js 10 | env: "development" | "production"; 11 | //ztoolkit: ZoteroToolkit; 12 | ztoolkit: MyToolkit; 13 | locale?: { 14 | stringBundle: any; 15 | }; 16 | prefs?: { 17 | window: Window; 18 | columns: Array; 19 | rows: Array<{ [dataKey: string]: string }>; 20 | }; 21 | }; 22 | // Lifecycle hooks 23 | public hooks: typeof hooks; 24 | // APIs 25 | public api: {}; 26 | 27 | constructor() { 28 | this.data = { 29 | alive: true, 30 | env: __env__, 31 | //ztoolkit: new ZoteroToolkit(), 32 | ztoolkit: createZToolkit(), 33 | }; 34 | this.hooks = hooks; 35 | this.api = {}; 36 | } 37 | } 38 | 39 | export default Addon; 40 | -------------------------------------------------------------------------------- /src/hooks.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../package.json"; 2 | import { getString, initLocale } from "./modules/locale"; 3 | import Views from "./modules/views"; 4 | import Utils from "./modules/utils"; 5 | import { createZToolkit } from "./ztoolkit" 6 | import { Prompt, default_prompt_list } from "./modules/prompts"; 7 | 8 | async function onStartup() { 9 | await Promise.all([ 10 | Zotero.initializationPromise, 11 | Zotero.unlockPromise, 12 | Zotero.uiReadyPromise, 13 | ]); 14 | initLocale(); 15 | ztoolkit.ProgressWindow.setIconURI( 16 | "default", 17 | `chrome://${config.addonRef}/content/icons/favicon.ico` 18 | ); 19 | 20 | Zotero.Prefs.set(`${config.addonRef}.supportedLLMs`, "") //! [c7w] change this... 21 | Zotero[config.addonInstance].views = new Views(); 22 | Zotero[config.addonInstance].utils = new Utils(); 23 | 24 | await Promise.all( 25 | Zotero.getMainWindows().map((win) => onMainWindowLoad(win)), 26 | ); 27 | 28 | } 29 | 30 | 31 | async function onMainWindowLoad(win: Window): Promise { 32 | // Create ztoolkit for every window 33 | addon.data.ztoolkit = createZToolkit(); 34 | 35 | 36 | //! [c7w] core view functions! 37 | // Zotero[config.addonInstance].views.registerInToolbar() 38 | 39 | Zotero[config.addonInstance].views.registerWindowAppearance() 40 | 41 | Zotero[config.addonInstance].views.registerInSidebar() 42 | 43 | Zotero[config.addonInstance].views.registerInMenupopup() 44 | 45 | 46 | //! [c7w] core view functions! 47 | 48 | //Guide.showGuideInMainWindowIfNeed(win); 49 | 50 | const callback = { 51 | notify: async ( 52 | event: string, 53 | type: string, 54 | ids: number[] | string[], 55 | extraData: { [key: string]: any }, 56 | ) => { 57 | onNotify(event, type, ids, extraData); 58 | }, 59 | }; 60 | 61 | var notifierID = Zotero.Notifier.registerObserver(callback, ["tab", "item", "file"]); 62 | } 63 | 64 | async function onMainWindowUnload(win: Window): Promise { 65 | //ztoolkit.unregisterAll(); 66 | addon.data.ztoolkit.unregisterAll(); 67 | Zotero.getMainWindow().document.querySelector("#papersgpt")?.remove(); 68 | } 69 | 70 | export function sleep(time) { 71 | return new Promise((resolve) => window.setTimeout(resolve, time)); 72 | } 73 | 74 | async function onNotify( 75 | event: string, 76 | type: string, 77 | ids: Array, 78 | extraData: { [key: string]: any }, 79 | ) { 80 | if (extraData?.skipAutoSync) return 81 | 82 | if (event === "select" && type === "tab") { 83 | await Zotero[config.addonInstance].views.registerInMenupopup() 84 | return 85 | } 86 | } 87 | 88 | 89 | export async function downloadFile(url, filename) { 90 | await Zotero.File.download(url, filename) 91 | var signFile = filename + ".done" 92 | var execCmd = [signFile]; 93 | var exec = "/usr/bin/touch" 94 | try { 95 | await Zotero.Utilities.Internal.exec(exec, execCmd); 96 | } catch { 97 | Zotero.log("touch error") 98 | } 99 | } 100 | 101 | export async function checkFileExist(filename) { 102 | return await IOUtils.exists(filename) 103 | } 104 | 105 | export async function startLocalLLMEngine(filename) { 106 | var execCmd = ['attach', filename]; 107 | var exec = "/usr/bin/hdiutil" 108 | try { 109 | await Zotero.Utilities.Internal.exec(exec, execCmd); 110 | } catch { 111 | Zotero.log("hdiutil command error!") 112 | } 113 | 114 | if (await checkFileExist("/Volumes/ChatPDFLocal/ChatPDFLocal.app")) { 115 | execCmd = ['/Volumes/ChatPDFLocal/ChatPDFLocal.app', '--args', 'appLaunchType', 'backend'] 116 | exec = "/usr/bin/open" 117 | try { 118 | await Zotero.Utilities.Internal.exec(exec, execCmd); 119 | } catch { 120 | } 121 | } 122 | } 123 | 124 | export async function shutdownLocalLLMEngine() { 125 | var execCmd = ['-9', 'ChatPDFLocal'] 126 | var exec = "/usr/bin/killall" 127 | try { 128 | await Zotero.Utilities.Internal.exec(exec, execCmd); 129 | } catch { 130 | } 131 | 132 | execCmd = ['-9', 'chatpdflocal-llama-server'] 133 | exec = "/usr/bin/killall" 134 | try { 135 | await Zotero.Utilities.Internal.exec(exec, execCmd); 136 | } catch { 137 | } 138 | 139 | execCmd = ['-9', 'chatpdflocal-llama-server-x86'] 140 | try { 141 | await Zotero.Utilities.Internal.exec(exec, execCmd); 142 | } catch { 143 | } 144 | 145 | execCmd = ['-9', 'huggingface_download'] 146 | try { 147 | await Zotero.Utilities.Internal.exec(exec, execCmd); 148 | } catch { 149 | } 150 | 151 | execCmd = ['detach', '/Volumes/ChatPDFLocal']; 152 | exec = "/usr/bin/hdiutil" 153 | try { 154 | await Zotero.Utilities.Internal.exec(exec, execCmd); 155 | } catch { 156 | } 157 | } 158 | 159 | function onShutdown(): void { 160 | if (Zotero.isMac) { 161 | Zotero.Prefs.set(`${config.addonRef}.startLocalServer`, false) 162 | 163 | shutdownLocalLLMEngine() 164 | 165 | // @ts-ignore 166 | const temp = Zotero.getTempDirectory(); 167 | var filename = "ChatPDFLocal" 168 | 169 | filename = PathUtils.join(temp.path.replace(temp.leafName, ""), `${filename}.dmg`); 170 | 171 | var execCmd = [filename]; 172 | var exec = "/bin/rm" 173 | try { 174 | Zotero.Utilities.Internal.exec(exec, execCmd); 175 | } catch { 176 | } 177 | 178 | var signFile = filename + ".done" 179 | execCmd = [signFile]; 180 | try { 181 | Zotero.Utilities.Internal.exec(exec, execCmd); 182 | } catch { 183 | } 184 | } 185 | 186 | ztoolkit.unregisterAll(); 187 | 188 | addon.data.alive = false; 189 | delete Zotero[config.addonInstance]; 190 | Zotero.Prefs.set(`${config.addonRef}.papersgptState`, "Offline") 191 | } 192 | 193 | export default { 194 | onStartup, 195 | onShutdown, 196 | onMainWindowLoad, 197 | onMainWindowUnload, 198 | }; 199 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { BasicTool } from "zotero-plugin-toolkit"; 2 | import Addon from "./addon"; 3 | import { config } from "../package.json"; 4 | 5 | const basicTool = new BasicTool(); 6 | 7 | 8 | if (!basicTool.getGlobal("Zotero")[config.addonInstance]) { 9 | // Set global variables 10 | let window: Window 11 | _globalThis.Zotero = basicTool.getGlobal("Zotero"); 12 | _globalThis.ZoteroPane = basicTool.getGlobal("ZoteroPane"); 13 | _globalThis.Zotero_Tabs = basicTool.getGlobal("Zotero_Tabs"); 14 | _globalThis.window = window = basicTool.getGlobal("window"); 15 | _globalThis.URL = basicTool.getGlobal("window").URL; 16 | _globalThis.URLSearchParams = basicTool.getGlobal("window").URLSearchParams; 17 | _globalThis.Headers = basicTool.getGlobal("window").Headers; 18 | _globalThis.AbortSignal = basicTool.getGlobal("window").AbortSignal; 19 | _globalThis.Request = basicTool.getGlobal("window").Request; 20 | _globalThis.AbortSignal.timeout = (ms: number) => { 21 | // @ts-ignore 22 | const controller = new window.AbortController(); 23 | const timer = window.setTimeout(() => controller.abort(), ms); 24 | controller.signal.addEventListener("abort", () => { 25 | window.clearTimeout(timer); 26 | }); 27 | return controller.signal; 28 | } 29 | 30 | _globalThis.document = basicTool.getGlobal("document"); 31 | _globalThis.addon = new Addon(); 32 | _globalThis.ztoolkit = addon.data.ztoolkit; 33 | ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`; 34 | ztoolkit.basicOptions.log.disableConsole = addon.data.env === "production"; 35 | ztoolkit.UI.basicOptions.ui.enableElementJSONLog = false 36 | ztoolkit.UI.basicOptions.ui.enableElementDOMLog = false 37 | ztoolkit.basicOptions.debug.disableDebugBridgePassword = 38 | addon.data.env === "development"; 39 | Zotero[config.addonInstance] = addon; 40 | // Trigger addon hook for initialization 41 | addon.hooks.onStartup(); 42 | } 43 | -------------------------------------------------------------------------------- /src/modules/Meet/BetterNotes.ts: -------------------------------------------------------------------------------- 1 | import Views from "../views"; 2 | import Meet from "./api"; 3 | 4 | /** 5 | * Prioritize returning the selected text, and then return all the previous text MD in the span 6 | * @param The line where the cursor is located, HTMLSpanElement 7 | * @returns 8 | */ 9 | export async function getEditorText(span: HTMLSpanElement) { 10 | const BNEditorApi = Zotero.BetterNotes.api.editor 11 | const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId); 12 | let lines = [...editor._iframeWindow.document.querySelector(".primary-editor").childNodes] 13 | lines = lines.slice(0, lines.indexOf(span)) 14 | const context = await Zotero.BetterNotes.api.convert.html2md(lines.map(e => e.outerHTML).join("\n")) 15 | let range = Zotero.BetterNotes.api.editor.getRangeAtCursor(editor) 16 | let selection = Zotero.BetterNotes.api.editor.getTextBetween(editor, range.from, range.to) 17 | ztoolkit.log(selection, range) 18 | if (selection.trim().length > 0) { 19 | ztoolkit.log("selection", selection) 20 | return selection 21 | } else { 22 | ztoolkit.log("context", context) 23 | return context 24 | } 25 | } 26 | 27 | export function reFocus(editor?: any) { 28 | if (!editor) { 29 | const BNEditorApi = Zotero.BetterNotes.api.editor 30 | editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId); 31 | } 32 | editor && editor._iframeWindow.focus() 33 | } 34 | 35 | 36 | 37 | export function replaceEditorText(htmlString: string) { 38 | const BNEditorApi = Zotero.BetterNotes.api.editor 39 | const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId); 40 | const range = BNEditorApi.getRangeAtCursor(editor) 41 | window.setTimeout(async () => { 42 | await Meet.Global.lock 43 | Meet.Global.lock = Zotero.Promise.defer() as _ZoteroTypes.PromiseObject 44 | BNEditorApi.del(editor, range.from, range.to) 45 | insertEditorText(htmlString) 46 | Meet.Global.lock.resolve() 47 | }) 48 | } 49 | 50 | /** 51 | * Insert text at the editor cursor 52 | * @param htmlString 53 | */ 54 | export function insertEditorText(htmlString: string, editor?: any) { 55 | const BNEditorApi = Zotero.BetterNotes.api.editor 56 | if (!editor) { 57 | editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId); 58 | } 59 | const to = BNEditorApi.getRangeAtCursor(editor).to 60 | reFocus(editor) 61 | BNEditorApi.insert( 62 | editor, 63 | htmlString, 64 | to, 65 | true 66 | ) 67 | reFocus(editor) 68 | } 69 | 70 | /** 71 | * Let UI follow this row 72 | */ 73 | export function follow() { 74 | const views = Zotero.PapersGPT.views as Views 75 | const BNEditorApi = Zotero.BetterNotes.api.editor 76 | const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId); 77 | let getLine: any = (index: number) => { 78 | return editor._iframeWindow.document.querySelector(`.primary-editor>*:nth-child(${index})`) 79 | } 80 | let place = (reBuild: boolean = false) => { 81 | const lineIndex = BNEditorApi.getLineAtCursor(editor) + 1 82 | let line = getLine(lineIndex) 83 | if (line.innerText.replace("\n", "").trim().length != 0) { 84 | line = getLine(lineIndex+1) 85 | } 86 | let { x, y } = line.getBoundingClientRect(); 87 | const leftPanel = document.querySelector("#betternotes-workspace-outline-container")! 88 | x = leftPanel.getAttribute("collapsed") ? 89 | 0 90 | : 91 | leftPanel.getBoundingClientRect().width 92 | views.show(x + 30, y + 38, reBuild) 93 | } 94 | place(true) 95 | let id = window.setInterval(async () => { 96 | place() 97 | }, 10) 98 | views._ids.push({ 99 | type: "follow", 100 | id: id 101 | }) 102 | } 103 | -------------------------------------------------------------------------------- /src/modules/Meet/Zotero.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../../package.json"; 2 | import { MD5 } from "crypto-js" 3 | import { Document } from "langchain/document"; 4 | import { similaritySearch } from "./integratellms"; 5 | import { search, isDocumentExist, addDoc } from "./papersgpt"; 6 | import Meet from "./api"; 7 | import ZoteroToolkit from "zotero-plugin-toolkit"; 8 | 9 | /** 10 | * Read clipboard 11 | * @returns string 12 | */ 13 | export function getClipboardText(): string { 14 | // @ts-ignore 15 | const clipboardService = window.Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard); 16 | // @ts-ignore 17 | const transferable = window.Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable); 18 | if (!transferable) { 19 | window.alert('Clipboard service error: Unable to create transportable instance'); 20 | } 21 | transferable.addDataFlavor('text/unicode'); 22 | clipboardService.getData(transferable, clipboardService.kGlobalClipboard); 23 | let clipboardData = {}; 24 | let clipboardLength = {}; 25 | try { 26 | transferable.getTransferData('text/unicode', clipboardData, clipboardLength); 27 | } catch (err: any) { 28 | window.console.error('Clipboard service acquisition failed:', err.message); 29 | } 30 | clipboardData = clipboardData.value.QueryInterface(Ci.nsISupportsString); 31 | return clipboardData.data 32 | } 33 | 34 | /** 35 | * Process selected items into full text 36 | * Note: The vector is not currently stored here because the entries are constantly being updated 37 | * @param key 38 | * @returns 39 | */ 40 | async function selectedItems2documents(key: string) { 41 | const docs = ZoteroPane.getSelectedItems().map((item: Zotero.Item) => { 42 | const text = JSON.stringify(item.toJSON()); 43 | return new Document({ 44 | pageContent: text.slice(0, 500), 45 | metadata: { 46 | type: "id", 47 | id: item.id, 48 | key 49 | } 50 | }) 51 | }) 52 | return docs 53 | } 54 | 55 | /** 56 | * @param items 57 | * @returns 58 | */ 59 | function mergeSameLine(items: PDFItem[]) { 60 | let toLine = (item: PDFItem) => { 61 | let line: PDFLine = { 62 | x: parseFloat(item.transform[4].toFixed(1)), 63 | y: parseFloat(item.transform[5].toFixed(1)), 64 | text: item.str || "", 65 | height: item.height, 66 | width: item.width, 67 | url: item?.url, 68 | _height: [item.height] 69 | } 70 | if (line.width < 0) { 71 | line.x += line.width 72 | line.width = -line.width 73 | } 74 | return line 75 | } 76 | 77 | let j = 0 78 | let lines: PDFLine[] = [toLine(items[j])] 79 | for (j = 1; j < items.length; j++) { 80 | let line = toLine(items[j]) 81 | let lastLine = lines.slice(-1)[0] 82 | // Consider superscript and subscript 83 | if ( 84 | line.y == lastLine.y || 85 | (line.y >= lastLine.y && line.y < lastLine.y + lastLine.height) || 86 | (line.y + line.height > lastLine.y && line.y + line.height <= lastLine.y + lastLine.height) 87 | ) { 88 | lastLine.text += (" " + line.text) 89 | lastLine.width += line.width 90 | lastLine.url = lastLine.url || line.url 91 | // Record all altitudes 92 | lastLine._height.push(line.height) 93 | } else { 94 | let hh = lastLine._height 95 | const num: any = {} 96 | for (let i = 0; i < hh.length; i++) { 97 | num[String(hh[i])] ??= 0 98 | num[String(hh[i])] += 1 99 | } 100 | lastLine.height = Number( 101 | Object.keys(num).sort((h1: string, h2: string) => { 102 | return num[h2] - num[h1] 103 | })[0] 104 | ) 105 | lines.push(line) 106 | } 107 | } 108 | return lines 109 | } 110 | 111 | declare type Box = { 112 | left: number; 113 | right: number; 114 | top: number; 115 | bottom: number; 116 | } 117 | 118 | /** 119 | * Determine whether two rectangles A and B intersect geometrically 120 | * @param A 121 | * @param B 122 | * @returns 123 | */ 124 | function isIntersect(A: Box, B: Box): boolean { 125 | if ( 126 | B.right < A.left || 127 | B.left > A.right || 128 | B.bottom > A.top || 129 | B.top < A.bottom 130 | ) { 131 | return false 132 | } else { 133 | return true 134 | } 135 | } 136 | 137 | /** 138 | * Determine whether two rows are cross-page rows at the same position置行 139 | * @param lineA 140 | * @param lineB 141 | * @param maxWidth 142 | * @param maxHeight 143 | * @returns 144 | */ 145 | function isIntersectLines(lineA: any, lineB: any, maxWidth: number, maxHeight: number) { 146 | let rectA = { 147 | left: lineA.x / maxWidth, 148 | right: (lineA.x + lineA.width) / maxWidth, 149 | bottom: lineA.y / maxHeight, 150 | top: (lineA.y + lineA.height) / maxHeight 151 | } 152 | let rectB = { 153 | left: lineB.x / maxWidth, 154 | right: (lineB.x + lineB.width) / maxWidth, 155 | bottom: lineB.y / maxHeight, 156 | top: (lineB.y + lineB.height) / maxHeight 157 | } 158 | return isIntersect(rectA, rectB) 159 | } 160 | 161 | /** 162 | * Read the full text of the PDF. Because the reading speed is generally faster, it is not stored. 163 | * Of course, dissertations, books, etc. are excluded 164 | * This function will stop reading when it encounters the reference keyword, because the reference too affects the final calculation of similarity. 165 | */ 166 | async function pdf2documents(itemkey: string) { 167 | const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance 168 | const PDFViewerApplication = (reader._iframeWindow as any).wrappedJSObject.PDFViewerApplication; 169 | await PDFViewerApplication.pdfLoadingTask.promise; 170 | await PDFViewerApplication.pdfViewer.pagesPromise; 171 | let pages = PDFViewerApplication.pdfViewer._pages; 172 | let totalPageNum = pages.length 173 | const popupWin = new ztoolkit.ProgressWindow("[Pending] PDF", { closeTime: -1 }) 174 | .createLine({ text: `[1/${totalPageNum}] Reading`, progress: 1, type: "success" }) 175 | .show() 176 | // const popupWin = Meet.Global.popupWin.createLine({ text: `[1/${totalPageNum}] Reading PDF`, progress: 1, type: "success" }) 177 | // .show() 178 | // Read all lines of the page 179 | const pageLines: any = {} 180 | let docs: Document[] = [] 181 | for (let pageNum = 0; pageNum < totalPageNum; pageNum++) { 182 | let pdfPage = pages[pageNum].pdfPage 183 | let textContent = await pdfPage.getTextContent() 184 | let items: PDFItem[] = textContent.items.filter((item: PDFItem) => item.str.trim().length) 185 | let lines = mergeSameLine(items) 186 | let index = lines.findIndex(line => /(r?eferences?|acknowledgements)$/i.test(line.text.trim())) 187 | if (index != -1) { 188 | lines = lines.slice(0, index) 189 | } 190 | pageLines[pageNum] = lines 191 | popupWin.changeLine({ idx: popupWin.lines.length - 1, text: `[${pageNum + 1}/${totalPageNum}] Reading PDF`, progress: (pageNum + 1) / totalPageNum * 100}) 192 | if (index != -1 && pageNum / totalPageNum >= .9) { 193 | break 194 | } 195 | } 196 | 197 | popupWin.changeLine({ idx: popupWin.lines.length - 1, text: "Reading PDF", progress: 100 }) 198 | popupWin.changeLine({ progress: 100 }); 199 | totalPageNum = Object.keys(pageLines).length 200 | 201 | for (let pageNum1 = 0; pageNum1 < totalPageNum; pageNum1++) { 202 | let pdfPage = pages[pageNum1].pdfPage 203 | const maxWidth = pdfPage._pageInfo.view[2]; 204 | const maxHeight = pdfPage._pageInfo.view[3]; 205 | let lines = [...pageLines[pageNum1]] 206 | // Todo: Remove header and footer information, duplicate 207 | 208 | 209 | // paragraph clustering 210 | // principle: Font size from large to small, merge; From small to big 211 | let abs = (x: number) => x > 0 ? x : -x 212 | const paragraphs = [[lines[0]]] 213 | for (let i = 1; i < lines.length; i++) { 214 | let lastLine = paragraphs.slice(-1)[0].slice(-1)[0] 215 | let currentLine = lines[i] 216 | let nextLine = lines[i + 1] 217 | const isNewParagraph = 218 | // Reach a certain row count threshold 219 | paragraphs.slice(-1)[0].length >= 5 && 220 | ( 221 | // There is text in a very large font on the current line 222 | currentLine._height.some((h2: number) => lastLine._height.every((h1: number) => h2 > h1)) || 223 | // The abstract is automatically one paragraph 224 | /abstract/i.test(currentLine.text) || 225 | // The distance from the previous line is too large 226 | abs(lastLine.y - currentLine.y) > currentLine.height * 2 || 227 | // First line indented paragraph 228 | (currentLine.x > lastLine.x && nextLine && nextLine.x < currentLine.x) 229 | ) 230 | // Open new paragraph 231 | if (isNewParagraph) { 232 | paragraphs.push([currentLine]) 233 | } 234 | // Otherwise, include it in the current paragraph 235 | else { 236 | paragraphs.slice(-1)[0].push(currentLine) 237 | } 238 | } 239 | ztoolkit.log(paragraphs) 240 | // Paragraph merge 241 | for (let i = 0; i < paragraphs.length; i++) { 242 | let box: { page: number, left: number; top: number; right: number; bottom: number } 243 | /** 244 | * All lines belong to a paragraph 245 | * Merge while calculating its bounds 246 | */ 247 | let _pageText = "" 248 | let line, nextLine 249 | for (let j = 0; j < paragraphs[i].length; j++) { 250 | line = paragraphs[i][j] 251 | if (!line) { continue } 252 | nextLine = paragraphs[i]?.[j + 1] 253 | // Update boundaries 254 | box ??= { page: pageNum1, left: line.x, right: line.x + line.width, top: line.y + line.height, bottom: line.y } 255 | if (line.x < box.left) { 256 | box.left = line.x 257 | } 258 | if (line.x + line.width > box.right) { 259 | box.right = line.x + line.width 260 | } 261 | if (line.y < box.bottom) { 262 | line.y = box.bottom 263 | } 264 | if (line.y + line.height > box.top) { 265 | box.top = line.y + line.height 266 | } 267 | _pageText += line.text 268 | if ( 269 | nextLine && 270 | line.height > nextLine.height 271 | ) { 272 | _pageText = "\n" 273 | } else if (j < paragraphs[i].length - 1) { 274 | if (!line.text.endsWith("-")) { 275 | _pageText += " " 276 | } 277 | } 278 | } 279 | _pageText = _pageText.replace(/\x20+/g, " ").replace(/^\x20*\n+/g, "").replace(/\x20*\n+/g, ""); 280 | if (_pageText.length > 0) { 281 | docs.push( 282 | new Document({ 283 | pageContent: _pageText, 284 | metadata: { type: "box", box: box!, key: itemkey }, 285 | }) 286 | ) 287 | } 288 | } 289 | } 290 | // popupWin.changeHeadline("[Done] PDF") 291 | // popupWin.startCloseTimer(1000) 292 | return docs 293 | } 294 | 295 | export async function pdf2txt() { 296 | const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance 297 | const PDFViewerApplication = (reader._iframeWindow as any).wrappedJSObject.PDFViewerApplication; 298 | await PDFViewerApplication.pdfLoadingTask.promise; 299 | await PDFViewerApplication.pdfViewer.pagesPromise; 300 | let pages = PDFViewerApplication.pdfViewer._pages; 301 | let totalPageNum = pages.length 302 | const popupWin = new ztoolkit.ProgressWindow("[Pending] PDF", { closeTime: -1 }) 303 | .createLine({ text: `[1/${totalPageNum}] Reading`, progress: 1, type: "success" }) 304 | // .show() 305 | // const popupWin = Meet.Global.popupWin.createLine({ text: `[1/${totalPageNum}] Reading PDF`, progress: 1, type: "success" }) 306 | // .show() 307 | // Read all lines of the page 308 | const pageLines: any = {} 309 | let docs: string[] = [] 310 | for (let pageNum = 0; pageNum < totalPageNum; pageNum++) { 311 | let pdfPage = pages[pageNum].pdfPage 312 | let textContent = await pdfPage.getTextContent() 313 | let items: PDFItem[] = textContent.items.filter((item: PDFItem) => item.str.trim().length) 314 | let lines = mergeSameLine(items) 315 | let index = lines.findIndex(line => /(r?eferences?|acknowledgements)$/i.test(line.text.trim())) 316 | if (index != -1) { 317 | lines = lines.slice(0, index) 318 | } 319 | pageLines[pageNum] = lines 320 | popupWin.changeLine({ idx: popupWin.lines.length - 1, text: `[${pageNum + 1}/${totalPageNum}] Reading PDF`, progress: (pageNum + 1) / totalPageNum * 100}) 321 | if (index != -1 && pageNum / totalPageNum >= .9) { 322 | break 323 | } 324 | } 325 | 326 | popupWin.changeLine({ idx: popupWin.lines.length - 1, text: "Reading PDF", progress: 100 }) 327 | popupWin.changeLine({ progress: 100 }); 328 | totalPageNum = Object.keys(pageLines).length 329 | 330 | for (let pageNum1 = 0; pageNum1 < totalPageNum; pageNum1++) { 331 | let pdfPage = pages[pageNum1].pdfPage 332 | const maxWidth = pdfPage._pageInfo.view[2]; 333 | const maxHeight = pdfPage._pageInfo.view[3]; 334 | let lines = [...pageLines[pageNum1]] 335 | // Todo: Remove header and footer information, duplicate 336 | 337 | 338 | // paragraph clustering 339 | // principle: Font size from large to small, merge; From small to big 340 | let abs = (x: number) => x > 0 ? x : -x 341 | const paragraphs = [[lines[0]]] 342 | for (let i = 1; i < lines.length; i++) { 343 | let lastLine = paragraphs.slice(-1)[0].slice(-1)[0] 344 | let currentLine = lines[i] 345 | let nextLine = lines[i + 1] 346 | const isNewParagraph = 347 | // Reach a certain row count threshold 348 | paragraphs.slice(-1)[0].length >= 5 && 349 | ( 350 | // There is text in a very large font on the current line 351 | currentLine._height.some((h2: number) => lastLine._height.every((h1: number) => h2 > h1)) || 352 | // The abstract is automatically one paragraph 353 | /abstract/i.test(currentLine.text) || 354 | // The distance from the previous line is too large 355 | abs(lastLine.y - currentLine.y) > currentLine.height * 2 || 356 | // First line indented paragraph 357 | (currentLine.x > lastLine.x && nextLine && nextLine.x < currentLine.x) 358 | ) 359 | // Open new paragraph 360 | if (isNewParagraph) { 361 | paragraphs.push([currentLine]) 362 | } 363 | // Otherwise, include it in the current paragraph 364 | else { 365 | paragraphs.slice(-1)[0].push(currentLine) 366 | } 367 | } 368 | ztoolkit.log(paragraphs) 369 | // Paragraph merge 370 | for (let i = 0; i < paragraphs.length; i++) { 371 | let box: { page: number, left: number; top: number; right: number; bottom: number } 372 | /** 373 | * All lines belong to a paragraph 374 | * Merge while calculating its bounds 375 | */ 376 | let _pageText = "" 377 | let line, nextLine 378 | for (let j = 0; j < paragraphs[i].length; j++) { 379 | line = paragraphs[i][j] 380 | if (!line) { continue } 381 | nextLine = paragraphs[i]?.[j + 1] 382 | // Update boundaries 383 | box ??= { page: pageNum1, left: line.x, right: line.x + line.width, top: line.y + line.height, bottom: line.y } 384 | if (line.x < box.left) { 385 | box.left = line.x 386 | } 387 | if (line.x + line.width > box.right) { 388 | box.right = line.x + line.width 389 | } 390 | if (line.y < box.bottom) { 391 | line.y = box.bottom 392 | } 393 | if (line.y + line.height > box.top) { 394 | box.top = line.y + line.height 395 | } 396 | _pageText += line.text 397 | if ( 398 | nextLine && 399 | line.height > nextLine.height 400 | ) { 401 | _pageText = "\n" 402 | } else if (j < paragraphs[i].length - 1) { 403 | if (!line.text.endsWith("-")) { 404 | _pageText += " " 405 | } 406 | } 407 | } 408 | _pageText = _pageText.replace(/\x20+/g, " ").replace(/^\x20*\n+/g, "").replace(/\x20*\n+/g, ""); 409 | if (_pageText.length > 0) { 410 | docs.push( 411 | _pageText 412 | ) 413 | } 414 | } 415 | } 416 | popupWin.changeHeadline("[Done] PDF") 417 | popupWin.startCloseTimer(300) 418 | // concat the docs and return 419 | return docs.join("\n\n") 420 | } 421 | 422 | /** 423 | * If you are currently in the main panel, generate text based on the selected item and find related - used to search for items 424 | * If you are in the PDF reading UI, read the original PDF text, search and return the corresponding paragraph - used to summarize the problem 425 | * @param queryText 426 | * @returns 427 | */ 428 | export async function getRelatedText(queryText: string) { 429 | const usingPublisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 430 | if (usingPublisher != "Local LLM") { 431 | // @ts-ignore 432 | const cache = (window._GPTGlobal ??= {cache: []}).cache 433 | let docs: Document[], key: string 434 | switch (Zotero_Tabs.selectedIndex) { 435 | case 0: 436 | // Only when the same entry is selected again and the entry has not been updated will it be reused, otherwise the index will be created repeatedly 437 | key = MD5(ZoteroPane.getSelectedItems().map(i => i.key).join("")).toString() 438 | docs = cache[key] || await selectedItems2documents(key) 439 | break; 440 | default: 441 | let pdfItem = Zotero.Items.get( 442 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number 443 | ) 444 | key = pdfItem.key 445 | docs = cache[key] || await pdf2documents(key) 446 | break 447 | } 448 | cache[key] = docs 449 | docs = await similaritySearch(queryText, docs, { key }) as Document[] 450 | Zotero[config.addonInstance].views.insertAuxiliary(docs) 451 | return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join("\n\n") 452 | } else { 453 | var docs: Document[], key: string 454 | let topn = 4 455 | var packFields: string 456 | switch (Zotero_Tabs.selectedIndex) { 457 | case 0: 458 | // Only when the same entry is selected again and the entry has not been updated will it be reused, otherwise the index will be created repeatedly 459 | key = MD5(ZoteroPane.getSelectedItems().map(i => i.key).join("")).toString() 460 | if (!isDocumentExist(key)) { 461 | docs = await selectedItems2documents(key) 462 | await addDoc(key, docs, "id") 463 | } 464 | 465 | packFields = "text-string:type-string:id-int" 466 | 467 | break; 468 | default: 469 | let pdfItem = Zotero.Items.get( 470 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number 471 | ) 472 | key = pdfItem.key 473 | let isKeyProcessed = await isDocumentExist(key) 474 | if (!isKeyProcessed) { 475 | docs = await pdf2documents(key) 476 | await addDoc(key, docs, "box") 477 | } 478 | packFields = "text-string:type-string:box_page-int:box_left-float:box_right-float:box_bottom-float:box_top-float" 479 | 480 | break 481 | } 482 | const usingModel = Zotero.Prefs.get(`${config.addonRef}.usingModel`) 483 | var results = await search("Local LLM", usingModel, key, queryText, topn, "", packFields) 484 | 485 | 486 | Zotero[config.addonInstance].views.insertAuxiliary(results) 487 | return results.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join("\n\n") 488 | } 489 | 490 | } 491 | 492 | export function getTranslatingLanguage() { 493 | return Zotero.Prefs.get(`${config.addonRef}.usingLanguage`) as string 494 | } 495 | 496 | /** 497 | * Get a field of the selected item 498 | * @param fieldName 499 | * @returns 500 | */ 501 | export function getItemField(fieldName: any) { 502 | return ZoteroPane.getSelectedItems()[0].getField(fieldName) 503 | } 504 | 505 | /** 506 | * Get PDF page text 507 | * @returns 508 | */ 509 | export function getPDFSelection() { 510 | try { 511 | return ztoolkit.Reader.getSelectedText( 512 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID) 513 | ); 514 | } catch { 515 | return "" 516 | } 517 | } 518 | 519 | export async function getPDFAnnotations(select: boolean = false) { 520 | let keys: string[] 521 | if (select) { 522 | // try { 523 | const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance 524 | const nodes = reader._iframeWindow?.document.querySelectorAll("[id^=annotation-].selected") as any 525 | ztoolkit.log(nodes) 526 | keys = [...nodes].map(i => i.id.split("-")[1]) 527 | ztoolkit.log(keys) 528 | // } catch {} 529 | } 530 | const pdfItem = Zotero.Items.get( 531 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number 532 | ) 533 | const docs: Document[] = [] 534 | pdfItem.getAnnotations().forEach((anno: any) => { 535 | if (select && keys.indexOf(anno.key) == -1) { return } 536 | const pos = JSON.parse(anno.annotationPosition) 537 | const rect = pos.rects[0] 538 | docs.push( 539 | new Document({ 540 | pageContent: anno.annotationText, 541 | metadata: { 542 | type: "box", 543 | box: { page: pos.pageIndex, left: rect[0], right: rect[2], top: rect[3], bottom: rect[1] }, 544 | key: pdfItem.key 545 | } 546 | }) 547 | ) 548 | }) 549 | Zotero[config.addonInstance].views.insertAuxiliary(docs) 550 | return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join("\n\n") 551 | } 552 | -------------------------------------------------------------------------------- /src/modules/Meet/api.ts: -------------------------------------------------------------------------------- 1 | import { 2 | getClipboardText, 3 | getItemField, 4 | getPDFSelection, 5 | getRelatedText, 6 | getPDFAnnotations, 7 | getTranslatingLanguage 8 | } from "./Zotero" 9 | 10 | import { 11 | getEditorText, 12 | insertEditorText, 13 | replaceEditorText, 14 | follow, 15 | reFocus 16 | } from "./BetterNotes" 17 | 18 | import { 19 | getGPTResponse 20 | } from "./integratellms" 21 | import Views from "../views"; 22 | 23 | const Meet: { 24 | [key: string]: any; 25 | Global: { 26 | [key: string]: any; 27 | views: Views | undefined 28 | } 29 | } = { 30 | /** 31 | * Open to users 32 | * Example: Meet.Zotero.xxx() 33 | */ 34 | Zotero: { 35 | /** 36 | * Returns the contents copied from the system clipboard 37 | */ 38 | getClipboardText, 39 | /** 40 | * Returns a field value of the selected entry. Multiple selections return a field value of the first selected item 41 | * @fieldName The received field name 42 | * Such as abstract, Meet.Zotero.getItemField("abstractNote") 43 | */ 44 | getItemField, 45 | 46 | getTranslatingLanguage, 47 | /** 48 | * Returns the text selected when reading PDF 49 | */ 50 | getPDFSelection, 51 | /** 52 | * Return relevant paragraphs. If you select multiple items, return the 5 items most relevant to the question 53 | * If you are in PDF it will read the entire PDF and return the 5 paragraphs most relevant to the question 54 | * @queryText Receive a query string 55 | * Meet.Zotero.getItemField("What does the XXX mentioned in this article mean?") 56 | */ 57 | getRelatedText, 58 | /** 59 | * Get PDF annotation content 60 | * @select Receives a boolean, whether to return the selected label 61 | * getPDFAnnotations(true) Return selected annotation 62 | * getPDFAnnotations() Returns all annotations by default 63 | */ 64 | getPDFAnnotations, 65 | }, 66 | /** 67 | * Partially open 68 | * The following functions are only for main notes 69 | */ 70 | BetterNotes: { 71 | getEditorText, 72 | insertEditorText, 73 | replaceEditorText, 74 | follow, 75 | reFocus 76 | }, 77 | integratellms: { 78 | getGPTResponse 79 | }, 80 | Global: { 81 | lock: undefined, 82 | input: undefined, 83 | views: undefined, 84 | popupWin: undefined, 85 | storage: undefined 86 | } 87 | } 88 | 89 | export default Meet 90 | -------------------------------------------------------------------------------- /src/modules/Meet/integratellms.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../../package.json"; 2 | import { MD5 } from "crypto-js" 3 | import { Document } from "langchain/document"; 4 | import LocalStorage from "../localStorage"; 5 | import Views from "../views"; 6 | import Meet from "./api"; 7 | const similarity = require('compute-cosine-similarity'); 8 | 9 | /** 10 | * Given text and documents, return a list of documents, returning the most similar ones 11 | * @param queryText 12 | * @param docs 13 | * @param obj 14 | * @returns 15 | */ 16 | export async function similaritySearch(queryText: string, docs: Document[], obj: { key: string }) { 17 | const storage = Meet.Global.storage = Meet.Global.storage || new LocalStorage(config.addonRef) 18 | await storage.lock.promise; 19 | const embeddings = new Embeddings() as any 20 | // Search local, to save space, only store vectors 21 | // The MD5 value is extracted here as verification. 22 | // Here local JSON files may become larger and larger 23 | var embeddingSource = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 24 | if (embeddingSource == "Claude-3") { 25 | const views = Zotero.PapersGPT.views as Views 26 | const openaiApiKey = views.publisher2models.get("OpenAI").apiKey 27 | const geminiApiKey = views.publisher2models.get("Gemini").apiKey 28 | if (openaiApiKey != null && openaiApiKey.length > 0) { 29 | embeddingSource = "OpenAI" 30 | } else if (geminiApiKey != null && geminiApiKey.length > 0) { 31 | embeddingSource = "Gemini" 32 | } else if (Zotero.isMac) { 33 | embeddingSource = "Localhost" 34 | } 35 | } 36 | const id = embeddingSource + ":" + MD5(docs.map((i: any) => i.pageContent).join("\n\n")).toString() 37 | await storage.lock 38 | const _vv = storage.get(obj, id) 39 | ztoolkit.log(_vv) 40 | let vv: any 41 | if (_vv) { 42 | Meet.Global.popupWin.createLine({ text: "Reading embeddings...", type: "default" }) 43 | vv = _vv 44 | } else { 45 | Meet.Global.popupWin.createLine({ text: "Generating embeddings...", type: "default" }) 46 | vv = await embeddings.embedDocuments(docs.map((i: any) => i.pageContent)) 47 | window.setTimeout(async () => { 48 | await storage.set(obj, id, vv) 49 | }) 50 | } 51 | 52 | const v0 = await embeddings.embedQuery(queryText) 53 | // Find the longest text among the 20 to prevent short but highly similar paragraphs from affecting the accuracy of the answer 54 | const relatedNumber = Zotero.Prefs.get(`${config.addonRef}.relatedNumber`) as number 55 | Meet.Global.popupWin.createLine({ text: `Searching ${relatedNumber} related content...`, type: "default" }) 56 | const k = relatedNumber * 5 57 | const pp = vv.map((v: any) => similarity(v0, v)); 58 | docs = [...pp].sort((a, b) => b - a).slice(0, k).map((p: number) => { 59 | return docs[pp.indexOf(p)] 60 | }) 61 | return docs.sort((a, b) => b.pageContent.length - a.pageContent.length).slice(0, relatedNumber) 62 | } 63 | 64 | 65 | class Embeddings { 66 | private openaiAPIURL: string = "https://api.openai.com/v1/embeddings" 67 | private geminiAPIURL: string = "https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:batchEmbedContents?key=" 68 | private embeddingAPIURL: string = "" 69 | constructor() { 70 | } 71 | private async request(input: string[]) { 72 | const views = Zotero.PapersGPT.views as Views 73 | let api = Zotero.Prefs.get(`${config.addonRef}.usingAPIURL`) as string 74 | var apiKey = Zotero.Prefs.get(`${config.addonRef}.usingAPIKEY`) 75 | const split_len: number = Zotero.Prefs.get(`${config.addonRef}.embeddingBatchNum`) as number 76 | const curPublisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 77 | if (curPublisher == "OpenAI") { 78 | this.embeddingAPIURL = this.openaiAPIURL 79 | } else if (curPublisher == "Gemini") { 80 | this.embeddingAPIURL = this.geminiAPIURL 81 | this.embeddingAPIURL += apiKey 82 | } else if (curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") { 83 | const openaiApiKey = views.publisher2models.get("OpenAI").apiKey 84 | const geminiApiKey = views.publisher2models.get("Gemini").apiKey 85 | if (openaiApiKey.length > 0) { 86 | this.embeddingAPIURL = this.openaiAPIURL 87 | apiKey = openaiApiKey 88 | } else if (geminiApiKey.length > 0) { 89 | this.embeddingAPIURL = this.geminiAPIURL 90 | this.embeddingAPIURL += geminiApiKey 91 | apiKey = geminiApiKey 92 | } else if (Zotero.isMac) { 93 | this.embeddingAPIURL = "http://localhost:9080/getTextEmbeddings" 94 | } 95 | } 96 | 97 | let res 98 | 99 | if (!apiKey && (curPublisher != "Claude-3" && curPublisher != "DeepSeek")) { 100 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 101 | .createLine({ text: "Your apiKey is not configured.", type: "default" }) 102 | .show() 103 | return 104 | } else if ((curPublisher == "Claude-3" || curPublisher == "DeepSeek") && this.embeddingAPIURL.length == 0) { 105 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 106 | .createLine({ text: "Embedding api is not configured.", type: "default" }) 107 | .show() 108 | return 109 | } 110 | 111 | 112 | var final_embeddings: number[] = [] 113 | for (let i = 0; i < input.length; i += split_len) { 114 | 115 |       const chunk = input.slice(i, i + split_len) 116 | 117 | try { 118 | if (curPublisher == "OpenAI" || ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("openai"))) { 119 | res = await Zotero.HTTP.request( 120 | "POST", 121 | this.embeddingAPIURL, 122 | { 123 | responseType: "json", 124 | headers: { 125 | "Content-Type": "application/json", 126 | "Authorization": `Bearer ${apiKey}`, 127 | }, 128 | body: JSON.stringify({ 129 | model: "text-embedding-ada-002", 130 | input: chunk 131 | }), 132 | } 133 | ) 134 | } else if (curPublisher == "Gemini" || ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("googleapis"))) { 135 | var batchRequests = [] 136 | for (let j = 0; j < split_len; j++) { 137 | if (i + j >= input.length) break 138 | batchRequests.push({ 139 | model: "models/text-embedding-004", 140 | content: { 141 | parts: [{ 142 | text: input[i + j] 143 | }] 144 | } 145 | }) 146 | } 147 | res = await Zotero.HTTP.request( 148 | "POST", 149 | this.embeddingAPIURL, 150 | { 151 | responseType: "json", 152 | headers: { 153 | "Content-Type": "application/json", 154 | }, 155 | body: JSON.stringify({ 156 | requests: batchRequests 157 | }), 158 | } 159 | ) 160 | } else if ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("localhost")) { 161 | res = await Zotero.HTTP.request( 162 | "POST", 163 | this.embeddingAPIURL, 164 | { 165 | responseType: "json", 166 | headers: { 167 | "Content-Type": "application/json", 168 | }, 169 | body: JSON.stringify({ 170 | texts: chunk 171 | }), 172 | } 173 | ) 174 | } 175 | } catch (error: any) { 176 | try { 177 | error = error.xmlhttp.response?.error 178 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 179 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 180 | .createLine({ text: error.message, type: "default" }) 181 | .show() 182 | } catch { 183 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 184 | .createLine({ text: error.message, type: "default" }) 185 | .show() 186 | } 187 | } 188 | 189 | if ((curPublisher == "OpenAI" || ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("openai"))) && res?.response?.data) { 190 | final_embeddings = final_embeddings.concat(res.response.data.map((i: any) => i.embedding)) 191 | } else if ((curPublisher == "Gemini" || ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("googleapis"))) && res?.response?.embeddings) { 192 | final_embeddings = final_embeddings.concat(res.response.embeddings.map((i: any) => i.values)) 193 | } else if ((curPublisher == "Claude-3" || curPublisher == "DeepSeek" || curPublisher == "Customized") && this.embeddingAPIURL.includes("localhost")) { 194 | final_embeddings = final_embeddings.concat(res.response.Embeddings.map((i: any) => i.values)) 195 | } 196 |     } 197 | return final_embeddings 198 | } 199 | 200 | public async embedDocuments(texts: string[]) { 201 | return await this.request(texts) 202 | } 203 | 204 | public async embedQuery(text: string) { 205 | return (await this.request([text]))?.[0] 206 | } 207 | } 208 | 209 | 210 | export async function getGPTResponse(requestText: string) { 211 | const usingPublisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 212 | 213 | if (usingPublisher == "Local LLM") { 214 | return await getResponseByLocalLLM(requestText) 215 | } 216 | 217 | return await getResponseByOnlineModel(requestText) 218 | } 219 | 220 | export async function getResponseByOnlineModel(requestText: string) { 221 | const views = Zotero.PapersGPT.views as Views 222 | const apiKey = Zotero.Prefs.get(`${config.addonRef}.usingAPIKEY`) 223 | const temperature = 0.7 224 | let apiURL = Zotero.Prefs.get(`${config.addonRef}.usingAPIURL`) as string 225 | const model = Zotero.Prefs.get(`${config.addonRef}.usingModel`) 226 | 227 | Zotero.log(`apiURL: ${apiURL}`) 228 | Zotero.log(`model: ${model}`) 229 | Zotero.log(`apiKey: ${apiKey}`) 230 | 231 | views.messages.push({ 232 | role: "user", 233 | content: requestText 234 | }) 235 | const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number 236 | // Store the last results 237 | let _textArr: string[] = [] 238 | // Changes in real time as requests return 239 | let textArr: string[] = [] 240 | // Activate output 241 | views.stopAlloutput() 242 | views.setText("") 243 | let responseText: string | undefined 244 | const id: number = window.setInterval(async () => { 245 | if (!responseText && _textArr.length == textArr.length) { return} 246 | _textArr = textArr.slice(0, _textArr.length + 1) 247 | let text = _textArr.join("") 248 | text.length > 0 && views.setText(text) 249 | if (responseText && responseText == text) { 250 | views.setText(text, true) 251 | window.clearInterval(id) 252 | } 253 | }, deltaTime) 254 | views._ids.push({ 255 | type: "output", 256 | id: id 257 | }) 258 | const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number 259 | 260 | const curPublisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 261 | 262 | if (curPublisher == "OpenAI" || curPublisher == "DeepSeek" || curPublisher == "Customized") { 263 | try { 264 | var deployedModel = model 265 | if (model.includes(":")) { 266 | let index = model.indexOf(":") 267 | deployedModel = model.substr(index + 1, model.length) 268 | } 269 | 270 | await Zotero.HTTP.request( 271 | "POST", 272 | apiURL, 273 | { 274 | headers: { 275 | "Content-Type": "application/json", 276 | "Authorization": `Bearer ${apiKey}`, 277 | }, 278 | body: JSON.stringify({ 279 | model: deployedModel, 280 | messages: views.messages.slice(-chatNumber), 281 | stream: true, 282 | temperature: Number(temperature), 283 | max_tokens: 4096 284 | }), 285 | responseType: "text", 286 | requestObserver: (xmlhttp: XMLHttpRequest) => { 287 | xmlhttp.onprogress = (e: any) => { 288 | try { 289 | textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content") >= 0).map((s: string) => { 290 | try { 291 | return JSON.parse(s.replace("data: ", "")).choices[0].delta.content.replace(/\n+/g, "\n") 292 | } catch { 293 | return false 294 | } 295 | }).filter(Boolean) 296 | } catch { 297 | // Changes in real time as requests return 298 | ztoolkit.log(e.target.response) 299 | } 300 | if (e.target.timeout) { 301 | e.target.timeout = 0; 302 | } 303 | }; 304 | }, 305 | } 306 | ); 307 | } catch (error: any) { 308 | try { 309 | error = JSON.parse(error?.xmlhttp?.response).error 310 | textArr = [`# ${error.code}\n> ${apiURL}\n\n**${error.type}**\n${error.message}`] 311 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 312 | .createLine({ text: error.message, type: "default" }) 313 | .show() 314 | } catch { 315 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 316 | .createLine({ text: error.message, type: "default" }) 317 | .show() 318 | } 319 | } 320 | } else if (curPublisher == "Gemini") { 321 | 322 | var deployedModel = model 323 | if (model.includes(":")) { 324 | let index = model.indexOf(":") 325 | deployedModel = model.substr(index + 1, model.length) 326 | } 327 | 328 | const index = apiURL.lastIndexOf("/") 329 | apiURL = apiURL.substr(0, index) 330 | apiURL = apiURL + "/" + deployedModel + ":streamGenerateContent?alt=sse&key=" + apiKey 331 | var text = "" 332 | if (views.messages.slice(-1)[0].role == "user") { 333 | text = views.messages.slice(-1)[0].content 334 | } else if (views.messages.slice(-2, -1)[0].role == "user") { 335 | text = views.messages.slice(-2, -1)[0].content 336 | } 337 | var requestParameters = [{ 338 | parts: [{ 339 | text: text 340 | }] 341 | }] 342 | 343 | try { 344 | await Zotero.HTTP.request( 345 | "POST", 346 | apiURL, 347 | { 348 | headers: { 349 | "Content-Type": "application/json", 350 | }, 351 | body: JSON.stringify({ 352 | contents: requestParameters, 353 | }), 354 | responseType: "text", 355 | requestObserver: (xmlhttp: XMLHttpRequest) => { 356 | xmlhttp.onprogress = (e: any) => { 357 | try { 358 | textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content") >= 0).map((s: string) => { 359 | try { 360 | return JSON.parse(s.replace("data: ", "")).candidates[0].content.parts[0].text.replace(/\n+/g, "\n") 361 | } catch { 362 | return false 363 | } 364 | }).filter(Boolean) 365 | } catch { 366 | // The error usually occurs when the token exceeds the limit 367 | ztoolkit.log(e.target.response) 368 | } 369 | if (e.target.timeout) { 370 | e.target.timeout = 0; 371 | } 372 | }; 373 | }, 374 | } 375 | ); 376 | } catch (error: any) { 377 | try { 378 | error = JSON.parse(error?.xmlhttp?.response).error 379 | textArr = [`# ${error.code}\n> ${apiURL}\n\n**${error.type}**\n${error.message}`] 380 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 381 | .createLine({ text: error.message, type: "default" }) 382 | .show() 383 | } catch { 384 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 385 | .createLine({ text: error.message, type: "default" }) 386 | .show() 387 | } 388 | } 389 | } else if (curPublisher == "Claude-3") { 390 | try { 391 | var deployedModel = model 392 | if (model.includes(":")) { 393 | let index = model.indexOf(":") 394 | deployedModel = model.substr(index + 1, model.length) 395 | } 396 | var re 397 | await Zotero.HTTP.request( 398 | "POST", 399 | apiURL, 400 | { 401 | headers: { 402 | "x-api-key": `${apiKey}`, 403 | "anthropic-version": "2023-06-01", 404 | "content-type": "application/json", 405 | "anthropic-beta": "messages-2023-12-15" 406 | }, 407 | body: JSON.stringify({ 408 | model: deployedModel, 409 | max_tokens: 2048, 410 | messages: views.messages.slice(-chatNumber), 411 | stream: true, 412 | }), 413 | responseType: "text", 414 | requestObserver: (xmlhttp: XMLHttpRequest) => { 415 | xmlhttp.onprogress = (e: any) => { 416 | try { 417 | textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content_block_delta") >= 0).map((s: string) => { 418 | try { 419 | return JSON.parse(s.replace("data: ", "")).delta.text.replace(/\n+/g, "\n") 420 | } catch { 421 | return false 422 | } 423 | }).filter(Boolean) 424 | } catch { 425 | // The error usually occurs when the token exceeds the limit 426 | ztoolkit.log(e.target.response) 427 | } 428 | if (e.target.timeout) { 429 | e.target.timeout = 0; 430 | } 431 | }; 432 | }, 433 | } 434 | ); 435 | } catch (error: any) { 436 | try { 437 | error = JSON.parse(error?.xmlhttp?.response).error 438 | textArr = [`# ${error.code}\n> ${apiURL}\n\n**${error.type}**\n${error.message}`] 439 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 440 | .createLine({ text: error.message, type: "default" }) 441 | .show() 442 | } catch { 443 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 444 | .createLine({ text: error.message, type: "default" }) 445 | .show() 446 | } 447 | } 448 | } 449 | 450 | responseText = textArr.join("") 451 | ztoolkit.log("responseText", responseText) 452 | views.messages.push({ 453 | role: "assistant", 454 | content: responseText 455 | }) 456 | return responseText 457 | } 458 | 459 | export async function getResponseByLocalLLM(requestText: string) { 460 | const publisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) as string 461 | if (publisher != "Local LLM") { 462 | return 463 | } 464 | const views = Zotero.PapersGPT.views as Views 465 | const temperature = Zotero.Prefs.get(`${config.addonRef}.temperature`) 466 | const apiURL = Zotero.Prefs.get(`${config.addonRef}.usingAPIURL`) as string 467 | const model = Zotero.Prefs.get(`${config.addonRef}.usingModel`) as string 468 | views.messages.push({ 469 | role: "user", 470 | content: requestText 471 | }) 472 | const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number 473 | // Store the last results 474 | let _textArr: string[] = [] 475 | // Changes in real time as requests return 476 | let textArr: string[] = [] 477 | // Activate output 478 | views.stopAlloutput() 479 | views.setText("") 480 | let responseText: string | undefined 481 | const id: number = window.setInterval(async () => { 482 | if (!responseText && _textArr.length == textArr.length) { return} 483 | _textArr = textArr.slice(0, _textArr.length + 1) 484 | let text = _textArr.join("") 485 | text.length > 0 && views.setText(text) 486 | if (responseText && responseText == text) { 487 | views.setText(text, true) 488 | window.clearInterval(id) 489 | } 490 | }, deltaTime) 491 | views._ids.push({ 492 | type: "output", 493 | id: id 494 | }) 495 | const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number 496 | var responseTimeout = 60000 * 3 497 | if (model == "QwQ-32B-Preview" || model == "marco-o1") { 498 | responseTimeout = 10 * 60000 499 | } 500 | 501 | try { 502 | await Zotero.HTTP.request( 503 | "POST", 504 | apiURL, 505 | { 506 | headers: { 507 | "Content-Type": "application/json", 508 | }, 509 | body: JSON.stringify({ 510 | model: model, 511 | messages: views.messages.slice(-chatNumber), 512 | stream: true, 513 | temperature: Number(temperature) 514 | }), 515 | responseType: "text", 516 | requestObserver: (xmlhttp: XMLHttpRequest) => { 517 | xmlhttp.onprogress = (e: any) => { 518 | try { 519 | textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content") >= 0).map((s: string) => { 520 | try { 521 | return JSON.parse(s.replace("data: ", "")).choices[0].delta.content.replace(/\n+/g, "\n") 522 | } catch { 523 | return false 524 | } 525 | }).filter(Boolean) 526 | } catch { 527 | // The error usually occurs when the token exceeds the limit 528 | ztoolkit.log(e.target.response) 529 | Zotero.log(e.target.response) 530 | } 531 | if (e.target.timeout) { 532 | e.target.timeout = 0; 533 | } 534 | }; 535 | }, 536 | timeout: responseTimeout 537 | } 538 | ); 539 | } catch (error: any) { 540 | try { 541 | error = JSON.parse(error?.xmlhttp?.response).error 542 | textArr = [`# ${error.code}\n> ${apiURL}\n\n**${error.type}**\n${error.message}`] 543 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 544 | .createLine({ text: error.message, type: "default" }) 545 | .show() 546 | } catch { 547 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 548 | .createLine({ text: error.message, type: "default" }) 549 | .show() 550 | } 551 | } 552 | responseText = textArr.join("") 553 | views.messages.push({ 554 | role: "assistant", 555 | content: responseText 556 | }) 557 | return responseText 558 | } 559 | 560 | 561 | -------------------------------------------------------------------------------- /src/modules/Meet/papersgpt.ts: -------------------------------------------------------------------------------- 1 | import { Document } from "langchain/document"; 2 | import { Views, sleep } from "../views"; 3 | import { config } from "../../../package.json"; 4 | 5 | export class ModelConfig { 6 | public models: string[] = []; 7 | public hasApiKey: boolean = true; 8 | public apiKey: string = ""; 9 | public areModelsReady: Map = new Map(); 10 | public defaultModelIdx: number = 0; 11 | public apiUrl: string = ""; 12 | public displayName: string = ""; 13 | } 14 | 15 | 16 | export async function search(publisher: string, model: string, 17 | docid: string, queryText: string, 18 | topn: number, embeddingModel: string, 19 | packFields: string) { 20 | var relatedDocs: Document[] = [] 21 | const url = `http://localhost:9080/search` 22 | let res 23 | const views = Zotero.PapersGPT.views as Views 24 | 25 | try { 26 | res = await Zotero.HTTP.request( 27 | "POST", 28 | url, 29 | { 30 | responseType: "json", 31 | headers: { 32 | "Content-Type": "application/json", 33 | }, 34 | body: JSON.stringify({ 35 | publisher: publisher, 36 | model: model, 37 | doc_id: docid, 38 | query: queryText, 39 | topn: topn, 40 | show_fields: packFields 41 | }), 42 | } 43 | ) 44 | } catch (error: any) { 45 | try { 46 | error = error.xmlhttp.response?.error 47 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 48 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 49 | .createLine({ text: error.message, type: "default" }) 50 | .show() 51 | } catch { 52 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 53 | .createLine({ text: error.message, type: "default" }) 54 | .show() 55 | } 56 | } 57 | 58 | if (res?.response?.Fields) { 59 | var fields_array = packFields.split(':') 60 | const fields_num = fields_array.length 61 | if (fields_num > 0) { 62 | const docs_num = res.response.Fields[fields_array[0]].length 63 | if (fields_num == 3) { // selected items 64 | for (let i = 0; i < docs_num; i++) { 65 | relatedDocs.push( 66 | new Document({ 67 | pageContent: res.response.Fields["text-string"][i], 68 | metadata: { 69 | type: res.response.Fields["type-string"][i], 70 | id: res.response.Fields["id-int"][i], 71 | }, 72 | })) 73 | } 74 | } else if (fields_num == 7) { // pdf2documents 75 | for (let i = 0; i < docs_num; i++) { 76 | relatedDocs.push( 77 | new Document({ 78 | pageContent: res.response.Fields["text-string"][i], 79 | metadata: { 80 | type: res.response.Fields["type-string"][i], 81 | box: { page: res.response.Fields["box_page-int"][i], 82 | left: res.response.Fields["box_left-float"][i], 83 | right: res.response.Fields["box_right-float"][i], 84 | top: res.response.Fields["box_top-float"][i], 85 | bottom: res.response.Fields["box_bottom-float"][i] }, 86 | } 87 | })) 88 | } 89 | } 90 | } 91 | } 92 | return relatedDocs 93 | } 94 | 95 | export async function isDocumentExist(key: string) { 96 | let res 97 | const views = Zotero.PapersGPT.views as Views 98 | const url = `http://localhost:9080/isDocumentExist` 99 | try { 100 | res = await Zotero.HTTP.request( 101 | "POST", 102 | url, 103 | { 104 | responseType: "json", 105 | headers: { 106 | "Content-Type": "application/json", 107 | }, 108 | body: JSON.stringify({ 109 | doc_id: key, 110 | }), 111 | } 112 | ) 113 | } catch (error: any) { 114 | try { 115 | error = error.xmlhttp.response?.error 116 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 117 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 118 | .createLine({ text: error.message, type: "default" }) 119 | .show() 120 | } catch { 121 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 122 | .createLine({ text: error.message, type: "default" }) 123 | .show() 124 | } 125 | } 126 | 127 | if (res?.response["Exist"]) { 128 | return res.response["Exist"] 129 | } 130 | return false 131 | } 132 | 133 | export async function addDoc(key: string, docs: Document[], type: string) { 134 | let res 135 | const views = Zotero.PapersGPT.views as Views 136 | var textsArray: string[] = [] 137 | var typesArray: string[] = [] 138 | var idsArray: number[] = [] 139 | var boxPageArray: number[] = [] 140 | var boxLeftArray: number[] = [] 141 | var boxRightArray: number[] = [] 142 | var boxTopArray: number[] = [] 143 | var boxBottomArray: number[] = [] 144 | for (let i = 0; i < docs.length; i++) { 145 | textsArray.push(docs[i].pageContent) 146 | typesArray.push(type) 147 | if (type == "box") { 148 | boxPageArray.push(docs[i].metadata.box.page) 149 | boxLeftArray.push(docs[i].metadata.box.left) 150 | boxRightArray.push(docs[i].metadata.box.right) 151 | boxTopArray.push(docs[i].metadata.box.top) 152 | boxBottomArray.push(docs[i].metadata.box.bottom) 153 | } else if (type == "id") { 154 | idsArray.push(docs[i].metadata.id) 155 | } 156 | } 157 | 158 | const url = `http://localhost:9080/add` 159 | try { 160 | if (type == "id") { 161 | res = await Zotero.HTTP.request( 162 | "POST", 163 | url, 164 | { 165 | responseType: "json", 166 | headers: { 167 | "Content-Type": "application/json", 168 | }, 169 | body: JSON.stringify({ 170 | doc_id: key, 171 | text$string: textsArray, 172 | type$string: typesArray, 173 | id$int: idsArray 174 | }), 175 | } 176 | ) 177 | } else if (type == "box") { 178 | res = await Zotero.HTTP.request( 179 | "POST", 180 | url, 181 | { 182 | responseType: "json", 183 | headers: { 184 | "Content-Type": "application/json", 185 | }, 186 | body: JSON.stringify({ 187 | doc_id: key, 188 | text$string: textsArray, 189 | type$string: typesArray, 190 | box_page$int: boxPageArray, 191 | box_left$float: boxLeftArray, 192 | box_right$float: boxRightArray, 193 | box_top$float: boxTopArray, 194 | box_bottom$float: boxBottomArray 195 | }), 196 | } 197 | ) 198 | } 199 | } catch (error: any) { 200 | try { 201 | error = error.xmlhttp.response?.error 202 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 203 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 204 | .createLine({ text: error.message, type: "default" }) 205 | .show() 206 | } catch { 207 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 208 | .createLine({ text: error.message, type: "default" }) 209 | .show() 210 | } 211 | } 212 | 213 | if (res?.response?.Code) { 214 | if (res.response.Code == 200) { 215 | return true 216 | } 217 | } 218 | return false 219 | } 220 | 221 | 222 | export async function selectModel(publisher: string, model: string) { 223 | let res 224 | const views = Zotero.PapersGPT.views as Views 225 | const url = `http://localhost:9080/selectModel` 226 | try { 227 | res = await Zotero.HTTP.request( 228 | "POST", 229 | url, 230 | { 231 | responseType: "json", 232 | headers: { 233 | "Content-Type": "application/json", 234 | }, 235 | body: JSON.stringify({ 236 | publisher: publisher, 237 | model: model 238 | }), 239 | } 240 | ) 241 | } catch (error: any) { 242 | try { 243 | error = error.xmlhttp.response?.error 244 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 245 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 246 | .createLine({ text: error.message, type: "default" }) 247 | .show() 248 | } catch { 249 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 250 | .createLine({ text: error.message, type: "default" }) 251 | .show() 252 | } 253 | } 254 | 255 | if (res?.response["Code"]) { 256 | return res.response["Code"] == 200 ? true : false 257 | } 258 | return false 259 | } 260 | 261 | 262 | export async function getLocalModelDownloadProgress(model: string) { 263 | let res 264 | 265 | const views = Zotero.PapersGPT.views as Views 266 | const url = `http://localhost:9080/getLocalModelDownloadProgress` 267 | try { 268 | res = await Zotero.HTTP.request( 269 | "POST", 270 | url, 271 | { 272 | responseType: "json", 273 | headers: { 274 | "Content-Type": "application/json", 275 | }, 276 | body: JSON.stringify({ 277 | publisher: "Local LLM", 278 | model: model 279 | }), 280 | } 281 | ) 282 | } catch (error: any) { 283 | try { 284 | error = error.xmlhttp.response?.error 285 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 286 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 287 | .createLine({ text: error.message, type: "default" }) 288 | .show() 289 | } catch { 290 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 291 | .createLine({ text: error.message, type: "default" }) 292 | .show() 293 | } 294 | } 295 | 296 | if (res?.response["Code"]) { 297 | if (res.response["Code"] == 203) { 298 | var downloadingValue = res.response["DownloadingPercent"] 299 | return (downloadingValue > 100 || downloadingValue < 0 ) ? 0 : downloadingValue 300 | } else if (res.response["Code"] == 200 301 | || res.response["Code"] == 201 302 | || res.response["Code"] == 202) { 303 | return res.response["Code"] 304 | } else { 305 | return -1 306 | } 307 | } 308 | return -1 309 | } 310 | 311 | export async function setApiKey(publisher: string, apiKey: string) { 312 | let res 313 | const views = Zotero.PapersGPT.views as Views 314 | const url = `http://localhost:9080/setLLMApiKey` 315 | try { 316 | res = await Zotero.HTTP.request( 317 | "POST", 318 | url, 319 | { 320 | responseType: "json", 321 | headers: { 322 | "Content-Type": "application/json", 323 | }, 324 | body: JSON.stringify({ 325 | publisher: publisher, 326 | API_KEY: apiKey 327 | }), 328 | } 329 | ) 330 | } catch (error: any) { 331 | try { 332 | error = error.xmlhttp.response?.error 333 | views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true) 334 | new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true }) 335 | .createLine({ text: error.message, type: "default" }) 336 | .show() 337 | } catch { 338 | new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true }) 339 | .createLine({ text: error.message, type: "default" }) 340 | .show() 341 | } 342 | } 343 | 344 | 345 | if (res?.response["Code"]) { 346 | return res.response["Code"] 347 | } 348 | return -1 349 | } 350 | 351 | function parseJsonResults(publisher2models: Map, publishers: string[], supportedLLMsJson: []) { 352 | 353 | const try_url = Zotero.Prefs.get(`${config.addonRef}.customModelApiUrl`) 354 | Zotero.log(try_url) 355 | if (!try_url) { 356 | Zotero.log("Setting default values for custom model") 357 | Zotero.Prefs.set(`${config.addonRef}.customModelApiUrl`, "https://api.openai.com/v1/chat/completions") 358 | Zotero.Prefs.set(`${config.addonRef}.customModelApiKey`, "xxxx2552xxxx41xxxx58xxxxc31xxxx7") 359 | Zotero.Prefs.set(`${config.addonRef}.customModelApiModel`, "gpt-4o") 360 | } 361 | 362 | // get base_url, api_key, model from Zotero.Prefs 363 | const curAPIUrl = Zotero.Prefs.get(`${config.addonRef}.customModelApiUrl`) 364 | const curAPIKey = Zotero.Prefs.get(`${config.addonRef}.customModelApiKey`) 365 | const curModel = Zotero.Prefs.get(`${config.addonRef}.customModelApiModel`) 366 | 367 | 368 | Zotero.Prefs.set(`${config.addonRef}.usingAPIKEY`, curAPIKey as string) 369 | Zotero.Prefs.set(`${config.addonRef}.usingAPIURL`, curAPIUrl as string) 370 | Zotero.Prefs.set(`${config.addonRef}.usingModel`, curModel as string) 371 | 372 | 373 | 374 | 375 | 376 | // var curPublisher = Zotero.Prefs.get(`${config.addonRef}.usingPublisher`) 377 | // for (var i = 0; i < supportedLLMsJson.length; i++) { 378 | // const publisher = supportedLLMsJson[i]["Publisher"] 379 | // var models = [] 380 | // var modelsAreReady = new Map() 381 | 382 | // models = supportedLLMsJson[i]["Models"] 383 | 384 | // // pref("extensions.zotero.__addonRef__.customModelApiUrl", "https://api.openai.com/v1/chat/completions"); 385 | // // pref("extensions.zotero.__addonRef__.customModelApiKey", "xxxx2552xxxx41xxxx58xxxxc31xxxx7"); 386 | // // pref("extensions.zotero.__addonRef__.customModelApiModel", "gpt-4o"); 387 | 388 | // // try get url. if url is not set, then set all above three to default value 389 | // const try_url = Zotero.Prefs.get(`${config.addonRef}.customModelApiUrl`) 390 | // if (try_url.length == 0) { 391 | // Zotero.Prefs.set(`${config.addonRef}.customModelApiUrl`, "https://api.openai.com/v1/chat/completions") 392 | // Zotero.Prefs.set(`${config.addonRef}.customModelApiKey`, "xxxx2552xxxx41xxxx58xxxxc31xxxx7") 393 | // Zotero.Prefs.set(`${config.addonRef}.customModelApiModel`, "gpt-4o") 394 | // } 395 | 396 | 397 | // var customizedModel = Zotero.Prefs.get(`${config.addonRef}.customModelApiModel`) 398 | // if (customizedModel.length > 0 && models.length == 0) { 399 | // models.push(customizedModel) 400 | // } else if (customizedModel.length > 0 && models.length > 0) { 401 | // models[0] = customizedModel 402 | // } 403 | 404 | 405 | // // var apiKey = supportedLLMsJson[i].hasOwnProperty("API_KEY") ? supportedLLMsJson[i]["API_KEY"] : "" 406 | // // if (apiKey.length == 0) { 407 | // // if (publisher == "OpenAI") { 408 | // // apiKey = Zotero.Prefs.get(`${config.addonRef}.openaiApiKey`) 409 | // // } else if (publisher == "Claude-3") { 410 | // // apiKey = Zotero.Prefs.get(`${config.addonRef}.claudeApiKey`) 411 | // // } else if (publisher == "Gemini") { 412 | // // apiKey = Zotero.Prefs.get(`${config.addonRef}.geminiApiKey`) 413 | // // } else if (publisher == "Customized") { 414 | // // apiKey = Zotero.Prefs.get(`${config.addonRef}.customModelApiKey`) 415 | // // } 416 | // // } 417 | 418 | // // var apiUrl = supportedLLMsJson[i]["API_URL"] 419 | // // if (publisher == "Customized" && apiUrl.length == 0) { 420 | // // apiUrl = Zotero.Prefs.get(`${config.addonRef}.customModelApiUrl`) 421 | // // } 422 | 423 | 424 | // let modelConfig: ModelConfig = { 425 | // models: models, 426 | // hasApiKey: true, 427 | // apiKey: curAPIKey as string, 428 | // areModelsReady: modelsAreReady, 429 | // defaultModelIdx: 0, 430 | // apiUrl: apiUrl 431 | // } 432 | 433 | // if (publisher == curPublisher && supportedLLMsJson[i].hasOwnProperty("API_KEY") && supportedLLMsJson[i]["API_KEY"].length > 0) { 434 | // Zotero.Prefs.set(`${config.addonRef}.usingAPIKEY`, supportedLLMsJson[i]["API_KEY"]) 435 | // } 436 | 437 | // var temp = publisher2models.get(publisher) 438 | // if (temp == null) { 439 | // publishers.push(publisher) 440 | // } 441 | // publisher2models.set(publisher, modelConfig) 442 | // } 443 | } 444 | 445 | 446 | export async function getSupportedLLMs(publisher2models: Map, publishers:string[], email: string, token: string) { 447 | Zotero.log("Getting supported LLMs!") 448 | const supportedLLMsJson = [ 449 | { 450 | "Publisher": "Customized", 451 | "Models": ["gpt-4o"], 452 | "API_URL": "", 453 | 454 | }, 455 | ] 456 | Zotero.Prefs.set(`${config.addonRef}.isLicenseActivated`, true) 457 | Zotero.Prefs.set(`${config.addonRef}.supportedLLMs`, JSON.stringify( 458 | supportedLLMsJson 459 | )) 460 | parseJsonResults(publisher2models, publishers, supportedLLMsJson) 461 | 462 | // var httpRequestError = false 463 | // let res 464 | // const views = Zotero.PapersGPT.views as Views 465 | 466 | // var url = "" 467 | // var trycount = 0 468 | 469 | // let isActivated = Zotero.Prefs.get(`${config.addonRef}.isLicenseActivated`) 470 | // isActivated = true 471 | // const supportedLLMs = Zotero.Prefs.get(`${config.addonRef}.supportedLLMs`) as string 472 | 473 | 474 | // //! TODO: hack this 475 | // if (isActivated 476 | // && supportedLLMs.length > 0) { 477 | // var supportedLLMsJson = JSON.parse(supportedLLMs) 478 | // if (supportedLLMsJson.length > 0) { 479 | // parseJsonResults(publisher2models, publishers, supportedLLMsJson) 480 | // return 481 | // } 482 | // } 483 | 484 | 485 | // var trycount = 0 486 | 487 | // do { 488 | // url = `https://www.papersgpt.com/api/supportmodels` 489 | // try { 490 | // res = await Zotero.HTTP.request( 491 | // "POST", 492 | // url, 493 | // { 494 | // responseType: "json", 495 | // headers: { 496 | // "Content-Type": "application/json", 497 | // }, 498 | // body: JSON.stringify({ 499 | // email: email, 500 | // token: token, 501 | // }), 502 | // timeout: 2000 503 | // } 504 | // ) 505 | // } catch (error: any) { 506 | // try { 507 | // httpRequestError = true 508 | // error = error.xmlhttp.response?.error 509 | // Zotero.log(error.message) 510 | // } catch { 511 | // Zotero.log(error) 512 | // httpRequestError = true 513 | // } 514 | // } 515 | // trycount = trycount + 1 516 | // } while (trycount < 2 && httpRequestError) 517 | 518 | 519 | 520 | // if (httpRequestError) { 521 | // Zotero.log("request error") 522 | // return 523 | // } 524 | 525 | // if (res?.response.Code) { 526 | // if (res.response.Code != 200) { 527 | // return 528 | // } 529 | // Zotero.Prefs.set(`${config.addonRef}.isLicenseActivated`, true) 530 | // var allElements = res?.response.SupportedLLMs as [] 531 | // var supportedLLMsStr = JSON.stringify(allElements) 532 | 533 | 534 | // parseJsonResults(publisher2models, publishers, allElements) 535 | // } 536 | } 537 | 538 | -------------------------------------------------------------------------------- /src/modules/base.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | 4 | const help = ` 5 | ### Quick Commands 6 | 7 | \`/help\` Show all commands. 8 | \`/clear\` Clear history conversation. 9 | \`/report\` Run this and copy the output content to give feedback to the developer. 10 | \`/secretKey sk-xxx\` Set GPT secret key. Generate it in https://platform.openai.com/account/api-keys. 11 | \`/api https://api.openai.com\` Set API. 12 | \`/model gpt-4/gpt-3.5-turbo\` Set GPT model. For example, \`/model gpt-3.5-turbo\`. 13 | \`/temperature 1.0\` Set GPT temperature. Controls the randomness and diversity of generated text, specified within a range of 0 to 1. 14 | \`/chatNumber 3\` Set the number of saved historical conversations. 15 | \`/relatedNumber 5\` Set the number of most relevant text. For example, the number of paragraphs referenced while using askPDF. 16 | \`/deltaTime 100\` Control GPT smoothness (ms). 17 | \`/width 32%\` Control GPT UI width (pct). 18 | \`/tagsMore expand/scroll\` Set mode to display more tags. 19 | \`/key default\` Restore the variable values above to their default values (if have). 20 | 21 | ### About UI 22 | 23 | You can hold down \`Ctrl\` and scroll the mouse wheel to zoom the entire UI. 24 | And when your mouse is in the output box, the size of any content in the output box will be adjusted. 25 | 26 | ### About Tag 27 | 28 | You can \`long click\` on the tag below to see its internal pseudo-code. 29 | You can type \`#xxx\` and press \`Enter\` to create a tag. And save it with \`Ctrl + S\`, during which you can execute it with \`Ctrl + R\`. 30 | You can \`right-long-click\` a tag to delete it. 31 | 32 | ### About Output Text 33 | 34 | You can \`double click\` on this text to copy GPT's answer. 35 | You can \`long press\` me without releasing, then move me to a suitable position before releasing. 36 | 37 | ### About Input Text 38 | 39 | You can exit me by pressing \`Esc\` above my head and wake me up by pressing \`Shift + /\` or \`Shift + ?\` in the Zotero main window. 40 | You can type the question in my header, then press \`Enter\` to ask me. 41 | You can press \`Ctrl + Enter\` to execute last executed command tag again. 42 | You can press \`Shift + Enter\` to enter long text editing mode and press \`Ctrl + R\` to execute long text. 43 | ` 44 | // This is OpenAI ChatGPT font style 45 | const fontFamily = `Söhne,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif,Helvetica Neue,Arial,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji` 46 | 47 | function parseTag(text: string) { 48 | text = text.replace(/^\n/, "").replace(/\n$/, "") 49 | let tagString = text.match(/^#(.+)\n/) as any 50 | function randomColor() { 51 | var letters = '0123456789ABCDEF'; 52 | var color = '#'; 53 | for (var i = 0; i < 6; i++) { 54 | color += letters[Math.floor(Math.random() * 16)]; 55 | } 56 | return color; 57 | } 58 | let tag: Tag = { 59 | tag: config.addonName, 60 | color: randomColor(), 61 | position: 9, 62 | text: text, 63 | trigger: "", 64 | } 65 | if (tagString) { 66 | tagString = tagString[0] 67 | tag.tag = tagString.match(/^#([^\[\n]+)/)[1] 68 | // parse color 69 | let color = tagString.match(/\[c(?:olor)?="?(#.+?)"?\]/) 70 | tag.color = color?.[1] || tag.color 71 | // parse position 72 | let position = tagString.match(/\[pos(?:ition)?="?(\d+?)"?\]/) 73 | tag.position = Number(position?.[1] || tag.position) 74 | // parse trigger keyword 75 | let trigger = tagString.match(/\[tr(?:igger)?="?(.+)"?\]/) 76 | tag.trigger = trigger?.[1] || tag.trigger 77 | tag.text = `#${tag.tag}[position=${tag.position}][color=${tag.color}][trigger=${tag.trigger}]` + "\n" + text.replace(/^#.+\n/, "") 78 | } 79 | return tag 80 | } 81 | 82 | let defaultChatPrompt: string = 83 | ` 84 | #Chat PDF[color=#0EA293][position=10][trigger=] 85 | You are a helpful assistant. Context information is below. 86 | $\{ 87 | Meet.Global.views.messages = []; 88 | Meet.Zotero.getRelatedText(Meet.Global.input) 89 | \} 90 | Using the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 91 | 92 | Answer the question: $\{Meet.Global.input\} 93 | 94 | Reply in ${Zotero.locale} 95 | ` 96 | 97 | 98 | let defaultBuiltInPrompts: any = [ 99 | "Summary", 100 | "Define the topic discussed in the provided context information", 101 | "Provide a detailed overview of its origins, significant milestones, and key developments over time", 102 | "Innovations", 103 | "Criticisms, limitations, or challenges of the topic talking about in the paper", 104 | "Potential future directions and developments" 105 | ] 106 | 107 | 108 | /** 109 | * The default label here cannot be deleted, but the content inside can be changed, such as color position and internal prompt 110 | */ 111 | let defaultBuiltInTags: any = [ 112 | ` 113 | #Summary[color=#0EA293][position=10] 114 | You are an academic research expert. Context information is below. 115 | $\{ 116 | Meet.Global.views.messages = []; 117 | Meet.Zotero.getRelatedText(Meet.Global.input) 118 | \} 119 | Using the provided context information of the research paper, produce a concise and clear summary that encapsulates the main findings, methodology, results, and implications of the study. Ensure that the summary is written in a manner that is accessible to a general audience while retaining the core insights and nuances of the original paper. Include key terms and concepts, and provide any necessary context or background information. The summary should serve as a standalone piece that gives readers a comprehensive understanding of the paper's significance without needing to read the entire document. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 120 | 121 | Reply in ${Zotero.locale} 122 | `, 123 | ` 124 | #Topic[color=#F49D1A][position=11] 125 | You are a research expert. Context information is below. 126 | $\{ 127 | Meet.Global.views.messages = []; 128 | Meet.Zotero.getRelatedText(Meet.Global.input) 129 | \} 130 | Using the provided context information of the research paper, define the topic of the paper clearly. Please provide a comprehensive definition that includes the core aspects of the topic, its boundaries, and the various perspectives from which it can be understood. Also, highlight any key terms or concepts that are essential to grasping the topic fully. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 131 | 132 | Reply in ${Zotero.locale} 133 | `, 134 | ` 135 | #Background[color=#0EA293][position=12] 136 | You are a research expert. Context information is below. 137 | $\{ 138 | Meet.Global.views.messages = []; 139 | Meet.Zotero.getRelatedText(Meet.Global.input) 140 | \} 141 | Using the provided context information of the research paper, understand the historical context of the topic talking about in the paper. Please provide a detailed overview of its origins, significant milestones, and key developments over time. Include any historical figures, events, or movements that have played a crucial role in shaping this topic. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 142 | 143 | Reply in ${Zotero.locale} 144 | `, 145 | ` 146 | #Innovations[color=#159895][position=13] 147 | You are a research expert. Context information is below. 148 | $\{ 149 | Meet.Global.views.messages = []; 150 | Meet.Zotero.getRelatedText(Meet.Global.input) 151 | \} 152 | Using the provided context information of the research paper, list the main contributions or innovations of this paper. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information 153 | 154 | Reply in ${Zotero.locale} 155 | `, 156 | ` 157 | #Challenges[color=#F14D72][position=14] 158 | You are a critical analysis expert. Context information is below. 159 | $\{ 160 | Meet.Global.views.messages = []; 161 | Meet.Zotero.getRelatedText(Meet.Global.input) 162 | \} 163 | Using the provided context information of the research paper, identify the challenges and criticisms. Please discuss any common criticisms, limitations, or challenges that researchers or practitioners face when dealing with this topic. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information 164 | 165 | Reply in ${Zotero.locale} 166 | `, 167 | ` 168 | #Outlook[color=#F14D72][position=15] 169 | You are a futurist expert. Context information is below. 170 | $\{ 171 | Meet.Global.views.messages = []; 172 | Meet.Zotero.getRelatedText(Meet.Global.input) 173 | \} 174 | Using the provided context information of the research paper, explore future directions and the potential. Please provide insights into where this field might be headed, including potential future developments and the impact they could have. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information 175 | 176 | Reply in ${Zotero.locale} 177 | `, 178 | ` 179 | #Translate[color=#F14D72][position=16][trigger=/^translate/] 180 | Translate these content to $\{Meet.Zotero.getTranslatingLanguage\}: 181 | $\{ 182 | Meet.Zotero.getPDFSelection() || 183 | Meet.Global.views.messages[0].content 184 | \} 185 | `, 186 | ` 187 | #Improve writing[color=#8e44ad][position=17][trigger=/^improve writing/] 188 | Below is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do so in markdown table. Paragraph: "$\{ 189 | Meet.Global.views.messages[0].content 190 | \}" 191 | `, 192 | ] 193 | defaultBuiltInTags = defaultBuiltInTags.map(parseTag) 194 | 195 | 196 | export { help, fontFamily, defaultBuiltInTags, parseTag, defaultChatPrompt, defaultBuiltInPrompts } 197 | -------------------------------------------------------------------------------- /src/modules/base.ts.bak: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | 4 | const help = ` 5 | ### Quick Commands 6 | 7 | \`/help\` Show all commands. 8 | \`/clear\` Clear history conversation. 9 | \`/report\` Run this and copy the output content to give feedback to the developer. 10 | \`/secretKey sk-xxx\` Set GPT secret key. Generate it in https://platform.openai.com/account/api-keys. 11 | \`/api https://api.openai.com\` Set API. 12 | \`/model gpt-4/gpt-3.5-turbo\` Set GPT model. For example, \`/model gpt-3.5-turbo\`. 13 | \`/temperature 1.0\` Set GPT temperature. Controls the randomness and diversity of generated text, specified within a range of 0 to 1. 14 | \`/chatNumber 3\` Set the number of saved historical conversations. 15 | \`/relatedNumber 5\` Set the number of most relevant text. For example, the number of paragraphs referenced while using askPDF. 16 | \`/deltaTime 100\` Control GPT smoothness (ms). 17 | \`/width 32%\` Control GPT UI width (pct). 18 | \`/tagsMore expand/scroll\` Set mode to display more tags. 19 | \`/key default\` Restore the variable values above to their default values (if have). 20 | 21 | ### About UI 22 | 23 | You can hold down \`Ctrl\` and scroll the mouse wheel to zoom the entire UI. 24 | And when your mouse is in the output box, the size of any content in the output box will be adjusted. 25 | 26 | ### About Tag 27 | 28 | You can \`long click\` on the tag below to see its internal pseudo-code. 29 | You can type \`#xxx\` and press \`Enter\` to create a tag. And save it with \`Ctrl + S\`, during which you can execute it with \`Ctrl + R\`. 30 | You can \`right-long-click\` a tag to delete it. 31 | 32 | ### About Output Text 33 | 34 | You can \`double click\` on this text to copy GPT's answer. 35 | You can \`long press\` me without releasing, then move me to a suitable position before releasing. 36 | 37 | ### About Input Text 38 | 39 | You can exit me by pressing \`Esc\` above my head and wake me up by pressing \`Shift + /\` or \`Shift + ?\` in the Zotero main window. 40 | You can type the question in my header, then press \`Enter\` to ask me. 41 | You can press \`Ctrl + Enter\` to execute last executed command tag again. 42 | You can press \`Shift + Enter\` to enter long text editing mode and press \`Ctrl + R\` to execute long text. 43 | ` 44 | // This is OpenAI ChatGPT font style 45 | const fontFamily = `Söhne,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif,Helvetica Neue,Arial,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji` 46 | 47 | function parseTag(text: string) { 48 | text = text.replace(/^\n/, "").replace(/\n$/, "") 49 | let tagString = text.match(/^#(.+)\n/) as any 50 | function randomColor() { 51 | var letters = '0123456789ABCDEF'; 52 | var color = '#'; 53 | for (var i = 0; i < 6; i++) { 54 | color += letters[Math.floor(Math.random() * 16)]; 55 | } 56 | return color; 57 | } 58 | let tag: Tag = { 59 | tag: config.addonName, 60 | color: randomColor(), 61 | position: 9, 62 | text: text, 63 | trigger: "", 64 | } 65 | if (tagString) { 66 | tagString = tagString[0] 67 | tag.tag = tagString.match(/^#([^\[\n]+)/)[1] 68 | // parse color 69 | let color = tagString.match(/\[c(?:olor)?="?(#.+?)"?\]/) 70 | tag.color = color?.[1] || tag.color 71 | // parse position 72 | let position = tagString.match(/\[pos(?:ition)?="?(\d+?)"?\]/) 73 | tag.position = Number(position?.[1] || tag.position) 74 | // parse trigger keyword 75 | let trigger = tagString.match(/\[tr(?:igger)?="?(.+)"?\]/) 76 | tag.trigger = trigger?.[1] || tag.trigger 77 | tag.text = `#${tag.tag}[position=${tag.position}][color=${tag.color}][trigger=${tag.trigger}]` + "\n" + text.replace(/^#.+\n/, "") 78 | } 79 | return tag 80 | } 81 | 82 | /** 83 | * The default label here cannot be deleted, but the content inside can be changed, such as color position and internal prompt 84 | */ 85 | let defaultTags: any = [ 86 | ` 87 | #ChatPDF[color=#0EA293][position=10][trigger=/^(本文|这篇文章|论文)/] 88 | You are a helpful assistant. Context information is below. 89 | $\{ 90 | Meet.Global.views.messages = []; 91 | Meet.Zotero.getRelatedText(Meet.Global.input) 92 | \} 93 | Using the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 94 | 95 | Answer the question: $\{Meet.Global.input\} 96 | 97 | Reply in ${Zotero.locale} 98 | `, 99 | ` 100 | #Translate[c=#D14D72][pos=11][trigger=/^翻译/] 101 | Translate these content to $\{Meet.Zotero.getTranslatingLanguage\}: 102 | $\{ 103 | Meet.Global.input.replace("翻译", "") || 104 | Meet.Zotero.getPDFSelection() || 105 | Meet.Global.views.messages[0].content 106 | \} 107 | 108 | `, 109 | ` 110 | #Improve writing[color=#8e44ad][pos=12][trigger=/^润色/] 111 | Below is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do so in markdown table. Paragraph: "$\{ 112 | Meet.Global.input.replace("润色", "") || 113 | Meet.Global.views.messages[0].content 114 | \}" 115 | `, 116 | ` 117 | #Clipboard[c=#576CBC][pos=13][trigger=/(剪贴板|复制内容)/] 118 | This is the content in my clipboard: 119 | $\{Meet.Zotero.getClipboardText()\} 120 | --- 121 | $\{Meet.Global.input\} 122 | `, 123 | ` 124 | #Annotations[c=#F49D1A][pos=14][trigger=/(选中|选择的|选择|所选)?(注释|高亮|标注)/] 125 | These are PDF Annotation contents: 126 | $\{ 127 | Meet.Zotero.getPDFAnnotations(Meet.Global.input.match(/(选中|选择的|选择|所选)/)) 128 | \} 129 | 130 | Please answer me in the language of my question. Make sure to cite results using [number] notation after the reference. 131 | My question is: $\{Meet.Global.input\} 132 | `, 133 | ` 134 | #Selection[c=#D14D72][pos=15][trigger=/^(这段|选中)(文本|话|文字|描述)/] 135 | Read these content: 136 | $\{ 137 | Meet.Zotero.getPDFSelection() || 138 | Meet.Global.views.messages[0].content 139 | \} 140 | --- 141 | Answer me in the language of my question. This is my question: $\{Meet.Global.input\} 142 | `, 143 | ` 144 | #Item[c=#159895][pos=16][trigger=/这篇(文献|论文|文章)/] 145 | This is a Zotero item presented in JSON format: 146 | $\{ 147 | JSON.stringify(ZoteroPane.getSelectedItems()[0].toJSON()) 148 | \} 149 | 150 | Base on this JSON: $\{Meet.Global.input\} 151 | `, 152 | ` 153 | #Items[c=#159895][pos=17][trigger=/这些(文献|论文)/] 154 | These are Zotero items presented in JSON format: 155 | $\{ 156 | Meet.Zotero.getRelatedText(Meet.Global.input) 157 | \} 158 | 159 | Please answer me using the lanaguage as same as my question. Make sure to cite results using [number] notation after the reference. 160 | My question is: $\{Meet.Global.input\} 161 | `, 162 | ] 163 | defaultTags = defaultTags.map(parseTag) 164 | 165 | 166 | export { help, fontFamily, defaultTags, parseTag } 167 | -------------------------------------------------------------------------------- /src/modules/localStorage.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | class LocalStorage { 4 | public filename!: string; 5 | public cache: any; 6 | public lock: any; 7 | constructor(filename: string) { 8 | this.lock = Zotero.Promise.defer() 9 | this.init(filename) 10 | } 11 | 12 | async init(filename: string) { 13 | const temp = Zotero.getTempDirectory(); 14 | Zotero.log(temp) 15 | this.filename = PathUtils.join(temp.path.replace(temp.leafName, ""), `${filename}.json`); 16 | try { 17 | const rawString = await Zotero.File.getContentsAsync(this.filename) as string 18 | this.cache = JSON.parse(rawString) 19 | } catch { 20 | this.cache = {} 21 | } 22 | this.lock.resolve() 23 | } 24 | 25 | get(item: Zotero.Item | { key: string }, key: string) { 26 | if (this.cache == undefined) { return } 27 | return (this.cache[item.key] ??= {})[key] 28 | } 29 | 30 | async set(item: Zotero.Item | { key: string }, key: string, value: any) { 31 | await this.lock.promise; 32 | (this.cache[item.key] ??= {})[key] = value 33 | window.setTimeout(async () => { 34 | await Zotero.File.putContentsAsync(this.filename, JSON.stringify(this.cache)); 35 | }) 36 | } 37 | } 38 | 39 | export default LocalStorage 40 | 41 | -------------------------------------------------------------------------------- /src/modules/locale.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | export function initLocale() { 4 | addon.data.locale = { 5 | stringBundle: Components.classes["@mozilla.org/intl/stringbundle;1"] 6 | .getService(Components.interfaces.nsIStringBundleService) 7 | .createBundle(`chrome://${config.addonRef}/locale/addon.properties`), 8 | }; 9 | } 10 | 11 | export function getString( 12 | localString: string, 13 | noReload: boolean = false 14 | ): string { 15 | try { 16 | return addon.data.locale?.stringBundle.GetStringFromName(localString); 17 | } catch (e) { 18 | if (!noReload) { 19 | initLocale(); 20 | return getString(localString, true); 21 | } 22 | return localString; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/modules/prompts.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | 4 | interface Prompt { 5 | name: string 6 | read_selection: boolean 7 | description: string 8 | prompt: string 9 | display: { 10 | color: string 11 | priority: number 12 | } 13 | } 14 | 15 | const default_prompt_list : Prompt[] = [ 16 | { 17 | name: "Abstract", 18 | read_selection: true, 19 | description: "Given abstract, summarize it.", 20 | prompt: `# 角色 21 | 你是文献摘要助手,具备快速阅读和理解机器学习文献的能力。 22 | # 工作任务 23 | 你的输入是文献的摘要部分,或简介部分,或两者均有。 24 | 1. 理解工作的背景与应用价值。 25 | 2. 分析之前方法的做法与挑战。 26 | 3. 概述采用的方法与对应的解决挑战。 27 | 4. 汇总实验过程与结论。 28 | 5. 归纳其他摘要中提到的点。 29 | 6. 输出完所有要点后,请根据你的理解,提出几个在这一部分还没有写清楚的问题,以及你认为可以进一步探讨的方向。 30 | # 注意事项 31 | - 确保文献内容准确无误。 32 | - 输出格式需遵循Markdown规范。 33 | - 分点作答,分点作答,分点作答!(把每一点放到四级标题里) 34 | - 保持英文输出。 35 | - 输出尽可能简洁明了,同一个点表达出意思即可,不必过多展开。 36 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $$...$$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。 37 | # 输入摘要`, 38 | display: { 39 | color: "#0EA293", 40 | priority: 10, // smaller number means to appear first 41 | }, 42 | }, 43 | { 44 | name: "Bullet", 45 | read_selection: true, 46 | description: "Decompose the provided text into bullets, helping readers to understand.", 47 | prompt: `# 角色 48 | 你是机器学习文献阅读助手,具备快速阅读和理解机器学习文献的能力。 49 | # 工作任务 50 | 你的输入是文献的全文或部分段落。请将输入的内容分解成简洁的要点,以便他人快速理解。 51 | 1. 按照逻辑关系组织要点。 52 | 2. 每个要点尽量简洁明了。 53 | 3. 试着概括每个要点在讲什么。(如这里在讲 xxx 这一技术的 细节 / 优势 / 和yyy的比较...) 54 | 4. 保留原文的关键词。 55 | # 注意事项 56 | - 确保要点准确无误。 57 | - 输出格式需遵循Markdown规范。 58 | - 分点作答,分点作答,分点作答!(把每一点放到四级标题里) 59 | - 保持英文输出。 60 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $$...$$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。 61 | # 输入文本`, 62 | display: { 63 | color: "#aabbcc", 64 | priority: 11, 65 | }, 66 | }, 67 | { 68 | name: "Translate", 69 | read_selection: true, 70 | description: "Translate the provided text into Chinese.", 71 | prompt: `# 角色 72 | 你是机器学习文献翻译助手,具备快速翻译英文文献的能力。 73 | # 工作任务 74 | 你的输入是英文文献的全文或部分段落。请将输入的内容翻译成中文。 75 | 1. 翻译内容需准确无误。 76 | 2. 保留原文的逻辑结构。 77 | 3. 保留原文的关键词。 78 | 4. 翻译成中文后,再次检查是否符合中文表达习惯。 79 | # 注意事项 80 | - 确保翻译内容准确无误。 81 | - 输出格式需遵循Markdown规范。 82 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $$...$$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。`, 83 | display: { 84 | color: "#FFC107", 85 | priority: 12, 86 | }, 87 | }, 88 | { 89 | name: "Summary", 90 | read_selection: true, 91 | description: "Summarize the provided text into a shorter version.", 92 | prompt: `# 角色 93 | 你是机器学习文献总结助手,具备快速总结文献内容的能力。 94 | # 工作任务 95 | 你的输入是英文文献的全文或部分段落。请将输入的内容进行总结。 96 | 1. 总结内容需准确无误。 97 | 2. 保留原文的逻辑结构。 98 | 3. 保留原文的关键词。 99 | 4. 总结内容需简洁明了。 100 | # 注意事项 101 | - 确保总结内容准确无误。 102 | - 输出格式需遵循Markdown规范。 103 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $$...$$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。`, 104 | display: { 105 | color: "#FF5722", 106 | priority: 13, 107 | }, 108 | }, 109 | { 110 | name: "Experiment", 111 | read_selection: true, 112 | description: "Summarize experiment settings and results.", 113 | prompt: `# 角色 114 | 你是机器学习文献实验助手,具备快速理解实验内容的能力。 115 | # 工作任务 116 | 你的输入是文献的实验部分。请将输入的内容进行总结。 117 | 1. 都用了哪些数据集?分别用来做什么?用了哪些评价指标?每个指标的含义是什么? 118 | 2. 都用了哪些基线方法?为什么选择这些方法?这些方法的优缺点是什么? 119 | 3. 都做了哪些实验?实验的目的是什么?实验的结果是什么? 120 | 4. 你认为实验的设计是否合理?有哪些地方可以改进? 121 | # 注意事项 122 | - 确保实验内容准确无误。 123 | - 输出格式需遵循Markdown规范。 124 | - 分点作答,分点作答,分点作答! 125 | - 保持英文输出。 126 | - 当你遇到数学公式时,请使用 $...$ 包裹行内公式,使用 $$...$$ 包裹块公式。注意不要使用 \(...\) 和 \[...\]。 127 | # 输入实验内容`, 128 | display: { 129 | color: "#FFC107", 130 | priority: 14, 131 | }, 132 | }, 133 | ] 134 | 135 | 136 | 137 | 138 | export { Prompt, default_prompt_list } 139 | -------------------------------------------------------------------------------- /src/modules/utils.ts: -------------------------------------------------------------------------------- 1 | import Meet from "./Meet/api"; 2 | 3 | export default class Utils { 4 | constructor() { 5 | } 6 | public getRGB(color: string) { 7 | var sColor = color.toLowerCase(); 8 | var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; 9 | if (sColor && reg.test(sColor)) { 10 | if (sColor.length === 4) { 11 | var sColorNew = "#"; 12 | for (var i = 1; i < 4; i += 1) { 13 | sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1)); 14 | } 15 | sColor = sColorNew; 16 | } 17 | var sColorChange = []; 18 | for (var i = 1; i < 7; i += 2) { 19 | sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2))); 20 | } 21 | return sColorChange; 22 | } 23 | return sColor; 24 | } 25 | 26 | /** 27 | * @deprecated 28 | * @param queryText 29 | * @returns 30 | */ 31 | public async getRelatedText(queryText: string) { 32 | return await Meet.Zotero.getRelatedText(queryText) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/ztoolkit.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../package.json"; 2 | 3 | export { createZToolkit }; 4 | 5 | function createZToolkit() { 6 | // const _ztoolkit = new ZoteroToolkit(); 7 | /** 8 | * Alternatively, import toolkit modules you use to minify the plugin size. 9 | * You can add the modules under the `MyToolkit` class below and uncomment the following line. 10 | */ 11 | const _ztoolkit = new MyToolkit(); 12 | initZToolkit(_ztoolkit); 13 | return _ztoolkit; 14 | } 15 | 16 | function initZToolkit(_ztoolkit: ReturnType) { 17 | const env = __env__; 18 | _ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`; 19 | _ztoolkit.basicOptions.log.disableConsole = env === "production"; 20 | _ztoolkit.UI.basicOptions.ui.enableElementJSONLog = __env__ === "development"; 21 | _ztoolkit.UI.basicOptions.ui.enableElementDOMLog = __env__ === "development"; 22 | _ztoolkit.basicOptions.debug.disableDebugBridgePassword = 23 | __env__ === "development"; 24 | _ztoolkit.basicOptions.api.pluginID = config.addonID; 25 | _ztoolkit.ProgressWindow.setIconURI( 26 | "default", 27 | `chrome://${config.addonRef}/content/icons/favicon.ico`, 28 | ); 29 | } 30 | 31 | import { BasicTool, UITool, ReaderTool, VirtualizedTableHelper, ProgressWindowHelper, ClipboardHelper, MenuManager, unregister, KeyboardManager } from "zotero-plugin-toolkit" 32 | 33 | 34 | class MyToolkit extends BasicTool { 35 | 36 | UI: UITool; 37 | VirtualizedTable: typeof VirtualizedTableHelper; 38 | ProgressWindow: typeof ProgressWindowHelper; 39 | Menu: MenuManager; 40 | //Guide: typeof GuideHelper; 41 | Shortcut: KeyboardManager; 42 | Reader: ReaderTool; 43 | Clipboard: typeof ClipboardHelper 44 | 45 | constructor() { 46 | super(); 47 | this.UI = new UITool(this); 48 | this.VirtualizedTable = VirtualizedTableHelper; 49 | this.ProgressWindow = ProgressWindowHelper; 50 | this.Menu = new MenuManager(this); 51 | //this.Guide = GuideHelper; 52 | this.Shortcut = new KeyboardManager(this); 53 | this.Reader = new ReaderTool(this); 54 | this.Clipboard = ClipboardHelper 55 | } 56 | 57 | unregisterAll() { 58 | unregister(this); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /tags/Abstract2Introduction.txt: -------------------------------------------------------------------------------- 1 | #摘要转综述[pos=1] 2 | 3 | 下面是一篇论文的摘要: 4 | 5 | ```js 6 | const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit 7 | let getSelection = () => { 8 | return ztoolkit.Reader.getSelectedText( 9 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID) 10 | ); 11 | } 12 | getSelection() 13 | ``` 14 | 15 | 16 | 现在我想引用它写一篇文献综述,请你帮我写几句话总结这篇论文的工作,作者没有告诉你,你可以用XX代替。我要中文的。要求50字左右。 17 | 18 | --- 19 | 20 | 使用场景: 选中PDF的摘要的时候 -------------------------------------------------------------------------------- /tags/AddTags.txt: -------------------------------------------------------------------------------- 1 | #🔭AddTags[position=9][color=#B7A7DB] 2 | 3 | 下面是我在Zotero里创建的一些嵌套标签,它们以#开头,中间用/连接: 4 | ```js 5 | Zotero.ZoteroGPT.views.messages = []; 6 | JSON.stringify(Zotero.ZoteroStyle.data.views.tagsUI.plainTags.slice(0, 20)) 7 | ``` 8 | --- 9 | 这是一篇文献的摘要: 10 | ```js 11 | ZoteroPane.getSelectedItems()[0].getField("abstractNote") 12 | ``` 13 | --- 14 | 15 | 请你帮我根据我已有的嵌套标签,分析出我该给这篇文献添加什么嵌套标签,请你推荐三个,并给我一段代码,这段代码将在Zotero里执行,下面是示例代码: 16 | ```js 17 | const tags = ["#tag1/tag2/tag3", "#tag1/tag2/tag3", "#tag1/tag2/tag3"] 18 | item = ZoteroPane.getSelectedItems()[0] 19 | tags.forEach(tag=>{ 20 | item.addTag(tag) 21 | }) 22 | await item.saveTx() 23 | ``` 24 | --- 25 | 你只需要回答我代码,除了代码你不需要进行任何文字描述,你给出代码是: -------------------------------------------------------------------------------- /tags/AskAbstract.txt: -------------------------------------------------------------------------------- 1 | #摘要提问[pos=0] 2 | 3 | 下面是一篇论文的摘要: 4 | 5 | ```js 6 | const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit 7 | let getSelection = () => { 8 | return ztoolkit.Reader.getSelectedText( 9 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID) 10 | ); 11 | } 12 | getSelection() 13 | ``` -------------------------------------------------------------------------------- /tags/AskClipboard.txt: -------------------------------------------------------------------------------- 1 | #📄AskClipboard[position=9][color=#dc4334] 2 | 3 | Read this: 4 | 5 | ```js 6 | 7 | Zotero.ZoteroGPT.utils.getClipboardText() 8 | 9 | ``` 10 | 11 | --- 12 | 13 | please answer this question based on above content (use 简体中文): 14 | ```js 15 | Zotero.ZoteroGPT.views.inputContainer.querySelector("input").value 16 | ``` -------------------------------------------------------------------------------- /tags/AskExperimentDetails.txt: -------------------------------------------------------------------------------- 1 | #总结实验方法[pos=9] 2 | 3 | 请用子弹列表的形式提取该段落的信息,包括,被试数量,实验设计(如, 2(Gender: male vs female) X 2(Matching Condition: matching or mismatching)),实验流程(如,被试首先观看刺激,然后进行反应,最后呈现反馈给被试)。务必使用中文回答。 4 | 下面是论文的方法部分: 5 | ```js 6 | const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit 7 | let getSelection = () => { 8 | return ztoolkit.Reader.getSelectedText( 9 | Zotero.Reader.getByTabID(Zotero_Tabs.selectedID) 10 | ); 11 | } 12 | ztoolkit.log(getSelection()) 13 | getSelection() 14 | ``` 15 | 16 | --- 17 | 18 | 选中PDF文字时候 -------------------------------------------------------------------------------- /tags/AskJournal.txt: -------------------------------------------------------------------------------- 1 | #期刊介绍[pos=9] 2 | 3 | 介绍一下下面这个期刊: 4 | ```js 5 | ZoteroPane.getSelectedItems()[0].getField("publicationTitle") 6 | ``` 7 | 8 | --- 9 | 10 | 应用场景: 选中主界面条目时候 11 | -------------------------------------------------------------------------------- /tags/AskPDF.txt: -------------------------------------------------------------------------------- 1 | #🪐AskPDF[pos=0][color=#009FBD] 2 | 3 | You are a helpful assistant. Context information is below. 4 | 5 | --- 6 | ```js 7 | window.gptInputString = Zotero.ZoteroGPT.views.inputContainer.querySelector("input").value 8 | Zotero.ZoteroGPT.views.messages = []; 9 | 10 | Zotero.ZoteroGPT.utils.getRelatedText( 11 | window.gptInputString 12 | ) 13 | 14 | ``` 15 | --- 16 | 17 | Current date: 18 | ```js 19 | String(new Date()) 20 | ``` 21 | Using the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. 22 | 23 | Answer the question: 24 | ```js 25 | window.gptInputString 26 | ``` 27 | 28 | Reply in 简体中文 29 | -------------------------------------------------------------------------------- /tags/Readme.md: -------------------------------------------------------------------------------- 1 | ## About Tag 2 | 3 | You can long click on the tag below to see its internal pseudo-code. 4 | You can type #xxx and enter to create a tag and save it with Ctrl + S, during which you can execute it with Ctrl + R. 5 | You can right-click and long-click a tag to delete it. 6 | 7 | ## About Output Text 8 | You can double click on this text to copy GPT's answer. 9 | You can long press me without releasing, then move me to a suitable position before releasing. 10 | 11 | ## About Input Text 12 | You can type the question in my header, enter and ask me a question. 13 | You can exit me by pressing Esc above my head and wake me up by pressing meta(ctrl) + enter in the Zotero window. 14 | -------------------------------------------------------------------------------- /tags/SearchItems.txt: -------------------------------------------------------------------------------- 1 | #🔍SearchItems[position=9][color=#ED5629] 2 | 3 | 现在你是一个数据库系统,下面是一些JSON信息,每个JSON对应Zotero一篇文献: 4 | 5 | --- 6 | 7 | ```js 8 | window.gptInputString = Zotero.ZoteroGPT.views.inputContainer.querySelector("input").value 9 | Zotero.ZoteroGPT.views.messages = []; 10 | 11 | Zotero.ZoteroGPT.utils.getRelatedText( 12 | window.gptInputString 13 | ) 14 | 15 | ``` 16 | 17 | --- 18 | 19 | 我现在在寻找一篇文献,它很可能就在我上面给你的文献之中。下面是对我想找的文献的描述: 20 | ```js 21 | window.gptInputString 22 | ``` 23 | 24 | 请你回答最有可能是哪几篇文献,请同时给出最可能的一篇。 25 | 26 | Reply in 简体中文 -------------------------------------------------------------------------------- /tags/Translate.txt: -------------------------------------------------------------------------------- 1 | #🎈Translate[pos=1][c=#21a2f1] 2 | 3 | translate these from english to 简体中文: 4 | ```js 5 | Zotero.ZoteroGPT.utils.getPDFSelection() 6 | ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "module": "commonjs", 5 | "target": "ES2016", 6 | "resolveJsonModule": true, 7 | "skipLibCheck": true, 8 | "strict": true 9 | }, 10 | "include": ["src", "typing", "node_modules/zotero-types"], 11 | "exclude": ["builds", "addon"] 12 | } 13 | -------------------------------------------------------------------------------- /typing/global.d.ts: -------------------------------------------------------------------------------- 1 | declare const _globalThis: { 2 | [key: string]: any; 3 | Zotero: _ZoteroTypes.Zotero; 4 | ZoteroPane: _ZoteroTypes.ZoteroPane; 5 | Zotero_Tabs: typeof Zotero_Tabs; 6 | window: Window; 7 | document: Document; 8 | ztoolkit: typeof ztoolkit; 9 | addon: typeof addon; 10 | }; 11 | 12 | declare const ztoolkit: import("zotero-plugin-toolkit").ZoteroToolkit; 13 | 14 | declare const rootURI: string; 15 | 16 | declare const addon: import("../src/addon").default; 17 | 18 | declare const __env__: "production" | "development"; 19 | 20 | 21 | declare type PDFLine = { 22 | x: number, 23 | _x?: number, 24 | y: number, 25 | text: string, 26 | height: number, 27 | _height: number[], 28 | width: number, 29 | url?: string, 30 | } 31 | 32 | declare type PDFItem = { 33 | chars: { 34 | baseline: number; 35 | c: string; 36 | fontName: string; 37 | fontSize: number; 38 | rect: number[]; 39 | rotation: number; 40 | }[]; 41 | dir: string; 42 | fontName: string; 43 | height: number; 44 | str: string; 45 | transform: number[]; 46 | width: number; 47 | url?: string; 48 | } 49 | 50 | declare type PDFAnnotation = { 51 | rect: number[]; 52 | url?: string; 53 | unsafeUrl?: string; 54 | } 55 | 56 | interface Rect { 57 | bottom: number; 58 | height: number; 59 | left: number; 60 | right: number; 61 | top: number; 62 | width: number; 63 | x: number; 64 | y: number; 65 | } 66 | interface Tag { tag: string; color: string; position: number, trigger: string, text: string } -------------------------------------------------------------------------------- /typings/prefs.d.ts: -------------------------------------------------------------------------------- 1 | // Generated by zotero-plugin-scaffold 2 | /* prettier-ignore */ 3 | /* eslint-disable */ 4 | // @ts-nocheck 5 | 6 | // prettier-ignore 7 | declare namespace _ZoteroTypes { 8 | interface Prefs { 9 | PluginPrefsMap: { 10 | "extensions.zotero.enable": boolean; 11 | "extensions.zotero.tags": string; 12 | "extensions.zotero.languages": string; 13 | "extensions.zotero.papersgptState": string; 14 | "extensions.zotero.startLocalServer": boolean; 15 | "extensions.zotero.email": string; 16 | "extensions.zotero.token": string; 17 | "extensions.zotero.isLicenseActivated": boolean; 18 | "extensions.zotero.grade": string; 19 | "extensions.zotero.supportedLLMs": string; 20 | "extensions.zotero.usingLanguage": string; 21 | "extensions.zotero.usingPublisher": string; 22 | "extensions.zotero.usingModel": string; 23 | "extensions.zotero.usingAPIKEY": string; 24 | "extensions.zotero.usingAPIURL": string; 25 | "extensions.zotero.openaiApiKey": string; 26 | "extensions.zotero.geminiApiKey": string; 27 | "extensions.zotero.claudeApiKey": string; 28 | "extensions.zotero.customModelApiUrl": string; 29 | "extensions.zotero.customModelApiKey": string; 30 | "extensions.zotero.customModelApiModel": string; 31 | "extensions.zotero.secretKey": string; 32 | "extensions.zotero.model": string; 33 | "extensions.zotero.api": string; 34 | "extensions.zotero.prompts": string; 35 | "extensions.zotero.temperature": string; 36 | "extensions.zotero.deltaTime": number; 37 | "extensions.zotero.width": string; 38 | "extensions.zotero.tagsMore": string; 39 | "extensions.zotero.chatNumber": number; 40 | "extensions.zotero.relatedNumber": number; 41 | "extensions.zotero.embeddingBatchNum": number; 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /update-template.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "__addonID__": { 4 | "updates": [ 5 | { 6 | "version": "__buildVersion__", 7 | "update_link": "__releasepage__", 8 | "applications": { 9 | "gecko": { 10 | "strict_min_version": "60.0" 11 | } 12 | } 13 | }, 14 | { 15 | "version": "__buildVersion__", 16 | "update_link": "__releasepage__", 17 | "applications": { 18 | "zotero": { 19 | "strict_min_version": "6.999" 20 | } 21 | } 22 | } 23 | ] 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /update-template.rdf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | __buildVersion__ 9 | 10 | 11 | zotero@chnm.gmu.edu 12 | 6.999 13 | * 14 | __releasepage__ 15 | 16 | 17 | 18 | 19 | juris-m@juris-m.github.io 20 | 6.999 21 | * 22 | __releasepage__ 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /update.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "papersgpt@papersgpt.com": { 4 | "updates": [ 5 | { 6 | "version": "0.0.8", 7 | "update_link": "", 8 | "applications": { 9 | "gecko": { 10 | "strict_min_version": "60.0" 11 | } 12 | } 13 | }, 14 | { 15 | "version": "0.0.8", 16 | "update_link": "", 17 | "applications": { 18 | "zotero": { 19 | "strict_min_version": "6.999" 20 | } 21 | } 22 | } 23 | ] 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /update.rdf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 0.0.8 9 | 10 | 11 | zotero@chnm.gmu.edu 12 | 6.999 13 | * 14 | 15 | 16 | 17 | 18 | 19 | juris-m@juris-m.github.io 20 | 6.999 21 | * 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /zotero-plugin.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "zotero-plugin-scaffold"; 2 | import pkg from "./package.json"; 3 | 4 | export default defineConfig({ 5 | source: ["src", "builds/addon"], 6 | dist: ".scaffold/build", 7 | name: pkg.config.addonName, 8 | id: pkg.config.addonID, 9 | namespace: pkg.config.addonRef, 10 | 11 | build: { 12 | assets: ["builds/addon/**/*.*"], 13 | define: { 14 | ...pkg.config, 15 | author: pkg.author, 16 | description: pkg.description, 17 | homepage: pkg.homepage, 18 | buildVersion: pkg.version, 19 | buildTime: "{{buildTime}}", 20 | __env__: `"production"`, 21 | }, 22 | prefs: { 23 | prefix: pkg.config.addonRef, 24 | }, 25 | esbuildOptions: [ 26 | { 27 | entryPoints: ["src/index.ts"], 28 | define: { 29 | __env__: `"${process.env.NODE_ENV}"`, 30 | }, 31 | bundle: true, 32 | target: "firefox115", 33 | outfile: `.scaffold/build/addon/content/scripts/${pkg.config.addonRef}.js`, 34 | }, 35 | ], 36 | }, 37 | }); --------------------------------------------------------------------------------