├── .github
└── ISSUE_TEMPLATE
│ ├── bug-report---错误报告.md
│ ├── feature-request---功能-建议提出.md
│ └── other-issue---其他问题.md
├── LICENSE
├── Lib
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-312.pyc
│ ├── compose.cpython-312.pyc
│ ├── config.cpython-312.pyc
│ ├── data_process.cpython-312.pyc
│ ├── direct_mode.cpython-312.pyc
│ ├── extract.cpython-312.pyc
│ ├── output.cpython-312.pyc
│ ├── playwright_process.cpython-312.pyc
│ └── print_redirector.cpython-312.pyc
├── compose.py
├── config.py
├── continue_trans.py
├── data_process.py
├── deeplx_darwin_amd64
├── deeplx_darwin_arm64
├── deeplx_windows_amd64.exe
├── deeplxfile.ico
├── direct_mode.py
├── extract.py
├── llm_translate.py
├── output.py
├── playwright_process.py
├── test.py
└── webkit
│ └── PLACE_PLAYWRGHT_WEBKIT_HERE
├── README.md
├── README_translated.md
├── config.json
├── deeplxfile_gui.py
└── images
├── MacOS.png
├── deeplx_file_support.png
├── deeplxfile_quality.png
├── pdf_demo_animation.gif
├── pdf_translate.png
└── playwright.gif
/.github/ISSUE_TEMPLATE/bug-report---错误报告.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report / 错误报告
3 | about: Create a report to help us improve / 让我们改进这个项目!
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug这个Bug是啥?**
11 | A clear and concise description of what the bug is.
12 | 一个清晰的描述有助于我了解问题的重现
13 |
14 | **To Reproduce如何重新这个Bug?**
15 |
16 |
17 | **Expected behavior预期的行为?**
18 | A clear and concise description of what you expected to happen.
19 |
20 |
21 | **Screenshots截图**
22 | If applicable, add screenshots to help explain your problem.
23 | 有需要也可以贴上截图
24 |
25 | **Additional context其他**
26 | Add any other context about the problem here.
27 | 其他项:您想要补充的内容/软件版本/运行环境等
28 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature-request---功能-建议提出.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request / 功能、建议提出
3 | about: Suggest an idea for this project / 您有什么想法都可以在这里写!
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/other-issue---其他问题.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Other issue / 其他问题
3 | about: blank issue
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__init__.py
--------------------------------------------------------------------------------
/Lib/__pycache__/__init__.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/__init__.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/compose.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/compose.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/config.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/config.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/data_process.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/data_process.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/direct_mode.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/direct_mode.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/extract.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/extract.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/output.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/output.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/playwright_process.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/playwright_process.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/__pycache__/print_redirector.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/__pycache__/print_redirector.cpython-312.pyc
--------------------------------------------------------------------------------
/Lib/compose.py:
--------------------------------------------------------------------------------
1 | import os
2 | import zipfile
3 | from lxml import etree as ET
4 | import tempfile
5 | from Lib.config import config
6 | #from config import config
7 |
8 | def read_strings_from_file(file_path):
9 | with open(file_path, 'r', encoding='utf-8') as f:
10 | return [line.strip() for line in f.readlines()]
11 |
12 | def update_shared_strings_in_xlsx(file_path, strings, enhance_mode):
13 | with tempfile.TemporaryDirectory() as tmpdirname:
14 | # 解压缩 .xlsx 文件
15 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
16 | zip_ref.extractall(tmpdirname)
17 |
18 | # 获取文件路径
19 | shared_strings_path = os.path.join(tmpdirname, 'xl', 'sharedStrings.xml')
20 | workbook_path = os.path.join(tmpdirname, 'xl', 'workbook.xml')
21 |
22 | if not os.path.exists(shared_strings_path) or not os.path.exists(workbook_path):
23 | print("共享字符串文件或 workbook.xml 文件不存在, 请检查 Excel 文档是否有误")
24 | return
25 |
26 | # 解析 workbook.xml 文件中的 sheet 标签
27 | if enhance_mode:
28 | tree = ET.parse(workbook_path)
29 | root = tree.getroot()
30 | sheet_elements = list(root.iter('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet'))
31 |
32 | # 检查 strings 数量是否足够
33 | if len(strings) < len(sheet_elements):
34 | print(f"警告: 提供的字符串数量 ({len(strings)}) 不足以替换 workbook.xml 中的 sheet 标签数量 ({len(sheet_elements)})。")
35 | return
36 |
37 | # 替换 sheet 标签名称
38 | for sheet_element, new_sheet_name in zip(sheet_elements, strings[:len(sheet_elements)]):
39 | sheet_element.set('name', new_sheet_name)
40 |
41 | # 保存修改后的 workbook.xml
42 | tree.write(workbook_path, xml_declaration=True, encoding='UTF-8', standalone=True)
43 |
44 | # 更新 strings 列表,去除已用于 sheet 标签的内容
45 | strings = strings[len(sheet_elements):]
46 |
47 | # 解析 sharedStrings.xml 文件
48 | parser = ET.XMLParser(remove_blank_text=False)
49 | tree = ET.parse(shared_strings_path, parser)
50 | root = tree.getroot()
51 |
52 | t_elements = list(root.iter('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t'))
53 |
54 | if len(strings) != len(t_elements):
55 | print(f"警告: 提供的字符串数量 ({len(strings)}) 与现有 标签数量 ({len(t_elements)}) 不匹配。")
56 | else:
57 | print("已匹配所有标签")
58 |
59 | # 更新 sharedStrings.xml 中的 标签
60 | for t_element, new_string in zip(t_elements, strings):
61 | original_text = t_element.text
62 | if original_text is not None and '\n' in original_text:
63 | new_string = new_string.replace(' ', '')
64 | lines = original_text.splitlines()
65 | if config.get("save_original", False):
66 | t_element.text = lines[0] + new_string
67 | if len(lines) > 1:
68 | t_element.text += '\n' + '\n'.join(lines[1:])
69 | else:
70 | t_element.text = new_string
71 | if len(lines) > 1:
72 | t_element.text += '\n' + '\n'.join(lines[1:])
73 | else:
74 | if config.get("save_original", False):
75 | t_element.text = (original_text or '') + new_string
76 | else:
77 | t_element.text = new_string
78 |
79 | # 将修改后的 sharedStrings.xml 文件写回
80 | tree.write(shared_strings_path, xml_declaration=True, encoding='UTF-8', pretty_print=False, standalone=True)
81 |
82 | new_xlsx_path = file_path.replace('.xlsx', '_translated.xlsx')
83 |
84 | # 如果文件已存在,则删除
85 | if os.path.exists(new_xlsx_path):
86 | os.remove(new_xlsx_path)
87 |
88 | # 将修改后的文件压缩回 .xlsx
89 | with zipfile.ZipFile(new_xlsx_path, 'w') as zip_ref:
90 | for foldername, subfolders, filenames in os.walk(tmpdirname):
91 | for filename in filenames:
92 | file_path = os.path.join(foldername, filename)
93 | arcname = os.path.relpath(file_path, tmpdirname)
94 | zip_ref.write(file_path, arcname)
95 |
96 |
97 | def update_shared_strings_in_docx(file_path, strings):
98 | with tempfile.TemporaryDirectory() as tmpdirname:
99 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
100 | zip_ref.extractall(tmpdirname)
101 |
102 | shared_strings_path = os.path.join(tmpdirname, 'word', 'document.xml')
103 |
104 | if not os.path.exists(shared_strings_path):
105 | print("错误:document.xml 文件不存在。")
106 | return
107 |
108 | parser = ET.XMLParser(remove_blank_text=True)
109 | tree = ET.parse(shared_strings_path, parser)
110 | root = tree.getroot()
111 |
112 | namespaces = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
113 | t_elements = root.xpath('//w:t', namespaces=namespaces)
114 |
115 | if len(strings) != len(t_elements):
116 | print(f"警告: 提供的字符串数量 ({len(strings)}) 与现有 标签数量 ({len(t_elements)}) 不匹配。")
117 |
118 | for t_element, new_string in zip(t_elements, strings):
119 | if config.get("save_original", False):
120 | t_element.text = (t_element.text or '') + new_string
121 | else:
122 | t_element.text = new_string
123 |
124 | tree.write(shared_strings_path, xml_declaration=True, encoding='UTF-8', pretty_print=True)
125 |
126 | new_docx_path = file_path.replace('.docx', '_translated.docx')
127 |
128 | if os.path.exists(new_docx_path):
129 | os.remove(new_docx_path)
130 |
131 | with zipfile.ZipFile(new_docx_path, 'w') as zip_ref:
132 | for foldername, subfolders, filenames in os.walk(tmpdirname):
133 | for filename in filenames:
134 | file_path = os.path.join(foldername, filename)
135 | arcname = os.path.relpath(file_path, tmpdirname)
136 | zip_ref.write(file_path, arcname)
137 |
138 | def update_shared_strings_in_pptx(file_path, strings):
139 | with tempfile.TemporaryDirectory() as tmpdirname:
140 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
141 | zip_ref.extractall(tmpdirname)
142 |
143 | slides_dir = os.path.join(tmpdirname, 'ppt', 'slides')
144 |
145 | if not os.path.exists(slides_dir):
146 | print("错误:slides 目录不存在。")
147 | return
148 |
149 | parser = ET.XMLParser(remove_blank_text=True)
150 | slide_files = sorted([f for f in os.listdir(slides_dir) if f.endswith('.xml')])
151 |
152 | string_index = 0
153 |
154 | for slide_file in slide_files:
155 | slide_path = os.path.join(slides_dir, slide_file)
156 | tree = ET.parse(slide_path, parser)
157 | root = tree.getroot()
158 |
159 | namespaces = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'}
160 | t_elements = root.xpath('//a:t', namespaces=namespaces)
161 |
162 | for t_element in t_elements:
163 | if string_index < len(strings):
164 | if config.get("save_original", False):
165 | t_element.text = (t_element.text or '') + strings[string_index]
166 | else:
167 | t_element.text = strings[string_index]
168 | string_index += 1
169 | else:
170 | break
171 |
172 | # 更新后的内容写回幻灯片文件
173 | tree.write(slide_path, xml_declaration=True, encoding='UTF-8', pretty_print=True)
174 |
175 | if string_index < len(strings):
176 | print(f"警告: 提供的字符串数量 ({len(strings)}) 超过了现有 标签数量 ({string_index}),未能完全替换。")
177 |
178 | new_pptx_path = file_path.replace('.pptx', '_translated.pptx')
179 |
180 | if os.path.exists(new_pptx_path):
181 | os.remove(new_pptx_path)
182 |
183 | with zipfile.ZipFile(new_pptx_path, 'w') as zip_ref:
184 | for foldername, subfolders, filenames in os.walk(tmpdirname):
185 | for filename in filenames:
186 | file_path = os.path.join(foldername, filename)
187 | arcname = os.path.relpath(file_path, tmpdirname)
188 | zip_ref.write(file_path, arcname)
189 |
190 | print(f"更新后的文件已保存为: {new_pptx_path}")
191 |
192 | def compose_file(file_type, input_path, enhance_mode):
193 | result_file_path = './out/translated_result.txt'
194 | #result_file_path = './translated_result.txt'
195 | # 读取文本文件内容
196 | result_strings = read_strings_from_file(result_file_path)
197 |
198 | if file_type == "Excel":
199 | # 更新 Excel 文件中的 sharedStrings.xml
200 | update_shared_strings_in_xlsx(input_path, result_strings, enhance_mode)
201 | print(f"生成翻译后的电子表格...")
202 | elif file_type == "Word":
203 | update_shared_strings_in_docx(input_path, result_strings)
204 | print(f"生成翻译后的word文档...")
205 | elif file_type == "PowerPoint":
206 | update_shared_strings_in_pptx(input_path, result_strings)
207 | print(f"生成翻译后的ppt文档...")
208 | elif file_type == "PDF":
209 | update_shared_strings_in_docx(input_path, result_strings)
210 | print(f"生成翻译后的PDF文档...")
211 | elif file_type == "TEXT":
212 | base_name, ext = os.path.splitext(input_path)
213 | output_path = base_name + '_translated' + ext
214 | with open(output_path, 'w', encoding='utf-8') as f:
215 | for string in result_strings:
216 | f.write(string + '\n')
217 | print(f"生成翻译后的txt文档")
218 | elif file_type == "Markdown":
219 | base_name, ext = os.path.splitext(input_path)
220 | output_path = base_name + '_translated' + ext
221 | with open(output_path, 'w', encoding='utf-8') as f:
222 | for string in result_strings:
223 | f.write(string + '\n')
224 | print(f"生成翻译后的Markdown文档")
225 |
226 |
227 | ##For test Use
228 | #compose_file("Excel", "./excel_test.xlsx", True)
229 |
230 |
231 |
--------------------------------------------------------------------------------
/Lib/config.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 |
4 | # 定义默认配置
5 | default_config = {
6 | "save_original": False, #保留原文件值
7 | "version": "0.5.11",
8 | "dev": False,
9 | "i18n": "ZH",
10 | "playwright_headless": False,
11 | "playwright_path": "./Lib/Webkit/Playwright.exe", # Mac "./Lib/Webkit/pw_run.sh", windows "./Lib/Webkit/Playwright.exe"
12 | "browser_login": False,
13 | "force_lang_select": False,
14 | "translation_mode": "playwright",
15 | "disable_user_profile": False,
16 | "enhance_mode": False,
17 | "deepl_token": "",
18 | "deeplx_core_version": "1.0.4",
19 | "deeplx_server": "",
20 | "llm_api_base": "https://api.openai.com/v1",
21 | "llm_api_key": "",
22 | "llm_model": "gpt-4o",
23 | "llm_prompt": "",
24 | "llm_max_token":"4096"
25 | }
26 |
27 | # 定义配置文件的路径
28 | config_path = './config.json'
29 |
30 | def load_config():
31 | """加载配置,如果config.json不存在则创建并使用默认配置。"""
32 | if not os.path.exists(config_path):
33 | # 如果不存在,创建config.json并写入默认配置
34 | with open(config_path, 'w', encoding='utf-8') as config_file:
35 | json.dump(default_config, config_file, indent=4)
36 | return default_config
37 | else:
38 | # 如果存在,加载config.json并更新默认配置
39 | with open(config_path, 'r', encoding='utf-8') as config_file:
40 | user_config = json.load(config_file)
41 | # 更新默认配置
42 | return {**default_config, **user_config}
43 |
44 | def save_config(config):
45 | """将配置保存到config.json中"""
46 | with open(config_path, 'w', encoding='utf-8') as config_file:
47 | json.dump(config, config_file, indent=4)
48 |
49 | # 直接加载配置供外部使用
50 | config = load_config()
51 |
--------------------------------------------------------------------------------
/Lib/continue_trans.py:
--------------------------------------------------------------------------------
1 |
2 | translated_path = './out/translated_result.txt'
3 | text_extracted_path = './tmp/text_extracted.txt'
4 | continue_path = './tmp/continue.txt'
5 |
6 | def move_lines():
7 |
8 |
9 | # Read lines from translated_result.txt
10 | with open(translated_path, 'r', encoding='utf-8') as file:
11 | translated_lines = file.readlines()
12 | a = len(translated_lines)
13 |
14 | # Write the translated lines to continue.txt
15 | with open(continue_path, 'w', encoding='utf-8') as file:
16 | file.writelines(translated_lines)
17 |
18 | # Read lines from text_extracted.txt
19 | with open(text_extracted_path, 'r', encoding='utf-8') as file:
20 | text_extracted_lines = file.readlines()
21 |
22 | remaining_text_extracted_lines = text_extracted_lines[a:]
23 |
24 | # Write the remaining lines back to text_extracted.txt
25 | with open(text_extracted_path, 'w', encoding='utf-8') as file:
26 | file.writelines(remaining_text_extracted_lines)
27 |
28 |
29 | def prepend_to_translated_result():
30 |
31 | # Read lines from continue.txt
32 | with open(continue_path, 'r', encoding='utf-8') as file:
33 | continue_lines = file.readlines()
34 |
35 | # Read original lines from translated_result.txt
36 | with open(translated_path, 'r', encoding='utf-8') as file:
37 | translated_lines = file.readlines()
38 |
39 | # Prepend continue.txt content to translated_result.txt
40 | with open(translated_path, 'w', encoding='utf-8') as file:
41 | file.writelines(continue_lines + translated_lines)
42 |
--------------------------------------------------------------------------------
/Lib/data_process.py:
--------------------------------------------------------------------------------
1 | import httpx
2 | import json
3 | import os
4 | import time
5 | from Lib.config import config
6 | output_dir = './out'
7 | os.makedirs(output_dir, exist_ok=True)
8 |
9 | def count_words(line):
10 | # 统计一行中的词数,以空格分隔
11 | return len(line.split())
12 |
13 | def process_file(file_path, source_lang, target_lang, deepl_token, mode = 'w'):
14 | if deepl_token:
15 | print("deeplx方法:Pro模式,将会消耗token")
16 | deeplx_server = config.get("deeplx_server")
17 | if deeplx_server:
18 | deeplx_api = rf"http://{deeplx_server}/v1/translate?token={deepl_token}"
19 | else:
20 | deeplx_api = "http://127.0.0.1:1188/v1/translate?token={deepl_token}"
21 | else:
22 | print("deeplx方法:免费模式")
23 | deeplx_server = config.get("deeplx_server")
24 | if deeplx_server:
25 | deeplx_api = rf"http://{deeplx_server}/translate"
26 | else:
27 | deeplx_api = "http://127.0.0.1:1188/translate"
28 |
29 |
30 | with open(file_path, 'r', encoding='utf-8') as file:
31 | lines = file.readlines()
32 |
33 | total_word_count = 0
34 | strings_array = []
35 | current_string = []
36 |
37 | for i, line in enumerate(lines):
38 | line = line.strip() # 去掉行首尾的空白字符
39 | line_word_count = count_words(line)
40 | total_word_count += line_word_count
41 |
42 | current_string.append(line) # 添加当前行到当前字符串中
43 |
44 | if total_word_count > 1000:
45 | # 当前字符串超过500词,截断并保存
46 | strings_array.append('\n'.join(current_string))
47 | # 重置统计
48 | total_word_count = 0
49 | current_string = []
50 |
51 | # 添加最后一部分(如果有剩余)
52 | if current_string:
53 | strings_array.append('\n'.join(current_string))
54 | alternative_index = 0 # 用于命名 alternatives 文件
55 | with open('./out/translated_result.txt', mode, encoding='utf-8') as result_file:
56 | process_block_count = 1
57 | for s in strings_array:
58 | print(f"正在处理第{process_block_count}个块...")
59 | process_block_count = process_block_count + 1
60 | #json_array = str(s)
61 | data = {
62 | "text": s,
63 | "source_lang": source_lang,
64 | "target_lang": target_lang
65 | }
66 | post_data = json.dumps(data)
67 | #print(post_data)
68 |
69 | retry_count = 0
70 | max_retries = 2
71 | success = False
72 | timeout_value = 20.0 # 秒
73 | retry_interval = 5.0
74 | while retry_count < max_retries:
75 |
76 | try:
77 | print("正在向deepl服务器发送请求")
78 | # 发送POST请求并打印结果
79 | r = httpx.post(url=deeplx_api, data=post_data, timeout=timeout_value)
80 | print("正在等待回传结果...")
81 | response_data = r.json()
82 |
83 | # 检查 'data' 是否存在
84 | if 'data' in response_data:
85 | # 将返回的数据中的
标签替换回换行符
86 | translated_text = response_data['data']
87 | # 保存 data 内容到 translated_result.txt
88 | result_file.write(translated_text + '\n')
89 | result_file.flush()
90 | success = True
91 | #print(f"收到数据\n {translated_text}")
92 |
93 | # 如果存在 alternatives,保存每个替代到不同的文件
94 | if "alternatives" in response_data and response_data["alternatives"] is not None:
95 | #if False: #暂时不执行这个
96 | alternatives = response_data["alternatives"]
97 | #print(alternatives)
98 | for alternative in alternatives:
99 | with open(f'./out/alternatives({alternative_index}).txt', mode, encoding='utf-8') as alt_file:
100 | alt_file.write(alternative + '\n')
101 | alternative_index += 1
102 | break # 成功处理后退出重试循环
103 |
104 | else:
105 | raise ValueError("未找到返回数据,可能是因为请求过于频繁,程序将会尝试重试\n 这可能是deeplx内核的问题,可以重启程序然后尝试兼容性更强的playwright模式")
106 |
107 | except (httpx.RequestError, ValueError) as exc:
108 | retry_count += 1
109 | if retry_count < max_retries:
110 | print(f"发生错误: {exc}. 程序将在{retry_interval} 秒后尝试... ({retry_count}/{max_retries})\n你可能需要切换到兼容性更强的playwright模式")
111 | time.sleep(retry_interval)
112 | else:
113 | print(f"已达到最大尝试值: {max_retries} ,翻译失败,正在尝试下一区块翻译")
114 |
115 | if not success:
116 | error_lines = s.splitlines()
117 | error_messages = [f"Error: {error_line}" for error_line in error_lines]
118 | error_message = "\n".join(error_messages) + "\n"
119 | result_file.write(error_message)
120 | print(f"已达到最大尝试值: {max_retries} ,翻译失败,正在尝试下一区块翻译")
121 |
122 |
123 |
--------------------------------------------------------------------------------
/Lib/deeplx_darwin_amd64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/deeplx_darwin_amd64
--------------------------------------------------------------------------------
/Lib/deeplx_darwin_arm64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/deeplx_darwin_arm64
--------------------------------------------------------------------------------
/Lib/deeplx_windows_amd64.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/deeplx_windows_amd64.exe
--------------------------------------------------------------------------------
/Lib/deeplxfile.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/deeplxfile.ico
--------------------------------------------------------------------------------
/Lib/direct_mode.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import time
3 | import os
4 | output_dir = './out'
5 | os.makedirs(output_dir, exist_ok=True)
6 |
7 | def count_words(line):
8 | # 统计一行中的词数,以空格分隔
9 | return len(line.split())
10 |
11 | def process_file(file_path, source_lang, target_lang):
12 | with open(file_path, 'r', encoding='utf-8') as file:
13 | lines = file.readlines()
14 |
15 | total_word_count = 0
16 | strings_array = []
17 | current_string = []
18 |
19 | for i, line in enumerate(lines):
20 | line = line.strip() # 去掉行首尾的空白字符
21 | line_word_count = count_words(line)
22 | total_word_count += line_word_count
23 |
24 | current_string.append(line) # 添加当前行到当前字符串中
25 |
26 | if total_word_count > 1000:
27 | # 当前字符串超过500词,截断并保存
28 | strings_array.append('\n'.join(current_string))
29 | # 重置统计
30 | total_word_count = 0
31 | current_string = []
32 |
33 | # 添加最后一部分(如果有剩余)
34 | if current_string:
35 | strings_array.append('\n'.join(current_string))
36 | alternative_index = 0 # 用于命名 alternatives 文件
37 | #source_lang = "EN"
38 | with open('./out/translated_result.txt', 'w', encoding='utf-8') as result_file:
39 | process_block_count = 1
40 | for s in strings_array:
41 | print(f"正在处理第{process_block_count}个块...")
42 | process_block_count = process_block_count + 1
43 | s_lines = s.splitlines() # 将多行字符串分割成行列表
44 | payload_texts = [{"text": line, "requestAlternatives": 0, "source_lang": source_lang}
45 | for line in enumerate(s_lines)]
46 | #print(payload_texts)
47 | ## 构造请求头
48 | url = "https://www2.deepl.com/jsonrpc"
49 | headers = {
50 | "Content-Type": "application/json",
51 | "User-Agent": "Mozilla/5.0"
52 | }
53 | payload = {
54 | "jsonrpc": "2.0",
55 | "method": "LMT_handle_texts",
56 | "params": {
57 | "texts": payload_texts,
58 | "lang": {
59 | "source_lang": source_lang, # 指定源语言
60 | "target_lang": target_lang
61 | },
62 | "priority": 1,
63 | "commonJobParams": {},
64 | "timestamp": int(time.time() * 1000)
65 | }
66 | }
67 |
68 |
69 | max_retries = 5
70 | retry_count = 0
71 | success = False
72 |
73 | while retry_count < max_retries and not success:
74 | try:
75 | response = requests.post(url, json=payload, headers=headers, timeout=30)
76 | print("正在等待返回结果")
77 | if response.status_code == 200:
78 | result_origin = response.json()
79 | #print(f"收到返回值\n{result_origin}\n")
80 |
81 | # 处理所有结果并去掉 index
82 | for item in result_origin['result']['texts']:
83 | # 去掉前面的 index(假设格式始终是 "index: 内容")
84 | text = item['text']
85 | result_file.write(text + '\n')
86 |
87 | success = True
88 |
89 | else:
90 | raise ValueError("未找到返回数据,可能是因为请求过于频繁,程序将会尝试重试")
91 |
92 | except (requests.exceptions.RequestException, ValueError) as exc:
93 | retry_count += 1
94 | if retry_count < max_retries:
95 | print(f"Error occurred: {exc}. Retrying in 10 seconds... ({retry_count}/{max_retries})")
96 | time.sleep(10)
97 | else:
98 | print(f"Failed after {max_retries} retries. Moving on to the next string.")
99 |
100 | if not success:
101 | error_lines = s.splitlines()
102 | error_messages = [f"Error: {error_line}" for error_line in error_lines]
103 | error_message = "\n".join(error_messages) + "\n"
104 | result_file.write(error_message)
105 | print(f"Failed after {max_retries} retries. Moving on to the next string.")
--------------------------------------------------------------------------------
/Lib/extract.py:
--------------------------------------------------------------------------------
1 | """
2 | Replacing Newline Characters: Within the extract_strings_from_xlsx function,
3 | any newline characters within the text of each tag are replaced with a space.
4 | This ensures that each tag's content is treated as a single line when writing to the output file.
5 |
6 | Handling Empty Tags: The code includes a check to ensure that if a tag is empty (None),
7 | it does not cause an error.
8 |
9 | """
10 |
11 | import os
12 | import zipfile
13 | import tempfile
14 | import socket
15 | import json
16 | from lxml import etree as ET
17 | from tkinter import filedialog
18 |
19 | tmp_dir = './tmp'
20 | input_path = ""
21 | file_type = ""
22 | process_cancelled = bool()
23 | if not os.path.exists(tmp_dir):
24 | os.makedirs(tmp_dir)
25 |
26 | def extract_strings_from_xlsx(file_path, enhance_mode):
27 | # 创建临时目录
28 | with tempfile.TemporaryDirectory() as tmpdirname:
29 | # 解压缩 .xlsx 文件
30 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
31 | zip_ref.extractall(tmpdirname)
32 |
33 | # 存储字符串
34 | strings = []
35 |
36 | if enhance_mode:
37 | # 解析 workbook.xml 文件
38 | workbook_path = os.path.join(tmpdirname, 'xl', 'workbook.xml')
39 | if not os.path.exists(workbook_path):
40 | print("workbook.xml 文件不存在。")
41 | return
42 | tree = ET.parse(workbook_path)
43 | root = tree.getroot()
44 |
45 | for sheet in root.iter('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet'):
46 | sheet_name = sheet.get('name', '')
47 | if sheet_name:
48 | strings.append(sheet_name)
49 |
50 | # 读取 sharedStrings.xml 文件
51 | shared_strings_path = os.path.join(tmpdirname, 'xl', 'sharedStrings.xml')
52 | if not os.path.exists(shared_strings_path):
53 | print("sharedStrings.xml 文件不存在。")
54 | return []
55 | tree = ET.parse(shared_strings_path)
56 | root = tree.getroot()
57 | # 查找所有 标签
58 | for t in root.iter('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t'):
59 | # 将所有换行符替换为单个空格,确保每个 标签的内容是一行
60 | text_content = t.text.replace('\n', ' ') if t.text else ''
61 | strings.append(text_content)
62 |
63 | return strings
64 |
65 |
66 | def extract_strings_from_docx(file_path):
67 | with tempfile.TemporaryDirectory() as tmpdirname:
68 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
69 | zip_ref.extractall(tmpdirname)
70 |
71 | document_path = os.path.join(tmpdirname, 'word', 'document.xml')
72 |
73 | if not os.path.exists(document_path):
74 | print("错误:document.xml 文件不存在,请确认是合法的word文档。")
75 | return []
76 |
77 | tree = ET.parse(document_path)
78 | root = tree.getroot()
79 |
80 | strings = []
81 |
82 | for t in root.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t'):
83 | text_content = t.text.replace('\n', ' ') if t.text else ''
84 | strings.append(text_content)
85 |
86 | return strings
87 |
88 | def extract_strings_from_pptx(file_path):
89 | with tempfile.TemporaryDirectory() as tmpdirname:
90 | with zipfile.ZipFile(file_path, 'r') as zip_ref:
91 | zip_ref.extractall(tmpdirname)
92 |
93 | slides_dir = os.path.join(tmpdirname, 'ppt', 'slides')
94 |
95 | if not os.path.exists(slides_dir):
96 | print("错误:slides 目录不存在,请确认是合法的 PowerPoint 文档。")
97 | return []
98 |
99 | strings = []
100 |
101 | slide_files = sorted([f for f in os.listdir(slides_dir) if f.endswith('.xml')])
102 |
103 | for slide_file in slide_files:
104 | if slide_file.endswith('.xml'):
105 | slide_path = os.path.join(slides_dir, slide_file)
106 | print(f"正在处理{slide_file}")
107 | tree = ET.parse(slide_path)
108 | root = tree.getroot()
109 |
110 | for t in root.iter('{http://schemas.openxmlformats.org/drawingml/2006/main}t'):
111 | text_content = t.text.replace('\n', ' ') if t.text else ''
112 | strings.append(text_content)
113 |
114 | return strings
115 |
116 | def requests_docx(message, docx_path):
117 | try:
118 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
119 | client_socket.connect(('localhost', 9999))
120 |
121 | # 发送消息到服务器
122 | client_socket.send(message.encode('utf-8'))
123 | print(f"Sent requests to server")
124 |
125 | # 接收服务器的响应
126 | response = client_socket.recv(1024).decode('utf-8')
127 | print(f"Received from server..")
128 |
129 | # 调用docx处理流程
130 | strings = extract_strings_from_docx(docx_path)
131 |
132 | except socket.error as e:
133 | raise Exception(f"Socket error: {e}\n请检查PDF服务是否运行\n 如果未下载请前往下载\nhttps://github.com/infrost/pdf2docxserver/releases/")
134 | strings = ""
135 | except Exception as e:
136 | strings = ""
137 | raise Exception(f"An unexpected error occurred: {e}")
138 | finally:
139 | client_socket.close()
140 | return strings
141 |
142 |
143 |
144 | def write_strings_to_file(strings, output_file):
145 | with open(output_file, 'w', encoding='utf-8') as f:
146 | for string in strings:
147 | f.write(f"{string}\n")
148 |
149 |
150 | def extract_file(enhance_mode):
151 | global process_cancelled
152 | # 打开文件选择对话框
153 | file_path = filedialog.askopenfilename(
154 | title='选择一个文件,目前支持了Excel,Word,PowerPoint',
155 | filetypes=[
156 | ('Excel, PowerPoint, Word, PDF, Markdown, Text', '*.xlsx *.pptx *.docx *.pdf *.md *.txt'),
157 | ('All Files', '*.*')
158 | ]
159 | )
160 |
161 | if not file_path:
162 | print("没有选择文件。")
163 | process_cancelled = True
164 | return
165 |
166 | global input_path
167 | input_path = file_path
168 |
169 | supported_files = [".xlsx",".docx",".pptx", ".pdf", ".md", ".txt"]
170 | file_extension = os.path.splitext(file_path)[1].lower()
171 | global file_type
172 | if file_extension not in supported_files:
173 | print("错误:不受支持的文件")
174 | process_cancelled = True
175 | return
176 | if file_extension == ".xlsx":
177 | file_type = "Excel"
178 | strings = extract_strings_from_xlsx(file_path, enhance_mode)
179 | elif file_extension == ".docx":
180 | file_type = "Word"
181 | strings = extract_strings_from_docx(file_path)
182 | elif file_extension == ".pptx":
183 | file_type = "PowerPoint"
184 | strings = extract_strings_from_pptx(file_path)
185 | elif file_extension == ".pdf":
186 | file_type = "PDF"
187 | base, _ = os.path.splitext(file_path)
188 | docx_path = base + '.docx'
189 | data = {
190 | "source_path": file_path,
191 | "output_path": docx_path,
192 | "arg": False
193 | }
194 | message = json.dumps(data)
195 | strings = requests_docx(message, docx_path)
196 | if not strings:
197 | process_cancelled = True
198 | return
199 | input_path = docx_path
200 | elif file_extension == ".md" or ".txt":
201 | if file_extension == ".md":
202 | file_type = "Markown"
203 | else:
204 | file_type = "TEXT"
205 |
206 | print (f"纯文本文件,无需预处理")
207 | strings = []
208 | with open(input_path, 'r', encoding='utf-8') as file:
209 | for line in file:
210 | strings.append(line.strip())
211 |
212 |
213 | print(f"已处理{file_type}文件: {input_path}")
214 | output_file = os.path.join(tmp_dir, 'text_extracted.txt')
215 | write_strings_to_file(strings, output_file)
216 | print(f"提取的字符串已写入 {output_file}")
217 |
218 |
219 |
220 |
--------------------------------------------------------------------------------
/Lib/llm_translate.py:
--------------------------------------------------------------------------------
1 | import openai
2 | import time
3 | import os
4 | import json
5 | output_dir = './out'
6 | os.makedirs(output_dir, exist_ok=True)
7 |
8 | languages = {
9 | "zh-Hans": "中文(简体)",
10 | "zh-Hant": "中文(繁体)",
11 | "en-US": "英文(美国)",
12 | "en-GB": "英文(英国)",
13 | "ja": "日文",
14 | "ko": "韩文",
15 | "fr": "法文",
16 | "de": "德文",
17 | "ru": "俄文",
18 | "es": "西班牙文",
19 | "it": "意大利文",
20 | "pt": "葡萄牙文",
21 | }
22 |
23 | def llm_process(file_path, source_lang, target_lang, api_base, api_key, model, max_token = 4096, custom_prompt = "", mode = 'w', retries = 3, delay = 5):
24 | openai.api_base = api_base
25 | openai.api_key = api_key
26 | llm_prompt = custom_prompt
27 | target_language_name = languages.get(target_lang, target_lang)
28 | if llm_prompt and llm_prompt is not None:
29 | system_prompt = (f"你是一个翻译助手,以json格式输出。翻译要求:{llm_prompt}\n"
30 | f"请将以下文本逐行翻译成语言代码为`{target_language_name}`,并确保每一行都被翻译,包括空行。"
31 | "**请确保翻译前后行数完全一致,除此之外不要有多余的消息**")
32 | else:
33 | system_prompt = (f"你是一个翻译助手,以json格式输出。请将以下文本逐行翻译成语言代码为`{target_language_name}`,"
34 | "并确保每一行都被翻译,包括空行。**请确保翻译前后行数完全一致,除此之外不要有多余的消息**")
35 |
36 | def get_response_from_model(source_data, prompt):
37 | messages = source_data
38 | print("正在向大模型发送翻译请求,可能需要一些时间...")
39 | for attempt in range(retries):
40 | try:
41 | response = openai.ChatCompletion.create(
42 | model=model,
43 | messages=[
44 | {"role": "system", "content": prompt},
45 | {"role": "user", "content": messages}
46 | ]
47 | )
48 | return response.choices[0].message['content'].strip()
49 |
50 | except openai.error.OpenAIError as e:
51 | print(f"OpenAI API error on attempt {attempt + 1}: {e}")
52 | if attempt < retries - 1:
53 | print(f"Retrying in {delay} seconds...")
54 | time.sleep(delay)
55 | else:
56 | print("Max retries reached. Unable to get a response.")
57 | return ""
58 | except Exception as e:
59 | print(f"Unexpected error on attempt {attempt + 1}: {e}")
60 | if attempt < retries - 1:
61 | print(f"Retrying in {delay} seconds...")
62 | time.sleep(delay)
63 | else:
64 | print("Max retries reached. Unable to get a response.")
65 | return ""
66 |
67 | def convert_to_json(text):
68 | lines = text.split('\n')
69 | json_data = [{"line" + str(index + 1): line} for index, line in enumerate(lines)]
70 | return json.dumps(json_data, ensure_ascii=False, indent=4)
71 |
72 | def convert_json_to_text(json_text):
73 | json_data = json.loads(json_text)
74 | lines = [list(item.values())[0] for item in json_data]
75 | # 使用 join 拼接所有行
76 | result = "\n".join(lines)
77 | # 如果 JSON 的最后一行为空字符串,确保结果末尾保留换行符
78 | if json_data and list(json_data[-1].values())[0] == "":
79 | if not result.endswith("\n"):
80 | result += "\n"
81 | return result
82 |
83 | def split_text_into_chunks(text, max_tokens):
84 | # 确保 max_tokens 为整数
85 | if not isinstance(max_tokens, int):
86 | try:
87 | max_tokens = int(max_tokens)
88 | except ValueError:
89 | print("Invalid max_tokens value. It must be an integer.")
90 | return []
91 | # 将文本转换为 JSON 数据(列表形式)
92 | data = json.loads(convert_to_json(text))
93 |
94 | chunks = []
95 | current_chunk = []
96 | current_tokens = 0
97 |
98 | for item in data:
99 | item_tokens = len(json.dumps(item))
100 | if current_tokens + item_tokens > max_tokens:
101 | chunks.append(json.dumps(current_chunk, ensure_ascii=False))
102 | current_chunk = []
103 | current_tokens = 0
104 | current_chunk.append(item)
105 | current_tokens += item_tokens
106 |
107 | if current_chunk:
108 | chunks.append(json.dumps(current_chunk, ensure_ascii=False))
109 |
110 | return chunks
111 |
112 | # 读取文件内容
113 | try:
114 | with open(file_path, 'r', encoding='utf-8') as file:
115 | text = file.read()
116 | except FileNotFoundError:
117 | print(f"File not found: {file_path}")
118 | return ""
119 | except Exception as e:
120 | print(f"Error reading file {file_path}: {e}")
121 | return ""
122 |
123 | # 根据 max_token 限制,将文本拆分为多个块
124 | text_chunks = split_text_into_chunks(text, max_token)
125 | translated_text = ""
126 |
127 | for i, chunk in enumerate(text_chunks):
128 | translated_chunk = get_response_from_model(chunk, system_prompt)
129 | if translated_chunk:
130 | print(translated_chunk)
131 | # 如果是最后一个块,则不额外添加换行符
132 | if i == len(text_chunks) - 1:
133 | translated_text += convert_json_to_text(translated_chunk)
134 | else:
135 | translated_text += convert_json_to_text(translated_chunk) + '\n'
136 | else:
137 | print("Skipping chunk due to translation failure.")
138 |
139 | if not translated_text:
140 | print("No translation results available.")
141 | return ""
142 |
143 | try:
144 | with open('./out/translated_result.txt', mode, encoding='utf-8') as output_file:
145 | output_file.write(translated_text)
146 | print("Translation complete.")
147 | except Exception as e:
148 | print(f"Error writing to file: {e}")
149 | return ""
150 |
--------------------------------------------------------------------------------
/Lib/output.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import io
3 |
4 | class RedirectText(io.StringIO):
5 | def __init__(self, text_widget, tag):
6 | super().__init__()
7 | self.text_widget = text_widget
8 | self.tag = tag
9 |
10 | def write(self, message):
11 | if isinstance(message, bytes):
12 | message = message.decode('utf-8')
13 | self.text_widget.insert('end', message, self.tag)
14 | self.text_widget.see('end') # 自动滚动到文本框的底部
15 |
16 | def flush(self):
17 | pass # flush方法可以留空
18 |
19 | def start_redirect(text_widget):
20 | redirector_out = RedirectText(text_widget, "default")
21 | redirector_err = RedirectText(text_widget, "error")
22 | sys.stdout = redirector_out
23 | sys.stderr = redirector_err
24 |
25 | def send_warning(text_widget, message):
26 | text_widget.insert('end', message + '\n', 'warning')
27 | text_widget.see('end')
28 |
29 | def success_message(text_widget, message):
30 | text_widget.insert('end', message + '\n', 'success')
31 | text_widget.see('end')
32 |
--------------------------------------------------------------------------------
/Lib/playwright_process.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | import subprocess
4 | import psutil
5 | from playwright.sync_api import sync_playwright
6 | from pathlib import Path
7 | from Lib.config import config
8 |
9 | output_dir = './out'
10 | os.makedirs(output_dir, exist_ok=True)
11 | make_edge_happy = False
12 |
13 | def count_words(line):
14 | # 统计一行中的词数,以空格分隔
15 | return len(line.split())
16 |
17 | def process_file(file_path):
18 | with open(file_path, 'r', encoding='utf-8') as file:
19 | lines = file.readlines()
20 |
21 | total_word_count = 0
22 | strings_array = []
23 | current_string = []
24 |
25 | for i, line in enumerate(lines):
26 | line = line.strip() # 去掉行首尾的空白字符
27 | line_word_count = count_words(line)
28 | total_word_count += line_word_count
29 |
30 | current_string.append(line) # 添加当前行到当前字符串中
31 |
32 | if total_word_count > 150:
33 | # 当前字符串超过1000词,截断并保存
34 | strings_array.append('\n'.join(current_string))
35 | # 重置统计
36 | total_word_count = 0
37 | current_string = []
38 |
39 | # 添加最后一部分(如果有剩余)
40 | if current_string:
41 | strings_array.append('\n'.join(current_string))
42 |
43 | return strings_array
44 |
45 | def split_text_on_line_boundary(text, midpoint):
46 | # 向前查找换行符
47 | split_point = text.rfind('\n', 0, midpoint)
48 | if split_point == -1: # 如果未找到换行符
49 | # 向后查找换行符
50 | split_point = text.find('\n', midpoint)
51 | if split_point == -1: # 如果仍未找到换行符
52 | split_point = midpoint # 直接使用原始midpoint
53 |
54 | # 根据找到的分割点拆分文本,并保留换行符
55 | part1 = text[:split_point + 1] # 包含换行符
56 | part2 = text[split_point + 1:] # 从换行符之后开始
57 | return part1, part2
58 |
59 | def initialize_edge(disable_user_profile, playwright_headless):
60 | # 结束现有edge进程
61 | print("正在尝试结束现有edge实例...")
62 | if os.name == 'nt':
63 | for proc in psutil.process_iter():
64 | try:
65 | if proc.name().lower() == "msedge.exe":
66 | proc.terminate()
67 | proc.wait(timeout=5)
68 | except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
69 | continue
70 | else:
71 | for proc in psutil.process_iter():
72 | try:
73 | if proc.name().lower() in ["msedge", "microsoft edge"]:
74 | proc.terminate()
75 | proc.wait(timeout=5)
76 | except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
77 | continue
78 | # 构建 Edge 默认用户数据目录路径
79 | print("正在构建带用户数据的调试模式edge...")
80 | if os.name == 'nt': # Windows
81 | username = os.getlogin()
82 | user_data_dir = fr"C:\Users\{username}\AppData\Local\Microsoft\Edge\User Data"
83 | default_edge_path = Path("C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe")
84 | elif os.name == 'posix': # macOS/Linux
85 | username = os.path.basename(os.path.expanduser("~"))
86 | if 'darwin' in os.uname().sysname.lower(): # macOS
87 | default_edge_path = Path("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge")
88 | user_data_dir = f"/Users/{username}/Library/Application Support/Microsoft Edge"
89 | else: # Linux
90 | user_data_dir = f"/home/{username}/.config/microsoft-edge"
91 | default_edge_path = "/usr/bin/microsoft-edge"
92 | else:
93 | raise OSError("Unsupported operating system")
94 | if not disable_user_profile:
95 | if not os.path.exists(user_data_dir):
96 | print(f"用户数据目录不存在: {user_data_dir}")
97 | user_data_dir = None
98 | if user_data_dir:
99 | #subprocess.Popen([shlex.quote(default_edge_path), '--remote-debugging-port=9222', f'--user-data-dir={user_data_dir}'])
100 | if playwright_headless:
101 | command = f'"{default_edge_path}" --remote-debugging-port=9222 --user-data-dir="{user_data_dir}" --headless'
102 | else:
103 | command = f'"{default_edge_path}" --remote-debugging-port=9222 --user-data-dir="{user_data_dir}"'
104 | subprocess.Popen(command, shell=True)
105 | print("edge已启动")
106 | else:
107 | command = f'"{default_edge_path}" --remote-debugging-port=9222'
108 | subprocess.Popen(command, shell=True)
109 | else:
110 | if playwright_headless:
111 | command = f'"{default_edge_path}" --remote-debugging-port=9222 --user-data-dir="{user_data_dir}" --inprivate --headless'
112 | else:
113 | command = f'"{default_edge_path}" --remote-debugging-port=9222 --user-data-dir="{user_data_dir}" --inprivate'
114 | subprocess.Popen(command, shell = True)
115 | print("正在拉起不带用户数据的edge")
116 | return default_edge_path
117 |
118 |
119 | def force_select(page, source_lang, target_lang):
120 | print("尝试强制指定源语言\n如果卡在此处可能需要手动点击一下源语言选择")
121 | try:
122 | page.wait_for_selector('span[data-testid="translator-source-lang"]')
123 | page.click('span[data-testid="translator-source-lang"]')
124 |
125 | # 使用 XPath 选择器
126 | lang_xpath = f'//button[@data-testid="translator-lang-option-{source_lang}"]'
127 | page.wait_for_selector(lang_xpath)
128 | page.click(lang_xpath)
129 |
130 | print(f"已强制指定源语言{source_lang}")
131 | except Exception as e:
132 | print(f"设置源语言时发生错误: {e}")
133 | print("尝试强制指定目标语言\n如果卡在此处可能需要手动点击一下目标语言选择")
134 | try:
135 | # 点击目标语言选择区域
136 | page.wait_for_selector('div[data-testid="translator-target-lang"]')
137 | page.click('div[data-testid="translator-target-lang"]')
138 |
139 | # 使用 XPath 选择器
140 | lang_xpath = f'//button[@data-testid="translator-lang-option-{target_lang}"]'
141 | page.wait_for_selector(lang_xpath)
142 | page.click(lang_xpath)
143 |
144 | print(f"已强制指定目标语言{target_lang}")
145 | except Exception as e:
146 | print(f"设置目标语言时发生错误: {e}")
147 |
148 | def translate_text(page, text, source_lang, target_lang, force_lang_select):
149 | global make_edge_happy
150 | # 使用CSS选择器定位输入框元素
151 | input_element = page.query_selector('div[contenteditable="true"][role="textbox"][aria-multiline="true"]')
152 | #print(text)
153 |
154 | if input_element:
155 | input_element.fill('') # 清空输入框
156 | input_element.fill(text)
157 | else:
158 | print("输入框元素未找到")
159 | return None
160 | if force_lang_select:
161 | force_select(page, source_lang, target_lang)
162 |
163 | time.sleep(1)
164 |
165 | # 使用wait_for_selector方法等待翻译结果出现
166 | output_element = page.wait_for_selector('section[aria-labelledby="translation-target-heading"] div[contenteditable="true"][role="textbox"][aria-multiline="true"]')
167 |
168 | if output_element:
169 | original_lines = len([line for line in text.split('\n') if line.strip()])
170 | retry_count = 0
171 | while True:
172 | time.sleep(2) # 每2秒检查一次
173 | translated_text = output_element.inner_text()
174 | translated_lines = [line for line in translated_text.splitlines() if line.strip()]
175 | #print(f"原译文{translated_text}")
176 | print(f"已翻译{len(translated_lines)}/{original_lines}行")
177 | if len(translated_lines) == original_lines:
178 | if not (translated_lines[-1] == '[...] 'and translated_lines[-2] == '[...] '):
179 | # 创建一个新列表用于合并翻译结果和原始输入的空行
180 | processed_result = []
181 | translated_index = 0 # 用于跟踪翻译文本的索引
182 | for line in text.split('\n'):
183 | if line.strip() == "": # 如果原始行是空行
184 | processed_result.append("") # 添加一个空行
185 | else:
186 | if translated_index < len(translated_lines):
187 | processed_result.append(translated_lines[translated_index]) # 添加对应的翻译文本
188 | translated_index += 1
189 |
190 | # 将处理后的结果合并成字符串
191 | translated_text = "\n".join(processed_result) + "\n"
192 | return translated_text
193 | retry_count += 1
194 | if retry_count >= 4:
195 | # 检查是否存在字符限制提示
196 | char_limit_element = page.query_selector('div[data-testid="translator-character-limit-proad"]')
197 | if char_limit_element:
198 | print("检测到字符限制,正在拆分输入文本...")
199 | # 拆分文本并分别翻译
200 | part1, part2 = split_text_on_line_boundary(text, len(text) // 2)
201 | translated_part1 = translate_text(page, part1, source_lang, target_lang, force_lang_select)
202 | translated_part2 = translate_text(page, part2, source_lang, target_lang, force_lang_select)
203 |
204 | if translated_part1 is not None and translated_part2 is not None:
205 | # 合并翻译结果
206 | return translated_part1.strip() + "\n" + translated_part2.strip() + "\n"
207 | else:
208 | print("部分翻译失败,无法合并结果")
209 | return None
210 | else:
211 | print("翻译行数不匹配,刷新网页重试")
212 | page.reload() # 刷新网页
213 | retry_count = 0 # 重置重试计数器
214 |
215 | input_element = page.query_selector('div[contenteditable="true"][role="textbox"][aria-multiline="true"]')
216 | if input_element:
217 | input_element.fill('') # 清空输入框
218 | input_element.fill(text)
219 | else:
220 | print("输入框元素未找到")
221 | return None
222 |
223 | output_element = page.wait_for_selector('section[aria-labelledby="translation-target-heading"] div[contenteditable="true"][role="textbox"][aria-multiline="true"]')
224 | if not output_element:
225 | print("翻译结果元素未找到")
226 | return None
227 | else:
228 | print("翻译结果元素未找到")
229 | return None
230 |
231 | def playwright_engine(
232 | source_lang, target_lang, force_lang_select,
233 | browser_login, disable_user_profile,
234 | playwright_headless, playwright_path, input_file_path = 'text_extracted.txt', mode = 'w'
235 | ):
236 | global make_edge_happy
237 | if browser_login or not Path(playwright_path).exists():
238 | default_edge_path = initialize_edge(disable_user_profile, playwright_headless)
239 | strings_array = process_file(input_file_path)
240 | output_file_path = os.path.join(output_dir, 'translated_result.txt')
241 |
242 | with sync_playwright() as p:
243 | # Launch the browser
244 | print("正在拉起浏览器")
245 | if Path(playwright_path).exists() and not browser_login:
246 | browser = p.webkit.launch(executable_path=playwright_path, headless=playwright_headless)
247 | make_edge_happy = False
248 | page = browser.new_page()
249 | elif default_edge_path.exists():
250 | print("正在使用edge内核,但该模式可能兼容性有问题")
251 | browser = p.chromium.connect_over_cdp('http://127.0.0.1:9222') # 连接到远程调试端口
252 | context = browser.contexts[0] # 获取已有的上下文
253 | page = context.pages[0]
254 | make_edge_happy = True
255 | else:
256 | raise FileNotFoundError("找不到Playwright内核")
257 |
258 | page.goto(f"https://www.deepl.com/translator#{source_lang}/{target_lang}/")
259 |
260 | with open(output_file_path, mode, encoding='utf-8') as result_file:
261 | for i, s in enumerate(strings_array):
262 | translation = translate_text(page, s, source_lang, target_lang, force_lang_select)
263 | if translation:
264 | print(f"写入翻译结果 {i + 1}, 正在尝试下一个资源段翻译")
265 | result_file.write(translation)
266 | result_file.flush() # 立即写入文件
267 |
268 | browser.close()
269 |
--------------------------------------------------------------------------------
/Lib/test.py:
--------------------------------------------------------------------------------
1 | from playwright.sync_api import sync_playwright
2 | import time
3 |
4 | def force_lang_select(target_lang):
5 | with sync_playwright() as p:
6 | browser = p.webkit.launch(executable_path="./webkit/Playwright.exe", headless=False)
7 | page = browser.new_page()
8 |
9 | # 打开 Deepl 翻译器网页
10 | page.goto("https://www.deepl.com/en/translator")
11 |
12 | time.sleep(1) # 等待选择区域展开
13 | # 点击目标语言选择区域
14 | page.wait_for_selector('div[data-testid="translator-target-lang"]')
15 | page.click('div[data-testid="translator-target-lang"]')
16 | print("已点击语言选择区域")
17 |
18 |
19 | # 使用 XPath 选择器
20 | lang_xpath = f'//button[@data-testid="translator-lang-option-{target_lang}"]'
21 | page.wait_for_selector(lang_xpath)
22 | page.click(lang_xpath)
23 |
24 | print(f"已强制指定目标语言{target_lang}")
25 |
26 |
27 | force_lang_select("zh-Hant")
28 |
29 |
30 |
--------------------------------------------------------------------------------
/Lib/webkit/PLACE_PLAYWRGHT_WEBKIT_HERE:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/Lib/webkit/PLACE_PLAYWRGHT_WEBKIT_HERE
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DeeplxFile
2 | 基于Deeplx/playwright提供的简单易用,快速,免费,不限制文件大小,支持超长文本翻译的文件翻译工具
3 |
4 | [简体中文](https://github.com/infrost/DeeplxFile)
5 | |
6 | [English](/README_translated.md)
7 |
8 | [](https://github.com/infrost/DeeplxFile/releases)
9 | ------------------
10 | 点击[这里下载](https://github.com/infrost/DeeplxFile/releases)
11 |
12 | **重要!** 如果使用中遇到疑问或错误,请先查看[置顶的issue](https://github.com/infrost/DeeplxFile/issues)
13 |
14 | ## 功能介绍
15 | ### 这个软件有什么优点?
16 | 目前复杂文档,尤其是大文档的excel翻译,要么是要钱,要么是效果不好,要么是干脆直接不支持,该软件完美解决以上问题。
17 |
18 | #### 现已支持LLM大模型沉浸式翻译!
19 | 和常规文档翻译方法不同的是,基于大模型的翻译可以指定翻译风格或者给定特定语境或者背景知识,使得翻译效果更贴切
20 |
21 | 如使用自定义翻译要求:这是一封商务信函,使用庄严体翻译。
22 |
23 | #### 翻译质量
24 | 谷歌翻译,复杂公式引用无法正确显示,而DeeplxFile能正确显示引用公式。
25 | 且使用DeepL作为翻译源,大部分情况下中英互译效果优于谷歌。
26 | 
27 |
28 | #### 翻译文件支持
29 | 以Excel为例,DeepL免费版不支持Excel翻译,谷歌不支持超过10MB的大文件翻译,DeeplxFile文档翻译无大小限制
30 | 
31 |
32 | #### 简单易用的跨平台
33 | 提供好了编译好的Windows / Mac OS,直接下载就能用。
34 | 你也可以用python的源代码编译其他平台如Linux使用,或者直接在源代码上运行。
35 |
36 | ### 翻译PDF并转换为可编辑的.docx文档 (Windows)
37 | 现已支持该功能,但由于PDF转换功能体积较为庞大,请前往独立下载:
38 | [pdf2docxserver](https://github.com/infrost/pdf2docxserver/releases/)
39 |
40 | **下载后双击运行这个转换服务软件,并保持打开状态。**
41 |
42 | **使用`DeeplxFile`翻译的时候会自动调用转换服务。**
43 | 翻译效果如图:
44 | 
45 |
46 | ### Playwright模式(Windows/Mac OS)
47 | 
48 | > 从`v0.5.0`版本开始支持,可在设置选项卡中可开启`Playwright`模式。
49 | > 该模式是不依赖项目`deeplx`的,基于微软爬虫项目`Playwright`的实现。
50 | > releases中的`_Lite`版本不包含该模式所需要的运行文件(webkit浏览器内核)。
51 |
52 | 该模式下,程序会模拟人类打开浏览器,复制粘贴翻译内容,并回传到程序里,优点是兼容性强,可以翻译大量文本(目前没有测试出文本长度限制)并规避`deeplx`项目内核带来的`请求频繁`的错误。
53 | 缺点是会稍微占用一些系统资源,且速度较慢,可以开启`隐藏操作过程`以节约系统资源。
54 |
55 | ### 直连模式
56 | 该模式同样不依赖`deeplx`,但是可用性较低,容易遇到Deepl服务器`请求频繁`的拒绝,轻量的文档翻译可能可用,是最节约资源也是最原生的翻译实现。
57 |
58 | ## 我该如何使用?
59 | ### Windows
60 | 提供了编译好的exe版本, 运行安装程序即可
61 |
62 | **推荐** 下载`DeeplxFile_setup_windows_Full.exe` 解压安装,该版本带有完整webkit内核,playwright模式稳定性更好。
63 | `Lite`版本不带有webkit内核,会调用系统自带的Edge浏览器,因此体积更小,但目前对edge的支持还在测试阶段,如果你不太需要playwright模式,可以用这个版本。
64 | (你也可以设置里自己指定webkit内核)
65 |
66 | ### MacOS
67 |
68 | **已支持playwright模式,如果需使用请确保系统安装了edge浏览器**
69 |
70 | 
71 |
72 | 右键解压出来的文件,选择打开新终端,
73 | 终端中输入
74 | ```bash
75 | ./deelxfile
76 | ```
77 |
78 | ### 从源代码运行
79 | 你也可以下载源代码,
80 | 然后运行
81 | ```bash
82 | python deeplxfile_gui.py
83 | ```
84 | > 如果你需要使用Playwright模式的翻译功能,为了保持仓库的精简性,请手动下载`playwright-webkit`放在`./Lib/webkit`目录下然后运行,或者在`Lib/playwright_process.py`中指定Playwright的运行目录。
85 | > 如果你不是Windows系统,你需要在`deeplxfile_gui.py`中指定其他版本的deeplx,或者去deeplx官方项目下方,下载一个deeplx运行。
86 |
87 |
88 | ## 版本说明
89 |
90 | ```bash
91 | --------- V0.5.5/V0.5.6--------------
92 | 支持macOS下的playwright(需要安装edge,要求版本:MacOS 12+)
93 | 程序GUI优化,bug修复
94 |
95 | --------- V0.5.3--------------
96 | 提供登录选项,在设置中开启后,可以先登录deepl账号再进行翻译,有更大的单词字符翻译上限。
97 | 支持了Playwright下强制指定目标语言,适用于多语言混合文档。
98 | 支持PDF翻译(插件形式,见使用说明),
99 | 支持了txt,md文档翻译
100 | 为软件增加一个图标,感谢[openvc](https://github.com/infrost/DeeplxFile/issues/3)
101 |
102 | --------- V0.5.2--------------
103 | 提供了调用系统edge浏览器的playwright方法,更加轻量(完整版的更加稳定)
104 |
105 | ---------- V0.5.0 ------------
106 | 该版本提供了完整GUI界面,和设置选项,更加简单易用
107 | 增加了Playwright模式(测试中)。
108 |
109 | ---------- V0.2.3 ------------
110 | 现已完全支持Word,Excel
111 |
112 | powerpoint 支持翻译大部分内容
113 |
114 | 运行项目后会在目录下生成config.json
115 | 设置`save_original`为`true`即可保留原文
116 | ```
117 | ## Star History
118 |
119 | [](https://star-history.com/#infrost/deeplxfile&Date)
120 |
--------------------------------------------------------------------------------
/README_translated.md:
--------------------------------------------------------------------------------
1 | # DeeplxFile
2 | Easy-to-use, fast, free, unlimited file size, file translation tool based on Deeplx/playwright for very long texts.
3 |
4 | [Simplified Chinese](https://github.com/infrost/DeeplxFile)
5 | |
6 | [English](/README_translated.md)
7 |
8 | **The English Version is translated by DeeplxFile itself!**
9 |
10 | ------------------
11 | Click [here to download](https://github.com/infrost/DeeplxFile/releases)
12 |
13 | Check out the details at [here](https://blog.infrost.site/2024/08/29/DeeplxFile/)
14 |
15 | ## Features
16 | ### What are the advantages of this software?
17 | At present, the excel translation of complex documents, especially large documents, either costs money, or has bad effect, or simply does not support directly, this software perfectly solves the above problems.
18 | #### translation quality:
19 | Google Translate, complex formula references can not be correctly displayed, while DeeplxFile can correctly display the reference formula.
20 | And using DeepL as the translation source, in most cases, the effect of Chinese and English translation is better than Google.
21 | 
22 |
23 | #### Translation File Support
24 | Take Excel as an example, DeepL free version doesn't support Excel translation, Google doesn't support translation of large files over 10MB, DeeplxFile document translation has no size limitation!
25 | 
26 |
27 | ### Translate PDF and convert to editable .docx documents
28 | This feature is now supported, but due to the large size of the PDF conversion feature, please go to the standalone download:
29 | [pdf2docxserver](https://github.com/infrost/pdf2docxserver/releases/)
30 |
31 | **Double-click to run this conversion service software after download and keep it open.**
32 |
33 | **The conversion service will be called automatically when you use `DeeplxFile` to translate.**
34 | The translation effect is as shown in the picture:
35 | 
36 |
37 | ### Playwright mode (Windows)
38 | 
39 | > Supported since `v0.5.0`, `Playwright` mode can be enabled in the Settings tab.
40 | > This mode is independent of the project `deeplx` and is based on the implementation of the Microsoft crawler project `Playwright`.
41 | > The `_Lite` version in releases does not include the runtime files (webkit browser kernel) needed for this mode.
42 |
43 | In this mode, the program simulates a human opening a browser, copying and pasting the translated content and sending it back to the program. The advantages are compatibility, the ability to translate large amounts of text (no text length limit has been tested so far) and circumventing the `request-heavy` bug introduced by the `deeplx` project kernel.
44 | The disadvantage is that it will take up some system resources and is slow, you can turn on `hidden operation process` to save system resources.
45 |
46 | ### Direct connection mode
47 | This mode also doesn't rely on `deeplx`, but has lower availability, and is prone to encountering `requests` rejections from the Deepl server. It may be used for lightweight document translation, and is the most resource-efficient and native translation implementation.
48 |
49 | ### How do I use it?
50 | ### Windows
51 | A compiled exe version is provided, just run the installer.
52 |
53 | **Recommended** Download `DeeplxFile_setup_windows_Full.exe` and unpack it, this version comes with a full webkit kernel and is more stable in playwright mode.
54 | The `Lite` version doesn't come with webkit kernel, it will call the system's own Edge browser, so it's smaller in size, but the support for edge is still in the testing stage, so if you don't need playwright mode too much, you can use this version.
55 | (You can also specify your own webkit kernel in the settings)
56 |
57 | ### MacOS
58 |
59 | **Playwright mode will be supported soon
60 |
61 | Right-click on the extracted folder and select Open New Terminal in Folder.
62 | In the terminal, type
63 | ```bash
64 | . /deelxfile
65 | ``
66 |
67 | ### Run from source
68 | You can also download the source code
69 | and run it.
70 | ```bash
71 | python deeplxfile_gui.py
72 | ```
73 | > If you need to use the Playwright mode translation feature, to keep the repository lean, manually download `playwright-webkit` in the `. /Lib/webkit` directory and run it, or specify the Playwright runtime directory in `Lib/playwright_process.py`.
74 | > If you're not on Windows, you'll need to specify another version of deeplx in `deeplxfile_gui.py`, or go to the bottom of the official deeplx project and download a deeplx to run.
75 |
76 |
77 | ## Versioning
78 |
79 | ```bash
80 | --------- V0.5.3--------------
81 | Provide login option, when you turn it on in settings, you can login to deepl account first and then translate, with larger word character translation limit.
82 | Supports forced target language specification under Playwright, applicable to multi-language mixed documents.
83 | Support PDF translation (in the form of plug-in, see the instructions).
84 | Supported txt,md document translation.
85 | add an icon for the software, thanks to [openvc](https://github.com/infrost/DeeplxFile/issues/3)
86 |
87 | --------- V0.5.2--------------
88 | Provide playwright method to call system edge browser, more lightweight (the full version is more stable)
89 |
90 | ---------- V0.5.0 ------------
91 | This version provides the full GUI interface, and setting options, more easy to use
92 | Added Playwright mode (in testing).
93 |
94 | ---------- V0.2.3 ------------
95 | Word, Excel are now fully supported
96 |
97 | powerpoint Support translate most of the content
98 |
99 | After running the project, config.json will be generated in the directory.
100 | Set `save_original` to `true` to preserve the original text.
101 | ``
102 |
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "save_original": false,
3 | "version": "0.5.11",
4 | "dev": false,
5 | "i18n": "ZH",
6 | "playwright_headless": false,
7 | "playwright_path": "./Lib/Webkit/Playwright.exe",
8 | "browser_login": false,
9 | "force_lang_select": false,
10 | "translation_mode": "deeplx",
11 | "disable_user_profile": false,
12 | "enhance_mode": false,
13 | "deepl_token": "",
14 | "deeplx_core_version": "1.0.4",
15 | "deeplx_server": "",
16 | "llm_api_base": "https://api.openai.com/v1",
17 | "llm_api_key": "",
18 | "llm_model": "gpt-4o",
19 | "llm_prompt": "",
20 | "llm_max_token": "4096"
21 | }
--------------------------------------------------------------------------------
/deeplxfile_gui.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import os
3 | import time
4 | import requests
5 | import json
6 | import sys
7 | from concurrent.futures import ThreadPoolExecutor
8 | from tkinter import Tk, Text, Entry, StringVar, BooleanVar, Label, OptionMenu, Button, Checkbutton, Frame, messagebox, DISABLED, NORMAL, Radiobutton
9 | from tkinter.ttk import Notebook, Separator, Style
10 | from Lib import compose, data_process, extract, direct_mode, playwright_process, continue_trans, llm_translate
11 | from Lib.output import start_redirect, send_warning, success_message
12 | from Lib.config import config, save_config
13 |
14 | def run_deeplx(output_text_box):
15 | global processes
16 | exe_path = os.path.join("Lib",
17 | "deeplx_windows_amd64" if os.name == 'nt'
18 | else "deeplx_darwin_amd64" if os.name == 'posix'
19 | else "deeplx_linux_amd64")
20 | try:
21 | process_args = [exe_path]
22 | if os.name == 'nt':
23 | process = subprocess.Popen(
24 | process_args,
25 | stdout=subprocess.PIPE,
26 | stderr=subprocess.PIPE,
27 | text=True,
28 | creationflags=subprocess.CREATE_NO_WINDOW # Windows特有的创建参数
29 | )
30 | else:
31 | # 非Windows系统
32 | process = subprocess.Popen(
33 | process_args,
34 | stdout=subprocess.PIPE,
35 | stderr=subprocess.PIPE,
36 | text=True
37 | )
38 | processes.append(process)
39 | for line in process.stdout:
40 | print(line.strip()) # 使用 print 输出内容,这会被重定向到文本框
41 | # 等待进程完成
42 | process.wait()
43 | # 检查返回码
44 | if process.returncode != 0:
45 | print(f"Process finished with return code: {process.returncode}")
46 |
47 | except FileNotFoundError:
48 | print(f"The file {exe_path} was not found.")
49 | except Exception as e:
50 | print(f"An error occurred: {e}")
51 |
52 | def send_process_job(source_lang, target_lang, output_text_box):
53 | if config.get("translation_mode") == "direct":
54 | direct_mode.process_file('./tmp/text_extracted.txt', source_lang, target_lang)
55 | elif config.get("translation_mode") == "playwright":
56 | playwright_process.playwright_engine(
57 | source_lang, target_lang, config.get("force_lang_select", False),
58 | config.get("browser_login", False), config.get("disable_user_profile", False),
59 | config.get("playwright_headless", False), config.get("playwright_path", "./Lib/Webkit/Playwright.exe"), './tmp/text_extracted.txt'
60 | )
61 | elif config.get("translation_mode") == "llm":
62 | print("正在请求大模型翻译")
63 | llm_translate.llm_process('./tmp/text_extracted.txt', source_lang, target_lang, config.get("llm_api_base", "https://api.openai.com/v1"), config.get("llm_api_key", ""), config.get("llm_model", "gpt-4-turbo"), config.get("llm_max_token", 4096), config.get("llm_prompt", ""), mode = 'w', retries = 3, delay = 5)
64 | else:
65 | data_process.process_file('./tmp/text_extracted.txt', source_lang, target_lang, config.get("deepl_token", ""))
66 |
67 | success_message(output_text_box,f"完成翻译,正在根据原文件回写:{extract.input_path}")
68 | compose.compose_file(extract.file_type, extract.input_path, config.get("enhance_mode", False))
69 | success_message(output_text_box, "翻译完成!已在输入的相同目录下生成文件")
70 |
71 |
72 |
73 | def process_translation():
74 | global processes
75 | if config.get("translation_mode") == "direct":
76 | send_warning(output_text_box,"\n【直连模式】\n当前使用直连模式请求deepl的翻译返回,不使用deeplx引擎,如果频繁请求可能会遇到错误\n该模式只能翻译较小的文件,大文件请使用deeplx引擎")
77 | elif config.get("translation_mode") == "playwright":
78 | print("\n启用playwright模式(测试模式)")
79 | if config.get("browser_login", False):
80 | messagebox.showinfo("警告","使用edge调用playwright会结束现有edge的所有进程\n请在执行前保存好数据!否则请取消文件导入")
81 | if config.get("force_lang_select", False):
82 | send_warning(output_text_box, "强制选择语言有时候脚本会选不上卡住,请留意提示,手动点击一下即可")
83 | elif config.get("translation_mode") == "llm":
84 | print("\n启用大模型模式(测试模式)")
85 | if config.get("llm_prompt") and config.get("llm_prompt") is not None:
86 | send_warning(output_text_box, f"自定义翻译要求:{config.get('llm_prompt')}")
87 | else:
88 | try:
89 | if processes:
90 | print("deeplx引擎已在运行")
91 | else:
92 | if config.get("deeplx_server",False):
93 | print("使用自定的deeplx引擎")
94 | else:
95 | print("正在启动deeplx引擎")
96 | deeplx_future = executor.submit(run_deeplx, output_text_box)
97 | except Exception as e:
98 | print(f"Deeplx引擎异常,尝试使用直连模式 {e}")
99 | config['translation_mode'] = "direct"
100 | save_config(config)
101 | print("已将direct_mode设置为True")
102 | source_lang_name = source_lang_var.get()
103 | target_lang_name = target_lang_var.get()
104 |
105 | # 遍历 languages 列表,找到对应的语言代码
106 | source_lang = next(lang[1] for lang in languages if lang[0] == source_lang_name)
107 | target_lang = next(lang[1] for lang in languages if lang[0] == target_lang_name)
108 |
109 | if source_lang == "zh-Hans" or "zh-Hant":
110 | source_lang = "zh"
111 | elif source_lang == "en-US" or "en-GB":
112 | source_lang = "en"
113 | print("源语言代码:", source_lang)
114 | print("目标语言代码:", target_lang)
115 | print("等待选择文件...")
116 |
117 | # 解压
118 | extract.extract_file(config.get("enhance_mode", False))
119 | if extract.process_cancelled:
120 | send_warning(output_text_box, "文件导入取消")
121 | extract.process_cancelled = False
122 | return
123 | success_message(output_text_box, "文档解析已完成")
124 | process_job = executor.submit(send_process_job, source_lang, target_lang, output_text_box)
125 |
126 | def recover_mode():
127 | messagebox.showinfo("提示", "请选择上次需要翻译的原始文档")
128 | extract.extract_file(config.get("enhance_mode", False))
129 | if extract.process_cancelled:
130 | send_warning(output_text_box, "文件导入取消")
131 | extract.process_cancelled = False
132 | return
133 | success_message(output_text_box, "文档解析已完成")
134 | compose.compose_file(extract.file_type, extract.input_path, config.get("enhance_mode", False))
135 | success_message(output_text_box, "已尝试将已翻译内容恢复至输入目录同名_translated文件")
136 | messagebox.showinfo("成功", "文档已恢复至输入目录同名_translated文件")
137 |
138 | def continue_translation():
139 | source_lang_name = source_lang_var.get()
140 | target_lang_name = target_lang_var.get()
141 | source_lang = next(lang[1] for lang in languages if lang[0] == source_lang_name)
142 | target_lang = next(lang[1] for lang in languages if lang[0] == target_lang_name)
143 | if source_lang == "zh-Hans" or "zh-Hant":
144 | source_lang = "zh"
145 | elif source_lang == "en-US" or "en-GB":
146 | source_lang = "en"
147 | print("源语言代码:", source_lang)
148 | print("目标语言代码:", target_lang)
149 | messagebox.showinfo("提示", "请选择上次需要翻译的原始文档")
150 | extract.extract_file(config.get("enhance_mode", False))
151 | if extract.process_cancelled:
152 | send_warning(output_text_box, "文件导入取消")
153 | extract.process_cancelled = False
154 | return
155 | success_message(output_text_box, "文档解析已完成")
156 | print("读取上次翻译进度")
157 | continue_trans.move_lines()
158 | process_job = executor.submit(send_continue_job, source_lang, target_lang, output_text_box)
159 | messagebox.showinfo("提示", "翻译任务已提交,请留意`翻译`页控制台提示")
160 |
161 | def send_continue_job(source_lang, target_lang, output_text_box):
162 | send_warning(output_text_box, "以继续模式翻译时,请确保与上次翻译的文档是相同的")
163 | global processes
164 | if config.get("translation_mode") == "direct":
165 | direct_mode.process_file('./tmp/text_extracted.txt', source_lang, target_lang)
166 | elif config.get("translation_mode") == "playwright":
167 | if config.get("browser_login", False):
168 | messagebox.showinfo("警告","使用edge调用playwright会结束现有edge的所有进程\n请在执行前保存好数据!否则请取消文件导入")
169 | if config.get("force_lang_select", False):
170 | send_warning(output_text_box, "强制选择语言有时候脚本会选不上卡住,请留意提示,手动点击一下即可")
171 | print("starting playwright engine...")
172 | playwright_process.playwright_engine(
173 | source_lang, target_lang, config.get("force_lang_select", False),
174 | config.get("browser_login", False), config.get("disable_user_profile", False),
175 | config.get("playwright_headless", False), config.get("playwright_path", "./Lib/Webkit/Playwright.exe"),
176 | './tmp/text_extracted.txt', mode = 'a'
177 | )
178 | else:
179 | try:
180 | if processes:
181 | print("deeplx引擎已在运行")
182 | else:
183 | if config.get("deeplx_server",False):
184 | print("使用自定的deeplx引擎")
185 | else:
186 | print("正在启动deeplx引擎")
187 | deeplx_future = executor.submit(run_deeplx, output_text_box)
188 | except Exception as e:
189 | print(f"Deeplx引擎异常,尝试使用直连模式 {e}")
190 | config['translation_mode'] = "direct"
191 | save_config(config)
192 | print("已将direct_mode设置为True")
193 | data_process.process_file('./tmp/text_extracted.txt', source_lang, target_lang, config.get("deepl_token", ""))
194 | success_message(output_text_box,f"完成翻译,正在根据原文件回写:{extract.input_path}")
195 | #continue_trans.prepend_to_translated_result()
196 | compose.compose_file(extract.file_type, extract.input_path, config.get("enhance_mode", False))
197 | success_message(output_text_box, "翻译完成!已在输入的相同目录下生成文件")
198 |
199 |
200 | def check_update():
201 | current_ver = config.get("version")
202 | version_url = "https://raw.githubusercontent.com/infrost/DeeplxFile/master/config.json"
203 | try:
204 | response = requests.get(version_url)
205 | response.raise_for_status() # 检查请求是否成功
206 |
207 | data = response.json()
208 | online_ver = data.get("version")
209 |
210 | return online_ver if online_ver else None
211 | except requests.exceptions.RequestException as e:
212 | return f"网络错误: {e}"
213 | except ValueError as e:
214 | return f"数据错误: {e}"
215 |
216 |
217 | def start_check():
218 | update_button.config(state=DISABLED, text = "正在检查更新...")
219 | update_feature = executor.submit(check_update)
220 | result = update_feature.result()
221 | if result is None:
222 | messagebox.showinfo("错误", "未找到可更新版本信息")
223 | elif "错误" in result:
224 | messagebox.showinfo("错误", result)
225 | else:
226 | current_ver = config.get("version")
227 | if result != current_ver:
228 | messagebox.showinfo("更新提示",
229 | f"当前版本V: {current_ver}, 有新版本可用: V{result}\n请前往下载https://github.com/infrost/DeeplxFile/releases/")
230 | else:
231 | messagebox.showinfo("更新提示", f"已是最新版本: V{current_ver}")
232 |
233 | update_button.config(state=NORMAL, text = "检查更新")
234 |
235 | def save_and_exit():
236 | global warn_label
237 | global playwright_label
238 | #config['direct_mode'] = direct_mode_var.get()
239 | #config['playwright_mode'] = playwright_mode_var.get()
240 | config['browser_login'] = browser_login_var.get()
241 | config['save_original'] = save_original_var.get()
242 | config['playwright_headless'] = playwright_headless_var.get()
243 | config['playwright_path'] = playwright_path_var.get()
244 | config['force_lang_select'] = force_lang_select_var.get()
245 | config['disable_user_profile'] = disable_user_profile_var.get()
246 | config['translation_mode'] = translation_mode_var.get()
247 | config['enhance_mode'] = enhance_mode_var.get()
248 | config['deepl_token'] = deepl_token_var.get()
249 | config['deeplx_server'] = deeplx_server_var.get()
250 | config['llm_api_base'] = llm_api_base_var.get()
251 | config['llm_api_key'] = llm_api_key_var.get()
252 | config['llm_model'] = llm_model_var.get()
253 | config['llm_max_token'] = llm_max_token_var.get()
254 | config['llm_prompt'] = llm_prompt_var.get()
255 | save_config(config)
256 | if config.get("translation_mode") == "playwright":
257 | if "playwright_label" in globals() and playwright_label is not None:
258 | playwright_label.destroy() # 移除旧的Label
259 | playwright_label = None
260 | elif not "playwright_label" in globals() or playwright_label is None:
261 | playwright_label = Label(settings_frame, text="若要使用本页设置中的功能,请在翻译设置中选择`playwright模式`", fg="red")
262 | playwright_label.pack(pady=10)
263 |
264 |
265 | if config.get("translation_mode") == "llm":
266 | if "warn_label" in globals() and warn_label is not None:
267 | warn_label.destroy() # 移除旧的Label
268 | warn_label = None
269 | elif not "warn_label" in globals() or warn_label is None:
270 | warn_label = Label(llm_frame, text="若要使用本页设置中的功能,请在翻译设置中选择`大模型`", fg="red")
271 | warn_label.pack(pady=10)
272 |
273 | messagebox.showinfo("成功","设置已保存")
274 |
275 |
276 | def on_close():
277 | global processes
278 | for process in processes:
279 | if process:
280 | process.terminate()
281 | processes.clear()
282 | executor.shutdown(wait=False)
283 | root.destroy() # 关闭窗口
284 | os._exit(0)
285 |
286 | #这里是进程管理
287 | processes = []
288 | executor = ThreadPoolExecutor(max_workers=5)
289 |
290 |
291 | """
292 |
293 | 这里开始为GUI窗口绘制
294 |
295 | """
296 | #GUI
297 | root = Tk()
298 | root.title("DeeplxFile 翻译工具")
299 | if os.name == 'nt':
300 | icon_path = "./Lib/deeplxfile.ico"
301 | root.geometry("500x520")
302 | else:
303 | icon_path = "./Lib/deeplxfile.icns"
304 | root.geometry("570x550")
305 | root.iconbitmap(icon_path)
306 | #i18n.change_locale('en')
307 | default_font = ("Microsoft YaHei", 10) # 设定字体为Arial,大小为12
308 | root.option_add("*Font", default_font)
309 |
310 | notebook = Notebook(root)
311 |
312 |
313 | """
314 |
315 | 翻译选项卡
316 |
317 | """
318 | translate_frame = Frame(notebook)
319 | notebook.add(translate_frame, text="翻译")
320 | style = Style()
321 | style.configure("TNotebook.Tab", font=("Microsoft YaHei", 12)) # 设置 notebook 选项卡字体大小
322 |
323 | languages = [
324 | ("中文(简体)", "zh-Hans"),
325 | ("中文(繁体)","zh-Hant"),
326 | ("英文(美国)", "en-US"),
327 | ("英文(英国)", "en-GB"),
328 | ("日文", "ja"),
329 | ("韩文", "ko"),
330 | ("法文", "fr"),
331 | ("德文", "de"),
332 | ("俄文", "ru"),
333 | ("西班牙文", "es"),
334 | ("意大利文", "it"),
335 | ("葡萄牙文", "pt"),
336 | ]
337 |
338 | source_lang_var = StringVar(translate_frame)
339 | target_lang_var = StringVar(translate_frame)
340 | source_lang_var.set(languages[0][0])
341 | target_lang_var.set(languages[1][0])
342 |
343 | source_label = Label(translate_frame, text="选择源语言:")
344 | source_label.pack(pady=(10, 5))
345 |
346 | source_menu = OptionMenu(translate_frame, source_lang_var, *[lang[0] for lang in languages])
347 | source_menu.pack(pady=10)
348 |
349 | target_label = Label(translate_frame, text="选择目标语言:")
350 | target_label.pack(pady=(10, 5))
351 |
352 | target_menu = OptionMenu(translate_frame, target_lang_var, *[lang[0] for lang in languages])
353 | target_menu.pack()
354 |
355 | #Separator(translate_frame, orient='horizontal').pack(fill='x', pady=10)
356 |
357 | start_button = Button(translate_frame, text="选择文件", command=process_translation)
358 | start_button.pack(pady=20)
359 |
360 |
361 | # 创建输出内容流
362 | output_text_box = Text(translate_frame, wrap='word', font=("Microsoft YaHei", 10))
363 | output_text_box.pack(expand=True, fill='both')
364 | output_text_box.tag_configure("default", foreground="gray")
365 | output_text_box.tag_configure("error", foreground="red")
366 | output_text_box.tag_configure("warning", foreground="orange")
367 | output_text_box.tag_configure("success", foreground="green")
368 | io_futrue = executor.submit(start_redirect, output_text_box)
369 |
370 |
371 | """
372 |
373 | 翻译设置
374 |
375 | """
376 |
377 | trans_config_frame = Frame(notebook)
378 | notebook.add(trans_config_frame, text="翻译设置")
379 |
380 | radio_frame = Frame(trans_config_frame, bd=2, relief="groove")
381 | radio_frame.pack(pady=10, padx=10, fill="x")
382 | mode_config_label = Label(radio_frame, text="翻译模式")
383 | mode_config_label.pack()
384 | translation_mode_var = StringVar(radio_frame)
385 | translation_mode_var.set(config.get("translation_mode", ""))
386 | Radiobutton(radio_frame, text="直连模式", variable=translation_mode_var, value="direct").pack(anchor='w')
387 | Radiobutton(radio_frame, text="大模型 (测试阶段,支持翻译要求)", variable=translation_mode_var, value="llm").pack(anchor='w')
388 | Radiobutton(radio_frame, text="Playwright (兼容性好,默认)", variable=translation_mode_var, value="playwright").pack(anchor='w')
389 | Radiobutton(radio_frame, text="Deeplx (速度快,小文件可用)", variable=translation_mode_var, value="deeplx").pack(anchor='w')
390 | deepl_token_var = StringVar(radio_frame)
391 | deepl_token_var.set(config.get("deepl_token", ""))
392 | deepl_token_var_label = Label(radio_frame, text="Deepl Pro 密钥: (留空采用免费方法)")
393 | deepl_token_var_label.pack(anchor='w', padx=25)
394 | deepl_token_var_entry = Entry(radio_frame, textvariable=deepl_token_var, width=30)
395 | deepl_token_var_entry.pack(anchor='w', padx=25, pady=5)
396 |
397 | deeplx_server_var = StringVar(radio_frame)
398 | deeplx_server_var.set(config.get("deeplx_server", ""))
399 | deeplx_server_var_label = Label(radio_frame, text="Deeplx服务器地址: (e.g.127.0.0.1:1188, 留空使用自带的)")
400 | deeplx_server_var_label.pack(anchor='w', padx=25)
401 | deeplx_server_var_entry = Entry(radio_frame, textvariable=deeplx_server_var, width=30)
402 | deeplx_server_var_entry.pack(anchor='w', padx=25, pady=5)
403 |
404 |
405 | doc_config_frame = Frame(trans_config_frame, bd=2, relief="groove")
406 | doc_config_frame.pack(pady=10, padx=10, fill="x")
407 | doc_config_label = Label(doc_config_frame, text="文档处理")
408 | doc_config_label.pack()
409 |
410 | save_original_var = BooleanVar(doc_config_frame)
411 | save_original_var.set(config.get("save_original", False))
412 | save_original_checkbox = Checkbutton(doc_config_frame, text="保留原文", variable = save_original_var)
413 | save_original_checkbox.pack(anchor='w')
414 |
415 | enhance_mode_var = BooleanVar(doc_config_frame)
416 | enhance_mode_var.set(config.get("enhance_mode", False))
417 | enhance_mode_checkbox = Checkbutton(doc_config_frame, text="增强模式(beta)", variable = enhance_mode_var)
418 | enhance_mode_checkbox.pack(anchor='w')
419 | enhance_mode_label = Label(doc_config_frame, text="增强模式会尝试翻译文档中SmartArt,Excel中工作表Sheet的表名等内容")
420 | enhance_mode_label.pack(anchor='w', padx = 15)
421 |
422 | save_button = Button(trans_config_frame, text="保存设置", command=save_and_exit)
423 | save_button.pack(pady=(0, 10))
424 |
425 |
426 | """
427 |
428 | Playwright设置
429 |
430 | """
431 |
432 | settings_frame = Frame(notebook)
433 | notebook.add(settings_frame, text="playwright设置")
434 |
435 | # Playwright模式
436 | comment_label = Label(settings_frame, text="Playwright模式会模拟人类操作翻译\n会较为消耗性能,但是兼容性较强\n如果出现请求频繁错误,可以尝试该模式\n\n若使用Edge,可以提前在edge浏览器中登录账号\n 调用edge的登录状态能让单次翻译的字符更多,更稳定。")
437 | comment_label.pack(pady=10)
438 |
439 | playwright_frame = Frame(settings_frame, borderwidth=2, relief="groove", pady=10)
440 | playwright_frame.pack(padx=5, pady=5, anchor='w') # 内边距
441 | left_frame = Frame(playwright_frame)
442 | left_frame.pack(side='left', padx=10)
443 |
444 | browser_login_var = BooleanVar(playwright_frame)
445 | browser_login_var.set(config.get("browser_login", False))
446 | browser_login_checkbox = Checkbutton(left_frame, text="使用系统edge浏览器", variable=browser_login_var)
447 | browser_login_checkbox.pack(anchor='w')
448 | #comment_label3 = Label(left_frame, text="可以提前在edge浏览器中登录账号\n 调用edge的登录状态能让\n单次翻译的字符更多,更稳定。")
449 | #comment_label3.pack(anchor='w')
450 |
451 | disable_user_profile_var = BooleanVar(playwright_frame)
452 | disable_user_profile_checkbox = Checkbutton(left_frame, text="edge浏览器不使用用户数据", variable=disable_user_profile_var)
453 | disable_user_profile_checkbox.pack(anchor='w')
454 |
455 | playwright_headless_var = BooleanVar(playwright_frame)
456 | playwright_headless_var.set(config.get("playwright_headless", False))
457 | playwright_headless_checkbox = Checkbutton(left_frame, text="隐藏操作过程", variable=playwright_headless_var)
458 | playwright_headless_checkbox.pack(anchor='w')
459 | comment_label2 = Label(left_frame, text="可以节约系统资源, 加快翻译速度")
460 | comment_label2.pack(anchor='w', padx=5, pady=2)
461 |
462 | right_frame = Frame(playwright_frame)
463 | right_frame.pack(side='left', padx=10)
464 |
465 | force_lang_select_var = BooleanVar(playwright_frame)
466 | force_lang_select_var.set(config.get("force_lang_select", False))
467 | force_lang_select_checkbox = Checkbutton(right_frame, text="强制指定语言", variable=force_lang_select_var)
468 | force_lang_select_checkbox.pack(anchor='w')
469 | comment_label4 = Label(right_frame, text="少数情况无法正确翻译到指定语言时\n可以尝试开启,略微影响速度")
470 | comment_label4.pack(anchor='w')
471 |
472 | playwright_path_var = StringVar(playwright_frame)
473 | playwright_path_var.set(config.get("playwright_path", ""))
474 | playwright_path_label = Label(right_frame, text="Playwright Webkit 内核路径:")
475 | playwright_path_label.pack(anchor='w')
476 | playwright_path_entry = Entry(right_frame, textvariable=playwright_path_var, width=30)
477 | playwright_path_entry.pack(anchor='w', padx=5)
478 |
479 | #Separator(settings_frame, orient='horizontal').pack(fill='x', pady=20)
480 |
481 |
482 | save_button = Button(settings_frame, text="保存设置", command=save_and_exit)
483 | save_button.pack(pady=(0, 10))
484 |
485 | if config.get("translation_mode") != "playwright":
486 | playwright_label = Label(settings_frame, text="若要使用本页设置中的功能,请在翻译设置中选择`playwright模式`", fg="red")
487 | playwright_label.pack(pady=10)
488 |
489 |
490 | """
491 |
492 | 大模型翻译
493 |
494 | """
495 |
496 | llm_frame = Frame(notebook)
497 | notebook.add(llm_frame, text="大模型翻译(测试)")
498 |
499 | llm_api_base_var = StringVar(llm_frame)
500 | llm_api_base_var.set(config.get("llm_api_base", ""))
501 | llm_api_base_var_label = Label(llm_frame, text="\n大模型API地址:")
502 | llm_api_base_var_label.pack(anchor='w')
503 | llm_api_base_var_entry = Entry(llm_frame, textvariable=llm_api_base_var, width=35)
504 | llm_api_base_var_entry.pack(anchor='w', padx=5)
505 |
506 | llm_api_key_var = StringVar(llm_frame)
507 | llm_api_key_var.set(config.get("llm_api_key", ""))
508 | llm_api_key_var_label = Label(llm_frame, text="\n大模型API密钥:")
509 | llm_api_key_var_label.pack(anchor='w')
510 | llm_api_key_var_entry = Entry(llm_frame, textvariable=llm_api_key_var, width=35)
511 | llm_api_key_var_entry.pack(anchor='w', padx=5)
512 |
513 | llm_model_var = StringVar(llm_frame)
514 | llm_model_var.set(config.get("llm_model", ""))
515 | llm_model_var_label = Label(llm_frame, text="\n大模型名称:")
516 | llm_model_var_label.pack(anchor='w')
517 | llm_model_var_entry = Entry(llm_frame, textvariable=llm_model_var, width=35)
518 | llm_model_var_entry.pack(anchor='w', padx=5)
519 |
520 | llm_max_token_var = StringVar(llm_frame)
521 | llm_max_token_var.set(config.get("llm_max_token", ""))
522 | llm_max_token_var_label = Label(llm_frame, text="\n单次翻译长度限制(4096大约消耗1500token):")
523 | llm_max_token_var_label.pack(anchor='w')
524 | llm_max_token_var_entry = Entry(llm_frame, textvariable=llm_max_token_var, width=35)
525 | llm_max_token_var_entry.pack(anchor='w', padx=5)
526 |
527 | llm_prompt_var = StringVar(llm_frame)
528 | llm_prompt_var.set(config.get("llm_prompt", ""))
529 | llm_prompt_var_label = Label(llm_frame, text="自定义翻译要求\n(如:“这是一封商务信函,请使用庄严体翻译”等,可留空):")
530 | llm_prompt_var_label.pack(anchor='w')
531 | llm_prompt_var_entry = Entry(llm_frame, textvariable=llm_prompt_var, width=50)
532 | llm_prompt_var_entry.pack(anchor='w', padx=5)
533 |
534 | save_button = Button(llm_frame, text="保存设置", command=save_and_exit)
535 | save_button.pack(pady=(0, 10))
536 |
537 | info_label = Label(llm_frame, text="大模型翻译是测试功能,可能会有不稳定的情况\n目前只支持openai/openai like的API\n大模型速度取决于所选模型,请耐心等待", fg="blue")
538 | info_label.pack(pady=10)
539 |
540 | if config.get("translation_mode") != "llm":
541 | warn_label = Label(llm_frame, text="若要使用本页设置中的功能,请在翻译设置中选择`大模型`", fg="red")
542 | warn_label.pack(pady=10)
543 |
544 | """
545 |
546 | About
547 |
548 | """
549 |
550 | about_frame = Frame(notebook)
551 | notebook.add(about_frame, text="其他")
552 |
553 |
554 | recovery_button = Button(about_frame, text="文档恢复", command=recover_mode)
555 | recovery_button.pack(padx=10, pady =10)
556 | recover_mode_label = Label(about_frame, text="若上一次翻译因错误或意外退出,可尝试保存上一次已翻译的部分")
557 | recover_mode_label.pack(pady=5)
558 | continue_button = Button(about_frame, text="继续翻译", command=continue_translation)
559 | continue_button.pack( padx=10)
560 | continue_mode_label = Label(about_frame, text="或者继续进行翻译")
561 | continue_mode_label.pack(pady=5)
562 |
563 |
564 |
565 | Separator(about_frame, orient='horizontal').pack(fill='x', pady=30)
566 |
567 | about_label = Label(about_frame, text= f"软件版本\nDeeplxFile by Kevin V{config.get("version")}")
568 | about_label.pack(pady=10)
569 | core_label = Label(about_frame, text= f"内核版本\nDeeplx Core V{config.get("deeplx_core_version")}")
570 | core_label.pack(pady=10)
571 |
572 | email = Label(about_frame, text= f"i@infrost.site")
573 | email.pack(pady=10)
574 |
575 | update_button = Button(about_frame, text="检查更新", command=start_check)
576 | update_button.pack()
577 |
578 |
579 | #End of GUI
580 | notebook.pack(padx=10, pady=10, expand=True, fill="both")
581 | root.protocol("WM_DELETE_WINDOW", on_close)
582 | root.mainloop()
583 |
--------------------------------------------------------------------------------
/images/MacOS.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/MacOS.png
--------------------------------------------------------------------------------
/images/deeplx_file_support.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/deeplx_file_support.png
--------------------------------------------------------------------------------
/images/deeplxfile_quality.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/deeplxfile_quality.png
--------------------------------------------------------------------------------
/images/pdf_demo_animation.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/pdf_demo_animation.gif
--------------------------------------------------------------------------------
/images/pdf_translate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/pdf_translate.png
--------------------------------------------------------------------------------
/images/playwright.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infrost/DeeplxFile/7273cad60befc92641a053cf4e71901d6d9688dd/images/playwright.gif
--------------------------------------------------------------------------------