Compare commits
16 Commits
master
...
develop-mi
| Author | SHA1 | Date |
|---|---|---|
|
|
94d2f22b3c | |
|
|
846739cf77 | |
|
|
5f4baba012 | |
|
|
1f63a9c01c | |
|
|
9f42a65e9e | |
|
|
4b50b6bf4e | |
|
|
59cbda30e2 | |
|
|
64ac579c2a | |
|
|
965781213e | |
|
|
8dbfeddfe4 | |
|
|
fd69d47eca | |
|
|
ac2b198cd7 | |
|
|
a598099fba | |
|
|
8509f351a4 | |
|
|
59e2554238 | |
|
|
75835051b2 |
|
|
@ -0,0 +1,25 @@
|
|||
.git
|
||||
.idea
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.log
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.zip
|
||||
output
|
||||
outputs
|
||||
tmp
|
||||
.cache
|
||||
node_modules
|
||||
web_ui/node_modules
|
||||
web_ui/dist
|
||||
test_files
|
||||
tests
|
||||
build
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/.venv
|
||||
**/venv*
|
||||
**/*.egg-info
|
||||
|
|
@ -2,4 +2,6 @@
|
|||
*.mjs linguist-vendored
|
||||
*.html linguist-documentation
|
||||
*.css linguist-vendored
|
||||
*.scss linguist-vendored
|
||||
*.scss linguist-vendored
|
||||
*.sh text eol=lf
|
||||
docker/** text eol=lf
|
||||
|
|
|
|||
|
|
@ -52,5 +52,7 @@ _build/
|
|||
|
||||
output/
|
||||
web_ui/node_modules
|
||||
build/
|
||||
*.egg-info/
|
||||
|
||||
web_ui/dist
|
||||
web_ui/dist
|
||||
|
|
|
|||
|
|
@ -0,0 +1,662 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
|
|
@ -1,76 +1,27 @@
|
|||
# ==========================================
|
||||
# 阶段 1:前端构建 (Node.js Builder)
|
||||
# ==========================================
|
||||
FROM node:18-alpine AS frontend-builder
|
||||
|
||||
WORKDIR /build
|
||||
# 利用镜像缓存:先拷贝 package.json
|
||||
COPY web_ui/package*.json ./
|
||||
RUN npm config set registry https://registry.npmmirror.com && \
|
||||
npm install
|
||||
|
||||
# 拷贝源码并构建
|
||||
COPY web_ui/ .
|
||||
RUN npm run build
|
||||
|
||||
# ==========================================
|
||||
# 阶段 2:最终运行环境 (CoreX Runtime)
|
||||
# ==========================================
|
||||
# MinerU 2.7.6 / Iluvatar CoreX
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
ENV MINERU_VLLM_DEVICE=corex
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV MINERU_MODEL_SOURCE=local
|
||||
|
||||
# 1. 系统级依赖:仅安装运行时必需的字体和工具
|
||||
RUN apt-get update && apt-get install -y \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fontconfig \
|
||||
libgl1-mesa-glx \
|
||||
&& fc-cache -fv \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 2. Python 依赖安装策略:
|
||||
# 使用 --no-deps 确保不覆盖 CoreX 预装的 torch 2.7.1 和 vllm 0.11.2
|
||||
RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip install 'mineru[core]>=2.7.4' --no-deps -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
# 手动补齐 MinerU 运行必需但基础镜像可能缺失的轻量依赖(不会破坏 torch)
|
||||
python3 -m pip install \
|
||||
"numpy==1.26.4" \
|
||||
"opencv-python==4.11.0.86" \
|
||||
"pydantic<2.0" \
|
||||
"modelscope" \
|
||||
"magic-pdf" \
|
||||
-i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip cache purge
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
|
||||
# 3. 拷贝项目源码(排除 web_ui 源码以减小体积)
|
||||
COPY . .
|
||||
|
||||
# ... 前面步骤保持不变 ...
|
||||
|
||||
# 4. 从阶段 1 拷贝前端构建产物
|
||||
RUN mkdir -p mineru/cli/static/web
|
||||
COPY --from=frontend-builder /build/dist/ ./mineru/cli/static/web/
|
||||
|
||||
# 5. 配置文件优化:必须先于模型下载执行
|
||||
RUN mkdir -p /root/.cache/modelscope/hub/models && \
|
||||
echo '{ \
|
||||
"models-dir": "/root/.cache/modelscope/hub/models", \
|
||||
"device-mode": "gpu", \
|
||||
"vlm-config": { \
|
||||
"kind": "vllm", \
|
||||
"precision": "fp16" \
|
||||
} \
|
||||
}' > /root/magic-pdf.json
|
||||
|
||||
# 6. 模型预下载
|
||||
RUN /bin/bash -c "export MINERU_MODEL_SOURCE=local && mineru-models-download -s modelscope -m all"
|
||||
|
||||
|
||||
|
||||
# 7. 入口点
|
||||
ENTRYPOINT ["/bin/bash", "-c", "exec \"$@\"", "--"]
|
||||
CMD ["python3", "-m", "mineru.cli.main"]
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
# MinerU 2.7.6 / Iluvatar CoreX
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
ENV MINERU_VLLM_DEVICE=corex
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
FROM unis-mindmap-api:latest
|
||||
RUN python3 -m pip install \
|
||||
boto3 \
|
||||
"pdfminer.six>=20251230" \
|
||||
pypdfium2 \
|
||||
pypdf \
|
||||
reportlab \
|
||||
pdftext \
|
||||
huggingface-hub \
|
||||
json-repair \
|
||||
fast-langdetect \
|
||||
scikit-image \
|
||||
openai \
|
||||
beautifulsoup4 \
|
||||
magika \
|
||||
mineru-vl-utils \
|
||||
qwen-vl-utils \
|
||||
matplotlib \
|
||||
ultralytics \
|
||||
doclayout_yolo==0.0.4 \
|
||||
dill \
|
||||
PyYAML \
|
||||
ftfy \
|
||||
shapely \
|
||||
pyclipper \
|
||||
omegaconf \
|
||||
onnxruntime \
|
||||
python-pptx \
|
||||
python-docx \
|
||||
openpyxl \
|
||||
xlrd \
|
||||
xlwt \
|
||||
pylatexenc \
|
||||
mammoth \
|
||||
-i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip cache purge
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
FROM unis-mindmap-api:latest
|
||||
|
||||
COPY mineru/backend/vlm/vlm_analyze.py /app/mineru/backend/vlm/vlm_analyze.py
|
||||
COPY mineru/backend/vlm/utils.py /app/mineru/backend/vlm/utils.py
|
||||
|
|
@ -1,27 +1,27 @@
|
|||
# Base image containing the vLLM inference environment, requiring amd64(x86-64) CPU + iluvatar GPU.
|
||||
# MinerU 2.7.6 / Iluvatar CoreX
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
ENV MINERU_VLLM_DEVICE=corex
|
||||
|
||||
|
||||
# Install Noto fonts for Chinese characters
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fontconfig && \
|
||||
fc-cache -fv && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install mineru latest
|
||||
RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip install 'mineru[core]>=2.7.4' \
|
||||
numpy==1.26.4 \
|
||||
opencv-python==4.11.0.86 \
|
||||
-i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip cache purge
|
||||
|
||||
# Download models and update the configuration file
|
||||
RUN /bin/bash -c "mineru-models-download -s modelscope -m all"
|
||||
|
||||
# Set the entry point to activate the virtual environment and run the command line tool
|
||||
ENTRYPOINT ["/bin/bash", "-c", "export MINERU_MODEL_SOURCE=local && exec \"$@\"", "--"]
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -1,86 +1,27 @@
|
|||
# ==========================================
|
||||
# 阶段 1: 构建阶段 (Builder) - 负责前端 UI 编译
|
||||
# ==========================================
|
||||
FROM docker.m.daocloud.io/ubuntu:22.04 AS builder
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# 替换为阿里云镜像源并安装 Node.js [cite: 8, 9]
|
||||
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
|
||||
apt-get update && apt-get install -y curl && \
|
||||
curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
|
||||
apt-get install -y nodejs && \
|
||||
apt-get clean
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
# 构建前端 Web UI [cite: 12]
|
||||
WORKDIR /app/web_ui
|
||||
RUN npm install && npm run build
|
||||
|
||||
|
||||
# ==========================================
|
||||
# 阶段 2: 运行阶段 (Runtime) - 天数智芯专用环境
|
||||
# ==========================================
|
||||
# 使用天数智芯官方适配镜像,该镜像内置了 Python 3.10.18 和 CoreX 驱动 [cite: 15]
|
||||
# MinerU 2.7.6 / Iluvatar CoreX
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
ENV MINERU_VLLM_DEVICE=corex
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
|
||||
# 1. 安装字体与 LibreOffice 依赖 [cite: 15]
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fontconfig \
|
||||
libgl1 \
|
||||
libreoffice-writer \
|
||||
libreoffice-core && \
|
||||
fc-cache -fv && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 2. 核心环境修复:确保在 CoreX 的 Python 路径下安装依赖
|
||||
# 注意:使用 python3 -m pip 确保安装到 3.10.18 环境,避免 uvicorn 找不到 [cite: 16]
|
||||
RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -m pip install \
|
||||
'mineru[core]>=2.7.4' \
|
||||
"uvicorn" \
|
||||
"fastapi" \
|
||||
"python-multipart" \
|
||||
"modelscope>=1.26.0" \
|
||||
"huggingface-hub>=0.32.4" \
|
||||
"mineru-vl-utils>=0.1.19.1" \
|
||||
"qwen-vl-utils>=0.0.14" \
|
||||
numpy==1.26.4 \
|
||||
opencv-python==4.11.0.86 \
|
||||
-i https://mirrors.aliyun.com/pypi/simple
|
||||
|
||||
# 3. 拷贝源码及第一阶段的前端产物 [cite: 10, 13]
|
||||
COPY . .
|
||||
RUN mkdir -p /app/mineru/cli/static/web && \
|
||||
cp -r /app/web_ui/dist/* /app/mineru/cli/static/web/
|
||||
|
||||
# 4. 下载模型权重 (离线模式必备) [cite: 16]
|
||||
RUN /bin/bash -c "mineru-models-download -s modelscope -m all"
|
||||
|
||||
# 5. 注入适配天数 GPU 的配置文件 (开启 vLLM 推理) [cite: 13]
|
||||
RUN mkdir -p /root/ && \
|
||||
echo '{ \
|
||||
"models-dir": "/root/.cache/modelscope/hub/models", \
|
||||
"device-mode": "cuda", \
|
||||
"vlm-config": { \
|
||||
"kind": "vllm", \
|
||||
"precision": "fp16" \
|
||||
} \
|
||||
}' > /root/magic-pdf.json
|
||||
|
||||
# 6. 设置环境变量 [cite: 17]
|
||||
ENV MINERU_MODEL_SOURCE=local
|
||||
ENV PYTHONPATH=/app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
|
||||
# 7. 启动服务:使用 /bin/bash 包装以加载 CoreX 环境路径,解决二进制执行错误
|
||||
ENTRYPOINT ["/bin/bash", "-c", "PYTHONPATH=/app exec python3 -m mineru.cli.fast_api --host 0.0.0.0 --port 8000"]
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -1,107 +1,27 @@
|
|||
# ==========================================
|
||||
# 阶段 1: 构建阶段 (Builder) - 适配天数智芯 (Iluvatar CoreX)
|
||||
# ==========================================
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10 AS builder
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# 替换为阿里云镜像源(corex base 已预优化,若无匹配则不影响)
|
||||
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
|
||||
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
|
||||
|
||||
# 安装构建环境、Node.js(Web UI)、libreoffice、字体等依赖
|
||||
# corex base 已包含部分字体与 Python,但仍需补充构建工具与 Node.js
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
build-essential curl wget git fontconfig libgl1 \
|
||||
libreoffice-writer libreoffice-core \
|
||||
fonts-noto-core fonts-noto-cjk \
|
||||
python3-pip && \
|
||||
curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
|
||||
apt-get install -y nodejs && \
|
||||
fc-cache -fv && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
# MinerU 2.7.6 / Iluvatar CoreX
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
ENV MINERU_VLLM_DEVICE=corex
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
# 1. 升级基础 Python 构建工具
|
||||
RUN python3 -m pip install --upgrade pip setuptools wheel -i https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
RUN python3 -m pip install --no-cache-dir \
|
||||
"uvicorn[standard]>=0.30" \
|
||||
"fastapi>=0.115" \
|
||||
"python-multipart>=0.0.9" \
|
||||
-i https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
# 2. 引入 corex.Dockerfile 的 pinned 依赖(解决版本冲突)
|
||||
RUN python3 -m pip install \
|
||||
numpy==1.26.4 \
|
||||
opencv-python==4.11.0.86 \
|
||||
-i https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
# 3. 预装项目所需核心依赖(跳过 torch,因为 corex base 已提供 GPU 版)
|
||||
RUN python3 -m pip install \
|
||||
"modelscope>=1.26.0" \
|
||||
"huggingface-hub>=0.32.4" \
|
||||
"mineru-vl-utils>=0.1.19.1" \
|
||||
"qwen-vl-utils>=0.0.14" \
|
||||
"transformers>=4.51.1" \
|
||||
"accelerate>=1.5.1" \
|
||||
-i https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
# 4. 安装项目及所有可选依赖 [all](自动涵盖 doclayout_yolo、layout/vlm 等)
|
||||
RUN python3 -m pip install -e ".[all]" -i https://mirrors.aliyun.com/pypi/simple/
|
||||
|
||||
# 5. 构建阶段预下载所有权重文件(结合 corex 的下载命令 + 配置)
|
||||
RUN mkdir -p /root/.cache/modelscope/hub/models && \
|
||||
echo '{"models-dir": "/root/.cache/modelscope/hub/models", "device-mode":"gpu"}' > /root/magic-pdf.json && \
|
||||
export MINERU_CONFIG_PATH=/root/magic-pdf.json && \
|
||||
/bin/bash -c "mineru-models-download -s modelscope -m all"
|
||||
|
||||
# 6. 构建前端 Web UI
|
||||
WORKDIR /app/web_ui
|
||||
RUN npm install && npm run build
|
||||
WORKDIR /app
|
||||
RUN mkdir -p mineru/cli/static/web && cp -r web_ui/dist/* mineru/cli/static/web/
|
||||
|
||||
# ==========================================
|
||||
# 阶段 2: 运行阶段 (Runtime)
|
||||
# ==========================================
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10 AS runtime
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# 替换为阿里云镜像源(安全起见)
|
||||
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
|
||||
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list || true
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y libgl1 libreoffice-writer libreoffice-core \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig python3 python3-pip && \
|
||||
fc-cache -fv && apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 从构建阶段拷贝依赖、预下载模型、源码和 Web UI 静态文件
|
||||
COPY --from=builder /usr/local/lib/python3.10/dist-packages /usr/local/lib/python3.10/dist-packages
|
||||
COPY --from=builder /usr/local/bin /usr/local/bin
|
||||
COPY --from=builder /root/.cache/modelscope/hub/models /root/.cache/modelscope/hub/models
|
||||
COPY --from=builder /app /app
|
||||
|
||||
# 核心修复:注入标准的运行时配置文件(适配 GPU)
|
||||
RUN mkdir -p /root/ && \
|
||||
echo '{ \
|
||||
"models-dir": "/root/.cache/modelscope/hub/models", \
|
||||
"device-mode": "gpu", \
|
||||
"vlm-config": { \
|
||||
"kind": "transformers", \
|
||||
"precision": "fp16" \
|
||||
} \
|
||||
}' > /root/magic-pdf.json
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
|
||||
# 启动服务(结合 corex 的 MINERU_MODEL_SOURCE=local + 原 fast_api 入口)
|
||||
ENTRYPOINT ["/bin/sh", "-c", "export MINERU_MODEL_SOURCE=local && PYTHONPATH=/app python3 -m mineru.cli.fast_api --host 0.0.0.0 --port 8000"]
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,8 @@
|
|||
# Apply together with accelerator constraints generated from the vendor image.
|
||||
mineru==2.7.6
|
||||
numpy==1.26.4
|
||||
opencv-python==4.11.0.86
|
||||
transformers==4.57.3
|
||||
mineru-vl-utils==0.1.19.1
|
||||
qwen-vl-utils==0.0.14
|
||||
pydantic>=2.12,<3
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export MINERU_MODEL_SOURCE=${MINERU_MODEL_SOURCE:-local}
|
||||
export MINERU_MODEL_DIR=${MINERU_MODEL_DIR:-/models}
|
||||
export MINERU_TOOLS_CONFIG_JSON=${MINERU_TOOLS_CONFIG_JSON:-/root/mineru.json}
|
||||
export MINERU_API_MAX_CONCURRENT_REQUESTS=${MINERU_API_MAX_CONCURRENT_REQUESTS:-1}
|
||||
export PYTHONPATH="/app${PYTHONPATH:+:$PYTHONPATH}"
|
||||
|
||||
# Preserve mounted settings, including optional title-aided configuration.
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
path = Path(os.environ['MINERU_TOOLS_CONFIG_JSON'])
|
||||
config = json.loads(path.read_text()) if path.exists() else {}
|
||||
models = config.setdefault('models-dir', {})
|
||||
if not isinstance(models, dict):
|
||||
raise ValueError('models-dir must contain pipeline and vlm paths')
|
||||
root = Path(os.environ['MINERU_MODEL_DIR'])
|
||||
for backend in ('pipeline', 'vlm'):
|
||||
override = os.getenv(f'MINERU_{backend.upper()}_MODEL_DIR')
|
||||
models[backend] = override or models.get(backend) or str(root / backend)
|
||||
config.setdefault('config_version', '1.3.1')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not path.exists() or json.loads(path.read_text()) != config:
|
||||
path.write_text(json.dumps(config, ensure_ascii=False, indent=2))
|
||||
PY
|
||||
exec "$@"
|
||||
|
|
@ -1,39 +1,26 @@
|
|||
# Use the official vllm image for gpu with Ampere、Ada Lovelace、Hopper architecture (8.0 <= Compute Capability <= 9.0)
|
||||
# Compute Capability version query (https://developer.nvidia.com/cuda-gpus)
|
||||
# only support x86_64 architecture
|
||||
FROM vllm/vllm-openai:v0.10.1.1
|
||||
# MinerU 2.7.6 / NVIDIA CUDA
|
||||
FROM vllm/vllm-openai:v0.11.2
|
||||
|
||||
# Use the official vllm image for gpu with Volta、Turing、Blackwell architecture (7.0 < Compute Capability < 8.0 or Compute Capability >= 10.0)
|
||||
# support x86_64 architecture and ARM(AArch64) architecture
|
||||
# FROM vllm/vllm-openai:v0.11.0
|
||||
|
||||
# Install libgl for opencv support & Noto fonts for Chinese characters
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fontconfig \
|
||||
libgl1 && \
|
||||
fc-cache -fv && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install LibreOffice for Word to PDF conversion (minimal installation)
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
libreoffice-writer \
|
||||
libreoffice-core \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install mineru latest
|
||||
RUN python3 -m pip install -U 'mineru[core]>=2.7.0' --break-system-packages && \
|
||||
python3 -m pip cache purge
|
||||
|
||||
# Download models and update the configuration file
|
||||
RUN /bin/bash -c "mineru-models-download -s huggingface -m all"
|
||||
|
||||
# Set the entry point to activate the virtual environment and run the command line tool
|
||||
ENTRYPOINT ["/bin/bash", "-c", "export MINERU_MODEL_SOURCE=local && exec \"$@\"", "--"]
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
# MinerU 2.7.6 / NVIDIA CUDA
|
||||
FROM vllm/vllm-openai:v0.11.2
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
MINERU_MODEL_SOURCE=local \
|
||||
MINERU_MODEL_DIR=/models \
|
||||
MINERU_TOOLS_CONFIG_JSON=/root/mineru.json \
|
||||
MINERU_API_MAX_CONCURRENT_REQUESTS=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core fonts-noto-cjk fontconfig libgl1 libglib2.0-0 \
|
||||
libreoffice-writer libreoffice-core && fc-cache -fv && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
COPY . /app
|
||||
# Resolve against the accelerator wheels already provided by the selected base image.
|
||||
RUN python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt && \
|
||||
python3 -m pip install 'setuptools>=61,<81' wheel && \
|
||||
python3 -m pip install --no-build-isolation \
|
||||
-c /tmp/accelerator-constraints.txt -c docker/constraints-2.7.6.txt '.[core]' && \
|
||||
python3 scripts/accelerator_constraints.py /tmp/accelerator-constraints.txt --check && \
|
||||
python3 -m pip check && \
|
||||
python3 -c "from mineru.version import __version__; assert __version__ == '2.7.6'" && \
|
||||
chmod +x docker/entrypoint.mineru-api.sh && python3 -m pip cache purge
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["/app/docker/entrypoint.mineru-api.sh"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
{
|
||||
"version": "2.7.6",
|
||||
"url": "https://files.pythonhosted.org/packages/44/99/a4cf2751c4055d25d16e915215c031ae362bf4bf198efed4991161c6159e/mineru-2.7.6-py3-none-any.whl",
|
||||
"sha256": "b85ea4cef26397013e92dfdf3a32e68b422e233d27ba103a152843559fd7eb51",
|
||||
"customizations": [
|
||||
"cli/common.py: Word conversion and file progress",
|
||||
"cli/fast_api.py: application API and compatibility routes",
|
||||
"cli/gradio_app.py: Markmap view",
|
||||
"backend/pipeline/pipeline_middle_json_mkcontent.py: six heading levels",
|
||||
"backend/vlm/vlm_middle_json_mkcontent.py: six heading levels",
|
||||
"utils/llm_aided.py: six-level title prompt"
|
||||
],
|
||||
"official_source_hashes": {
|
||||
"version.py": "eb11b65df72d35957f88c01b0dfdcfb1c7b05b08cf7f07e6002db369e311d8a2",
|
||||
"__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"backend/utils.py": "18b254dc8ce70e6844d7fa8d9a453550eb6cbac9081c17b382c1153ba51aafe6",
|
||||
"backend/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"backend/hybrid/hybrid_analyze.py": "49c930e93fa9bccbf757f9ea66405e5bc918e333480655b1a9e4b6bd7a8daad6",
|
||||
"backend/hybrid/hybrid_magic_model.py": "fc3bc1ab958ffd466f9877e1665a31aaff8c2a85967bfc9ed6434bbfa440e6b5",
|
||||
"backend/hybrid/hybrid_model_output_to_middle_json.py": "c84f9cd5e19ae4bccfa8b7ca7ef04e37f4894658eacb3d81ecb8a0945704ec54",
|
||||
"backend/hybrid/__init__.py": "20582bd82f0d7d2023f2aec917b40ea8cbc2889e8573c4c8b94dd48760da1595",
|
||||
"backend/pipeline/batch_analyze.py": "dd406cd963b0708fa67c6025c59b78dfb3aa48e95e5cf2e7a586eb0fd8790f9e",
|
||||
"backend/pipeline/model_init.py": "d831d8c2aad65ed2b7bfabb911fa051d9a9f50d134d0c2dfcee10687e3a1a018",
|
||||
"backend/pipeline/model_json_to_middle_json.py": "ade5e4511ff02a6243eb877bbd135733116f8b09330e51a346c869770b15aae2",
|
||||
"backend/pipeline/model_list.py": "edc5cc05f66b3f42baa96b9e8350fff96a1400d79220dce49ff89cf44ed840bb",
|
||||
"backend/pipeline/para_split.py": "2aaf79326be43e6eeb2b1942486893bd52b217b084ac7236786180b39b0b9744",
|
||||
"backend/pipeline/pipeline_analyze.py": "f365c7ee15729ee0ff9ee93ebfb6bfce1c7fdd9fcc1d2df5b08bab4349479974",
|
||||
"backend/pipeline/pipeline_magic_model.py": "c3c8c6c7c7fac9937459fdb23cfdcbf6b60a73dae8831ade642ad427326f3cef",
|
||||
"backend/pipeline/pipeline_middle_json_mkcontent.py": "34908b18a13b06a336e1b45da5709f4da9728aaa33a301598e9773a48532e5a0",
|
||||
"backend/pipeline/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"backend/vlm/model_output_to_middle_json.py": "02a617e38812f5cad43bfb7b4ae51ab43ef51158e8c3aa48eb2036224de0434b",
|
||||
"backend/vlm/utils.py": "8a0c6073e6578def93290bd9da9fd82594cc9074bdc9713bbb5f8571a184559d",
|
||||
"backend/vlm/vlm_analyze.py": "55cf2b473bdc1397a08d6fc9ecbd1bb9ea3674b2b76f728a233bc22b60320519",
|
||||
"backend/vlm/vlm_magic_model.py": "4687685703498738f2b912e7e48a398053085f53710aeb8bcc26d4c4668a57cd",
|
||||
"backend/vlm/vlm_middle_json_mkcontent.py": "c3e4b36e6e078ad47b318e298a7482659757b4f4aa9ad954f5c8cd87820e4328",
|
||||
"backend/vlm/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"cli/client.py": "98f35f3044a1546fa2b619a5250e6719121a7768026605230461cdef30262e14",
|
||||
"cli/common.py": "7cc3dcdb7e43b67ba942487db8520c1d4a71392bc2a79c9cdc0e7ab0069b0166",
|
||||
"cli/fast_api.py": "6606e9f208a291cb8e9e065a966cebb1f50cadd2a739df5300066b31f190597b",
|
||||
"cli/gradio_app.py": "d882163a6d9b1071eae4164c95f98ddf2009c3535ff125002d343de68f9b632d",
|
||||
"cli/models_download.py": "2cd7e822952524cee6eea6f64a20b1b63303c388c82c142d67034fd89a18f355",
|
||||
"cli/vlm_server.py": "dbb1daa8edf0a4c5d203f9c0dc20ba24e0531cadeaeba48fd34703ea6f47b901",
|
||||
"cli/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"data/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"data/data_reader_writer/base.py": "9ea98071d1ce5cc3893ba4404f720b96280315ac3c3a9d124f20b0e723b301b2",
|
||||
"data/data_reader_writer/dummy.py": "312c5069938af22fa59643d70e7d3c92fbee22d7b9a0907fe25463af59a75ed0",
|
||||
"data/data_reader_writer/filebase.py": "8255d548927eb80fffa83d09feb7611d4d956043866a20b6824f52270ca73e3e",
|
||||
"data/data_reader_writer/multi_bucket_s3.py": "6f05488a65556a3d0c35e549a4d000ad6e35746caaaaf0b3abd259e8e85db298",
|
||||
"data/data_reader_writer/s3.py": "3707fc89c1d542a9bc448da7e00cf356ec0aef9775ab925956e0e97bbe028478",
|
||||
"data/data_reader_writer/__init__.py": "f6a9c636bb2e181330c1fb10cbaa0285d933fbe6bf2cf758584d15659af4cabe",
|
||||
"data/io/base.py": "4aa350a9edf466fa15be0ec656ffa12cc0a337ac81803c9041678b806b137e14",
|
||||
"data/io/http.py": "776f826411a330f3af7409240bdcf150429862264f80befa66a706e21203793d",
|
||||
"data/io/s3.py": "ddf0e2b4deeb1069f50ca0e48cab5fdb20baf260eb27eb55cb28bc55890d61e0",
|
||||
"data/io/__init__.py": "9a343f2c049a5fee3fa60fb5bb368c272b0812582552cde8f9a92aac03fc3024",
|
||||
"data/utils/exceptions.py": "a3116951056e9bc2d1140820d5c66f328378c604947bde6b80d0d4da6cd39707",
|
||||
"data/utils/path_utils.py": "ca47a8f965b5eb723618a016a34bc8a4fd4caedc08f7d3cfaad082d39ba1bd53",
|
||||
"data/utils/schemas.py": "30afe99d690aebd3119d56b29278b6b42472eacc7b71d09e3ebcbf5bb5148217",
|
||||
"data/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/layout/doclayoutyolo.py": "0edb4835dba5cd38987150e5ffbd280ed51d7d598673daa429699b3ce180795d",
|
||||
"model/layout/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/mfd/yolo_v8.py": "388e40c5582ddc5bd7a783589340435d7be90e5a3d62333a6f20f20bf4d9f09b",
|
||||
"model/mfd/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/mfr/utils.py": "a408b51e7913b8ed11eb6e751dd97ea39d26d301f409ef3d3c07fbe160ac5cf5",
|
||||
"model/mfr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/mfr/pp_formulanet_plus_m/predict_formula.py": "b586f1746fe834b6f5f02b1092eb1903eaf77f11d0775b839dfcc8150e88214e",
|
||||
"model/mfr/pp_formulanet_plus_m/processors.py": "3122b26a7c620c38e00d01c1a2ff868cab4f9ccc7db529b1042f462243377edf",
|
||||
"model/mfr/pp_formulanet_plus_m/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/mfr/unimernet/Unimernet.py": "64ad0cf5f3e667388ae03df71f760d0fb4671e2424455092fa5bcd7d8f8dedda",
|
||||
"model/mfr/unimernet/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/mfr/unimernet/unimernet_hf/modeling_unimernet.py": "fe5377cc32b17aab16fa1f6d5f1efd0d8893e6e4f83fd8b11b8f56ad260a1711",
|
||||
"model/mfr/unimernet/unimernet_hf/__init__.py": "907708486f064b84d6256df84822427a2d63c68e87c6f3b4d1a0b476ac8d1602",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py": "87045aaf7a6a37f715b374d14cd4ae841e3069c06771f27eaaf6936a345bd317",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py": "5e49cbe940f6b217dc12b003f242e4e754f2dcbb5bbfbb838bf6379311b58def",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py": "f53dab069c865f96054188fcf7e996ba346890ebb3e3180dade06e7a0720d7f7",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py": "397dde4542819ca097b7124e1b7b1d368075215f99ede7e0594fa069c9583860",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py": "6bd902bf0cc925246b29036d5b6a0ea53c2b6a9cdea7c06318558b84b1754f49",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py": "43f7dd9851d406d12801f5a9f5aa307704c213630814c38f6d88e84b25cada25",
|
||||
"model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py": "f3fd432b00c20d4064787622249e8c667a1d641b1ab476ea872821d75b3d7840",
|
||||
"model/ocr/pytorch_paddle.py": "707313979b0aca7e01636db4efeec643879997d05051cb39b9cc70fcd15ecc82",
|
||||
"model/ocr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/ori_cls/paddle_ori_cls.py": "5484b6d887ab1d24fb83ad000bdaf63c44081ba35059e41a1f53ab5c8c4d4ec8",
|
||||
"model/ori_cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/reading_order/layout_reader.py": "21550570d303177fa48a8f812318e9a479d64b77873eabef362848c367db2053",
|
||||
"model/reading_order/xycut.py": "7b3352abf6385178b3b41e7c85b5c9b234c994e06a5888ee5b9036b8b49a652a",
|
||||
"model/reading_order/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/table/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/table/cls/paddle_table_cls.py": "e4fb6278a42703380c3514d91609ea42c196293110df2c855909c14488df4380",
|
||||
"model/table/cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/table/rec/RapidTable.py": "d9d35d189b1576c19f466eabddd78445432cb79448c47d18ba21802e441b353c",
|
||||
"model/table/rec/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/table/rec/slanet_plus/main.py": "bdfadcbd0f4905fdf661953d78da1eb68a9da5cac536c03558da9006c1bc8b6a",
|
||||
"model/table/rec/slanet_plus/matcher.py": "bb017ec022da625690dc943ff98cb01959755d0627c7b1bf453b962d6f099419",
|
||||
"model/table/rec/slanet_plus/matcher_utils.py": "f70b7fc9d79e5622dde7b6d4ea0de59d75e78b8f6a2d2adad82eb0485419922c",
|
||||
"model/table/rec/slanet_plus/table_structure.py": "aadf873d8210ca9d1a586fcc9a733fb0c40257c64b6f8ac02d2b9ec82a213e03",
|
||||
"model/table/rec/slanet_plus/table_structure_utils.py": "6184a4c0dd9674bc7baa458c48690f63bc97387e44355860e42b111a1b59e569",
|
||||
"model/table/rec/slanet_plus/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/table/rec/unet_table/main.py": "275dd0effeacb58c9e76655e75ff42643ed1d2dba0b867d3837677a1be060ee3",
|
||||
"model/table/rec/unet_table/table_recover.py": "ad2c9e5b2b8fd7433c74b280e5ed27e0fd835cc61b55b9a02f111c75903cff41",
|
||||
"model/table/rec/unet_table/table_structure_unet.py": "8679982f36454652b463882bf3be06f4668b6a170a9cd65836e9fcebd15d987f",
|
||||
"model/table/rec/unet_table/utils.py": "09802a256d3078f264e0d01e99bf16db4dcdec4df6bf4ba38966f16a70e177c2",
|
||||
"model/table/rec/unet_table/utils_table_line_rec.py": "eb3d2360ee92f300267c77b9b40c847f3599210bfcc2b9ff75153d182ee82aba",
|
||||
"model/table/rec/unet_table/utils_table_recover.py": "5e4b09b18f36652d24a949cd4fe8ef698cf1277577b2f312ce3d29bb021abb59",
|
||||
"model/table/rec/unet_table/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/utils/pytorchocr/base_ocr_v20.py": "e5b23b300bbae6bfaf9f6f24af0749ea98d932412f5a3b2913b110693b11111c",
|
||||
"model/utils/pytorchocr/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/utils/pytorchocr/data/__init__.py": "618bb773e5b87e0104af1c4333df2e437a16c0f121fbac3be4b638cdc8f856d3",
|
||||
"model/utils/pytorchocr/data/imaug/operators.py": "79d05a0de7b39910241a476e3c5e8859c529136597461ee6011a929f0cb29c40",
|
||||
"model/utils/pytorchocr/data/imaug/__init__.py": "7381f48173d1c1e434c0c16792b08b4d1e8caed1be7b89148a7c70ab61b557d5",
|
||||
"model/utils/pytorchocr/modeling/common.py": "debda34ef3d8412e08813bc8a91e25e9b055c11ee39fef3bad29a9bf7b65ab12",
|
||||
"model/utils/pytorchocr/modeling/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/utils/pytorchocr/modeling/architectures/base_model.py": "4615760e6fa8b34f24085ca54f9ef346eef61eafd125d172df141ed4c3da0ae5",
|
||||
"model/utils/pytorchocr/modeling/architectures/__init__.py": "0c203d152e26139a021c3941854ae460b77115e4086e13e3e0ff2827f811643f",
|
||||
"model/utils/pytorchocr/modeling/backbones/det_mobilenet_v3.py": "af48169c0d579add19c381502f1ee47fe596c1977fdba3df37384cd3976b72e1",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_donut_swin.py": "9530a37bb98fb84f9f1ded3901325ee42efbc319340914e8940b43fe07d04e68",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_hgnet.py": "52c21bcea37f928c86a128754c0f6bdbb4a08291db78a4b71e6992f80d80c34e",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_lcnetv3.py": "f954734cfb6becb4e6c09e1d0adb08fbe803f35600761de59556aef4ae159dcf",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_mobilenet_v3.py": "989984eb11a98c7647d956b0d7a2e5225a911459bd47dc91b122446b7627de7c",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_mv1_enhance.py": "2b8a7d28560d9a5b55df2dd0b311c8012371a2a946b71800a02c5e1687f20a6c",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_pphgnetv2.py": "61fa75c51e5286ce5bd6ec468e1152ad880fabd065dcda20612a3e28e26ed3c9",
|
||||
"model/utils/pytorchocr/modeling/backbones/rec_svtrnet.py": "008694677216064473da95a66a70634b441d25c6278a6312578316a1f36941c8",
|
||||
"model/utils/pytorchocr/modeling/backbones/__init__.py": "74e9aa86f2eb04cfb68a6730b7bde44ba00f98c6e1a15613a33966a8e9117ea0",
|
||||
"model/utils/pytorchocr/modeling/heads/cls_head.py": "a6e232e46954b4029eafa792e0758abb4ecfcd177e1e50c0a88cf95aa8c11da0",
|
||||
"model/utils/pytorchocr/modeling/heads/det_db_head.py": "fa4f1ba6e190c3fc48543b2e9ab7e298ec60d0efa83f630e0320c94e353bd11a",
|
||||
"model/utils/pytorchocr/modeling/heads/rec_ctc_head.py": "cb0ca4e512605084dd5efad4664db205258ab1a648aa74e87dd15bb9052dc235",
|
||||
"model/utils/pytorchocr/modeling/heads/rec_multi_head.py": "2b8d12300f2d0155aefb77f081f8778c659e54501d5673321e3799788f4e3bb4",
|
||||
"model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py": "e5c2c951ab032ab6020b8ef34f1d83e4eb25e829cf87a24099dc1beac69e0d68",
|
||||
"model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py": "c2c1f16445f654eea43442d1e37794325796257ac352070fe672d67cd22b33e1",
|
||||
"model/utils/pytorchocr/modeling/heads/__init__.py": "7650d6008083ff73eb622862a421c33f91822551fff9fc128fb59fa237c808ca",
|
||||
"model/utils/pytorchocr/modeling/necks/db_fpn.py": "4cb176a52caf442d283f32f4795c8d960dd6e99bdfaf827c7c3d67ce2541eee2",
|
||||
"model/utils/pytorchocr/modeling/necks/intracl.py": "c3641dc1d23d069896f76552e26a8bdf5b1511121b639dd37db0f943aa2489a6",
|
||||
"model/utils/pytorchocr/modeling/necks/rnn.py": "4c052ae267b883fc97c5ab79c053a0193aa7a82d9450ad456762defb61162aa0",
|
||||
"model/utils/pytorchocr/modeling/necks/__init__.py": "eb7e0bd72f905afe4ff28a4d89298abd0131dd4b24736d111bc0d888275b97c5",
|
||||
"model/utils/pytorchocr/postprocess/cls_postprocess.py": "d555565d3fdbd6f8466fb3c6beac9f510dc8a7b2eea47eb6bcfbdaf7c1ad8d30",
|
||||
"model/utils/pytorchocr/postprocess/db_postprocess.py": "01d64f17b7eb850dbb555769d0616631c5ed8afc036597d7621cc93a53f8cd4b",
|
||||
"model/utils/pytorchocr/postprocess/rec_postprocess.py": "a86077a271441611e3aa4b0847520a3b1d8463df1ec1fb268c00e3ad15e0df46",
|
||||
"model/utils/pytorchocr/postprocess/__init__.py": "882d4e97a093c51599054c90ff9215311ea422eaeff5624f3965a8ecd02e6410",
|
||||
"model/utils/pytorchocr/utils/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"model/utils/pytorchocr/utils/resources/arch_config.yaml": "06f697b075d7572c5838562392dec7b72656884c8baef1ec1ec2587d06528436",
|
||||
"model/utils/pytorchocr/utils/resources/models_config.yml": "408baa7aef75a5fbaac9ae096f199941290e6247be876073db53b6a4e2d03d87",
|
||||
"model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml": "6bbcae78e4d4adfa59a3c0ac2babd0a246cb341d89f8fefb8a168287f2e8cef4",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ka_dict.txt": "fad3f765943275eec2134a6fbc9b52785426641104d4e7db3a159dc73f341dde",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt": "a5bc3887c43c901e5a3f97b13ffadf1c5754ede7cc8c9f5abe22e875a7c48372",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt": "7f92f7dbb9b75a4787a83bfb4f6d14a8ab515525130c9d40a9036f61cf6999e9",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt": "db40aa52ceb112055be80c694afdf655d5d2c4f7873704524cc16a447ca913ba",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt": "09c7440bfc5477e5c41052304b6b185aff8c4a5e8b2b4c23c1c706f6fe1ee9fc",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_dict.txt": "d1979e9f794c464c0d2e0b70a7fe14dd978e9dc644c0e71f14158cdf8342af1b",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt": "31defc62c0c3ad3674a82da6192226a2ba98ef4ff014a7045cb88d59f9c3de31",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_en_dict.txt": "e025a66d31f327ba0c232e03f407ae8d105e1e709e7ccb3f408aa778c24e70d6",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt": "3e95f1581557162870cacdba5af91a4c6be2890710d395b0c3c7578e7ee5e6eb",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt": "a88071c68c01707489baa79ebe0405b7beb5cca229f4fc94cc3ef992328802d7",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_latin_dict.txt": "ccbcc45730b3fbbd9050c5bc74db6a99067141ef1035e3d14889a84a6b9b1aff",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt": "85b541352ae18dc6ba6d47152d8bf8adff6b0266e605d2eef2990c1bf466117b",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt": "42f83f5d3fdb50778e4fa5b66c58d99a59ab7792151c5e74f34b8ffd7b61c9d6",
|
||||
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt": "57f5406f94bb6688fb7077f7be65f08bbd71cecf48c01ea26c522cb5c4836b7a",
|
||||
"model/utils/tools/__init__.py": "c44a91eb967c60ecce2e8acb8cad0b087a2cdb35feb42bb14abc67763534d211",
|
||||
"model/utils/tools/infer/predict_cls.py": "f1198a975bde8e7665eb971a1d9355dad6ba84cb20e41fcb13e16ea823bc4fc0",
|
||||
"model/utils/tools/infer/predict_det.py": "bd8411127eef10b5f106cafbd8208256f9b583057cd8e35a0b019fc542239def",
|
||||
"model/utils/tools/infer/predict_rec.py": "f811fddc90e2b2ed244fa0b21c0e2995438a71bd8bf94bc393b4de8a7e6ec2de",
|
||||
"model/utils/tools/infer/predict_system.py": "8647a0927ea1ab6bf6cea1d500feb5e7e93e7e44d2f2cc116126d97a8aa6488f",
|
||||
"model/utils/tools/infer/pytorchocr_utility.py": "8b53c537efe479f254519e1593b8a0b354d4f207c4ad30e50d763afbc51ababc",
|
||||
"model/utils/tools/infer/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
|
||||
"model/vlm/lmdeploy_server.py": "3efc4935c508281f15cd63035de575b744874a0cff50b3b7e9903325ba69cfdd",
|
||||
"model/vlm/vllm_server.py": "802e1b93005b9d05e99b16a2ab59cf7fb460585fa95181128cbb2cbde26ae83a",
|
||||
"model/vlm/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"resources/header.html": "ef1adfe9b1a5a11fb765e4c3c80f89bdabc4fcd791b940dede9d3b7042945d22",
|
||||
"resources/fasttext-langdetect/lid.176.ftz": "e33db98de5d095f003b0645244841d33b0763864daf8d0516ae3cc1cfa759a56",
|
||||
"utils/block_pre_proc.py": "b86066c5fd8c47d6e99539d023cc478c223e923de9951849af485c58a89d6ce4",
|
||||
"utils/block_sort.py": "e52d5576946023bd83d9d45bdd0a795d08aa4a688fa442f0148a9ba6c847d630",
|
||||
"utils/boxbase.py": "c67180d64ee156d4d0aeb7aa94998af92037cbd79d4c780b9868aa1ab4977241",
|
||||
"utils/char_utils.py": "ef84f9625af99a2d6e75d008b8992ef59eac1fbbe147bb79f79fc7eea99bbb87",
|
||||
"utils/check_sys_env.py": "4d18f3838c56ca8486ae0bf829a3f6db903ef7dc4180b01f67570f706aab0400",
|
||||
"utils/cli_parser.py": "e2c78502ed64ba5b189f0e96336abf7318043addad12b655908f8b34417f906c",
|
||||
"utils/config_reader.py": "d37012a89509225e8291755cb1ec299cf0c0a3d23b598763fe1c7ea2c50aae51",
|
||||
"utils/cut_image.py": "8379b89df7093569718be3f49295d3b659aca5790c70b09f1b0998b90f99da11",
|
||||
"utils/draw_bbox.py": "164829a6353346137ebb1bc285d9211d77036af244680a4c0faa82eaaa11c1f4",
|
||||
"utils/engine_utils.py": "2666a8f7e3beb190f31fbbc034a103698e8d27cb6eb612ac4ebdb72c521e04b5",
|
||||
"utils/enum_class.py": "59e8edef35fe11b9af40cfda8883c24b870537f2b4fbc398ce53b93f2cacba07",
|
||||
"utils/format_utils.py": "dacf3dbc77122128eea2593c1ef8372bee7ead16e24f752cede14bcd42ab34ab",
|
||||
"utils/guess_suffix_or_lang.py": "6940b6c002706b92c7d121f1c136ce109a95560be9754096145ea87fc7835647",
|
||||
"utils/hash_utils.py": "50f4bff0d441995ba67723afd7a2e6bfa2f2db12bc3950c911ee601ba80a2059",
|
||||
"utils/language.py": "ed14f79b149aee3769a02e7249ded975d1c0ed33bb52c9e60ce5a2619031bb28",
|
||||
"utils/llm_aided.py": "f56532b6fc5e9d202e696478b1342154f43987ca58d3054e1f53b6b23ffa74bb",
|
||||
"utils/magic_model_utils.py": "f07bfe04393d133e13531ea1ad527febbe726598203e3e9489bf35952a66d228",
|
||||
"utils/models_download_utils.py": "51f8efc21c4ee819091dae494a9115359ef51a82cc3cc989a729b74c7113d93e",
|
||||
"utils/model_utils.py": "61a77136e46fb96679c96d8d912a43d1961325d8f46554b65fc285fe19465820",
|
||||
"utils/ocr_utils.py": "94f22bc0d5226f99abcd4929a274581ee502763576aaf11334b4b338bc9f96b5",
|
||||
"utils/os_env_config.py": "5472bd952dd014986bc166bd14e154d52c26ee85e76f2e1268d3634f2a274d38",
|
||||
"utils/pdf_classify.py": "e83179a47ffd52af377ec16da7b9f88be39d6101b3a0d395f4bd1505486004c4",
|
||||
"utils/pdf_image_tools.py": "b534a4dfd7e024a2c4b21c0f02e2462e5fe9552ae610a8d6039e45e9d19caf88",
|
||||
"utils/pdf_page_id.py": "7a6f7aea4d760915b8463e3d44688b07ff082f09173c19d645eb40a5ac77793b",
|
||||
"utils/pdf_reader.py": "59e20d9b94b25815174f4c0ff65cc86de1ecf0fe9650890dea754be57e0bcc6e",
|
||||
"utils/pdf_text_tool.py": "284ced8df76ab081c7ba24c400c00becbaf5392dd1ed4afeb93a8688246345e4",
|
||||
"utils/run_async.py": "acf78fe010997ab47c541c910e1898cdf6626a12d5aa8644055012e787408cd8",
|
||||
"utils/span_block_fix.py": "d1e5508c90ab4f4df0a11b7d86887a52ee364e9d5d69c7c64efdb1dc1f6aabde",
|
||||
"utils/span_pre_proc.py": "9eee818794d63ca1731ee15f6c4b3402caf4e0ce3138be4838dcfff062479f8e",
|
||||
"utils/table_merge.py": "2ce471cf44c77a60aa1fbe3a14c562a84b8bcccd3cf0ce07808904bb00c87cd5",
|
||||
"utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
# MinerU 2.7.6
|
||||
|
||||
本分支基于官方 PyPI 2.7.6,原始包校验值及文件清单见 `2.7.6-baseline.json`。
|
||||
保留 Word 转 PDF、解析进度、Gradio/独立导图页面及导图整理接口。
|
||||
解析内核使用 2.7.6 的跨页表格、PDF 超时和国产卡适配修复。
|
||||
|
||||
## 六级标题和 MaxKB
|
||||
|
||||
Pipeline、VLM 的 Markdown 与 content-list 输出保留一级至六级标题。
|
||||
可选的 LLM 辅助标题分级提示也允许六级。实际识别结果取决于文档和启用的分级方式。
|
||||
|
||||
MaxKB 新建解析资源选择 V2,默认版本为 2.7.6。
|
||||
服务地址填写 API 基址,例如 `http://parser-host:8100`。
|
||||
`POST /file_parse` 和独立页面使用的 `POST /api/file_parse` 指向同一处理函数。
|
||||
响应按请求返回 Markdown、middle_json、model_output、content_list、Base64 图片。
|
||||
MaxKB 保留原有 2.7.1、2.7.4、3.4.5、4.x 资源的版本定义。
|
||||
|
||||
## 构建
|
||||
|
||||
在仓库根目录执行。Docker 命令需有相应权限。
|
||||
|
||||
```bash
|
||||
API_FLAVOR=cuda bash scripts/build-images.sh
|
||||
API_FLAVOR=corex bash scripts/build-images.sh
|
||||
```
|
||||
|
||||
NVIDIA API 镜像为 `unis-mindmap-api:2.7.6-cuda`,使用 vLLM 0.11.2 配套基础镜像。
|
||||
天数 API 镜像为 `unis-mindmap-api:2.7.6-corex`,使用厂商 CoreX 4.4.0、Torch 2.7.1、vLLM 0.11.2、Python 3.10 基础镜像。
|
||||
独立页面镜像为 `unis-mindmap-web:2.7.6`。
|
||||
|
||||
API 镜像从本仓库安装 `.[core]`,并约束 `mineru==2.7.6`。
|
||||
安装前记录基础镜像的 Torch、torchvision、vLLM 等版本,作为 pip 约束,安装后再次核对并运行 `pip check`。
|
||||
新增依赖包括 Word 备用转换所需的 python-docx 和 Pydantic 2。
|
||||
CoreX 与 CUDA 的依赖解析冲突会使构建失败,日志会保留 pip 的冲突原因。
|
||||
|
||||
## 准备模型和启动
|
||||
|
||||
先准备与 MinerU 2.7.6 对应的 Pipeline、VLM 权重。
|
||||
`MINERU_MODEL_DIR` 下使用 `pipeline`、`vlm` 两个目录,分别放对应模型仓库的根内容。
|
||||
构建和启动过程使用挂载的本地模型。
|
||||
|
||||
```bash
|
||||
API_FLAVOR=cuda GPU_IDS=0 MINERU_MODEL_DIR=/data/unis/mineru-models bash scripts/start-mindmap.sh
|
||||
API_FLAVOR=corex GPU_IDS=0 MINERU_MODEL_DIR=/data/unis/mineru-models bash scripts/start-mindmap.sh
|
||||
```
|
||||
|
||||
脚本默认使用容器名 `mineru-276-api`、`mindmap-276-web`。
|
||||
API 映射至宿主机 `127.0.0.1:8100`,页面端口为 `9898`。
|
||||
可通过 `API_NAME`、`WEB_NAME`、`API_PORT`、`WEB_PORT` 调整。
|
||||
已有同名容器时脚本退出,由运维显式管理旧容器。
|
||||
天数启动传递 `MINERU_VLLM_DEVICE=corex`,并挂载厂商运行所需的设备和内核目录。
|
||||
|
||||
可挂载 `MINERU_TOOLS_CONFIG_JSON` 指定的 JSON 配置。
|
||||
入口保留已有配置,并补齐缺失的模型目录。
|
||||
`MINERU_PIPELINE_MODEL_DIR`、`MINERU_VLM_MODEL_DIR` 可分别覆盖模型路径。
|
||||
`MINERU_GPU_MEMORY_UTILIZATION` 默认 `0.5`,用于 vLLM 显存预算。
|
||||
API 默认单请求并发,`MINERU_API_MAX_CONCURRENT_REQUESTS` 可配置上限。
|
||||
|
||||
## 检查
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests/unittest -p test_parser_276.py -v
|
||||
python -m build --wheel
|
||||
```
|
||||
|
||||
协议测试模拟推理输出,检查 HTTP 协议和标题保留。
|
||||
目标卡验收需另行检查实际驱动、模型加载、PDF/OCR、显存和并发行为。
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
Metadata-Version: 2.4
|
||||
Name: mineru
|
||||
Version: 2.7.1
|
||||
Version: 2.7.6
|
||||
Summary: A practical tool for converting PDF to Markdown
|
||||
License: AGPL-3.0
|
||||
Project-URL: homepage, https://mineru.net/
|
||||
|
|
@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|||
Classifier: Programming Language :: Python :: 3.13
|
||||
Requires-Python: <3.14,>=3.10
|
||||
Description-Content-Type: text/markdown
|
||||
License-File: LICENSE.md
|
||||
Requires-Dist: boto3>=1.28.43
|
||||
Requires-Dist: click>=8.1.7
|
||||
Requires-Dist: loguru>=0.7.2
|
||||
|
|
@ -26,6 +27,8 @@ Requires-Dist: pillow>=11.0.0
|
|||
Requires-Dist: pypdfium2>=4.30.0
|
||||
Requires-Dist: pypdf>=5.6.0
|
||||
Requires-Dist: reportlab
|
||||
Requires-Dist: python-docx<2,>=1.2
|
||||
Requires-Dist: pydantic<3,>=2.12
|
||||
Requires-Dist: pdftext>=0.6.3
|
||||
Requires-Dist: modelscope>=1.26.0
|
||||
Requires-Dist: huggingface-hub>=0.32.4
|
||||
|
|
@ -59,7 +62,7 @@ Requires-Dist: matplotlib<4,>=3.10; extra == "pipeline"
|
|||
Requires-Dist: ultralytics<9,>=8.3.48; extra == "pipeline"
|
||||
Requires-Dist: doclayout_yolo==0.0.4; extra == "pipeline"
|
||||
Requires-Dist: dill<1,>=0.3.8; extra == "pipeline"
|
||||
Requires-Dist: PyYAML<7,>=6.0.2; extra == "pipeline"
|
||||
Requires-Dist: PyYAML<7,>=6.0.1; extra == "pipeline"
|
||||
Requires-Dist: ftfy<7,>=6.3.1; extra == "pipeline"
|
||||
Requires-Dist: shapely<3,>=2.0.7; extra == "pipeline"
|
||||
Requires-Dist: pyclipper<2,>=1.3.0; extra == "pipeline"
|
||||
|
|
@ -75,9 +78,6 @@ Requires-Dist: uvicorn; extra == "api"
|
|||
Provides-Extra: gradio
|
||||
Requires-Dist: gradio==5.49.1; extra == "gradio"
|
||||
Requires-Dist: gradio-pdf==0.0.22; extra == "gradio"
|
||||
Provides-Extra: vuex
|
||||
Requires-Dist: nodejs>=16.0.0; extra == "vuex"
|
||||
Requires-Dist: npm>=8.0.0; extra == "vuex"
|
||||
Provides-Extra: core
|
||||
Requires-Dist: mineru[vlm]; extra == "core"
|
||||
Requires-Dist: mineru[pipeline]; extra == "core"
|
||||
|
|
@ -87,4 +87,8 @@ Provides-Extra: all
|
|||
Requires-Dist: mineru[core]; extra == "all"
|
||||
Requires-Dist: mineru[mlx]; sys_platform == "darwin" and extra == "all"
|
||||
Requires-Dist: mineru[vllm]; sys_platform == "linux" and extra == "all"
|
||||
Requires-Dist: mineru[lmdeploy]; sys_platform == "windows" and extra == "all"
|
||||
Requires-Dist: mineru[lmdeploy]; sys_platform == "win32" and extra == "all"
|
||||
Dynamic: license-file
|
||||
|
||||
|
||||
markitdown
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
LICENSE.md
|
||||
README.md
|
||||
pyproject.toml
|
||||
mineru/__init__.py
|
||||
mineru/version.py
|
||||
|
|
@ -36,6 +38,22 @@ mineru/cli/fast_api.py
|
|||
mineru/cli/gradio_app.py
|
||||
mineru/cli/models_download.py
|
||||
mineru/cli/vlm_server.py
|
||||
mineru/cli/static/markmap/d3.min.js
|
||||
mineru/cli/static/markmap/markmap-lib.js
|
||||
mineru/cli/static/markmap/markmap-toolbar.js
|
||||
mineru/cli/static/markmap/markmap-view.js
|
||||
mineru/cli/static/web/index.html
|
||||
mineru/cli/static/web/assets/index-B_viQAxH.css
|
||||
mineru/cli/static/web/assets/index-CxJ0NebI.css
|
||||
mineru/cli/static/web/assets/index-D7YNJWSR.js
|
||||
mineru/cli/static/web/assets/index-zcV97yfy.js
|
||||
mineru/cli/static/web/assets/markdown-_Dy2zPzC.js
|
||||
mineru/cli/static/web/assets/vendor-DDOvA1Mb.js
|
||||
mineru/cli/static/web/assets/vendor-DSv9k51x.js
|
||||
mineru/cli/static/web/markmap/d3.min.js
|
||||
mineru/cli/static/web/markmap/markmap-lib.js
|
||||
mineru/cli/static/web/markmap/markmap-toolbar.js
|
||||
mineru/cli/static/web/markmap/markmap-view.js
|
||||
mineru/data/__init__.py
|
||||
mineru/data/data_reader_writer/__init__.py
|
||||
mineru/data/data_reader_writer/base.py
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
[console_scripts]
|
||||
mineru = mineru.cli:client.main
|
||||
mineru = mineru.cli.client:main
|
||||
mineru-api = mineru.cli.fast_api:main
|
||||
mineru-gradio = mineru.cli.gradio_app:main
|
||||
mineru-lmdeploy-server = mineru.cli.vlm_server:lmdeploy_server
|
||||
mineru-models-download = mineru.cli.models_download:download_models
|
||||
mineru-openai-server = mineru.cli.vlm_server:openai_server
|
||||
mineru-vllm-server = mineru.cli.vlm_server:vllm_server
|
||||
mineru-vue-dev = web_ui:start.sh
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ pillow>=11.0.0
|
|||
pypdfium2>=4.30.0
|
||||
pypdf>=5.6.0
|
||||
reportlab
|
||||
python-docx<2,>=1.2
|
||||
pydantic<3,>=2.12
|
||||
pdftext>=0.6.3
|
||||
modelscope>=1.26.0
|
||||
huggingface-hub>=0.32.4
|
||||
|
|
@ -32,7 +34,7 @@ mineru[mlx]
|
|||
[all:sys_platform == "linux"]
|
||||
mineru[vllm]
|
||||
|
||||
[all:sys_platform == "windows"]
|
||||
[all:sys_platform == "win32"]
|
||||
mineru[lmdeploy]
|
||||
|
||||
[api]
|
||||
|
|
@ -61,7 +63,7 @@ matplotlib<4,>=3.10
|
|||
ultralytics<9,>=8.3.48
|
||||
doclayout_yolo==0.0.4
|
||||
dill<1,>=0.3.8
|
||||
PyYAML<7,>=6.0.2
|
||||
PyYAML<7,>=6.0.1
|
||||
ftfy<7,>=6.3.1
|
||||
shapely<3,>=2.0.7
|
||||
pyclipper<2,>=1.3.0
|
||||
|
|
@ -85,7 +87,3 @@ vllm<0.12,>=0.10.1.1
|
|||
torch<3,>=2.6.0
|
||||
transformers!=4.57.2,<5.0.0,>=4.51.1
|
||||
accelerate>=1.5.1
|
||||
|
||||
[vuex]
|
||||
nodejs>=16.0.0
|
||||
npm>=8.0.0
|
||||
|
|
|
|||
|
|
@ -424,7 +424,8 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
|
|||
# 调用通用方法
|
||||
return tie_up_category_by_index(
|
||||
get_subjects,
|
||||
get_objects
|
||||
get_objects,
|
||||
object_block_type=object_block_type
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -297,7 +297,14 @@ def ocr_det_batch_setting(device):
|
|||
# 检测torch的版本号
|
||||
import torch
|
||||
from packaging import version
|
||||
if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'):
|
||||
|
||||
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
|
||||
|
||||
if (
|
||||
version.parse(torch.__version__) >= version.parse("2.8.0")
|
||||
or str(device).startswith('mps')
|
||||
or device_type.lower() in ["corex"]
|
||||
):
|
||||
enable_ocr_det_batch = False
|
||||
else:
|
||||
enable_ocr_det_batch = True
|
||||
|
|
|
|||
|
|
@ -193,7 +193,12 @@ def batch_image_analyze(
|
|||
# 检测torch的版本号
|
||||
import torch
|
||||
from packaging import version
|
||||
if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'):
|
||||
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
|
||||
if (
|
||||
version.parse(torch.__version__) >= version.parse("2.8.0")
|
||||
or str(device).startswith('mps')
|
||||
or device_type.lower() in ["corex"]
|
||||
):
|
||||
enable_ocr_det_batch = False
|
||||
else:
|
||||
enable_ocr_det_batch = True
|
||||
|
|
|
|||
|
|
@ -296,8 +296,8 @@ def union_make(pdf_info_dict: list,
|
|||
|
||||
def get_title_level(block):
|
||||
title_level = block.get('level', 1)
|
||||
if title_level > 4:
|
||||
title_level = 4
|
||||
if title_level > 6:
|
||||
title_level = 6
|
||||
elif title_level < 1:
|
||||
title_level = 0
|
||||
return title_level
|
||||
|
|
|
|||
|
|
@ -18,6 +18,15 @@ def enable_custom_logits_processors() -> bool:
|
|||
compute_capability = f"{major}.{minor}"
|
||||
elif hasattr(torch, 'npu') and torch.npu.is_available():
|
||||
compute_capability = "8.0"
|
||||
elif hasattr(torch, 'gcu') and torch.gcu.is_available():
|
||||
compute_capability = "8.0"
|
||||
elif hasattr(torch, 'musa') and torch.musa.is_available():
|
||||
compute_capability = "8.0"
|
||||
elif hasattr(torch, 'mlu') and torch.mlu.is_available():
|
||||
compute_capability = "8.0"
|
||||
elif hasattr(torch, 'sdaa') and torch.sdaa.is_available():
|
||||
compute_capability = "8.0"
|
||||
|
||||
else:
|
||||
logger.info("CUDA not available, disabling custom_logits_processors")
|
||||
return False
|
||||
|
|
@ -96,4 +105,128 @@ def set_default_batch_size() -> int:
|
|||
except Exception as e:
|
||||
logger.warning(f'Error determining VRAM: {e}, using default batch_ratio: 1')
|
||||
batch_size = 1
|
||||
return batch_size
|
||||
return batch_size
|
||||
|
||||
|
||||
def _get_device_config(device_type: str) -> dict | None:
|
||||
"""获取不同设备类型的配置参数"""
|
||||
|
||||
# 各设备类型的配置定义
|
||||
DEVICE_CONFIGS = {
|
||||
# "musa": {
|
||||
# "compilation_config_dict": {
|
||||
# "cudagraph_capture_sizes": [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30],
|
||||
# "simple_cuda_graph": True
|
||||
# },
|
||||
# "block_size": 32,
|
||||
# },
|
||||
"corex": {
|
||||
"compilation_config_dict": {
|
||||
"cudagraph_mode": "FULL_DECODE_ONLY",
|
||||
"level": 0
|
||||
},
|
||||
},
|
||||
"kxpu": {
|
||||
"compilation_config_dict": {
|
||||
"splitting_ops": [
|
||||
"vllm.unified_attention", "vllm.unified_attention_with_output",
|
||||
"vllm.unified_attention_with_output_kunlun", "vllm.mamba_mixer2",
|
||||
"vllm.mamba_mixer", "vllm.short_conv", "vllm.linear_attention",
|
||||
"vllm.plamo2_mamba_mixer", "vllm.gdn_attention", "vllm.sparse_attn_indexer"
|
||||
]
|
||||
},
|
||||
"block_size": 128,
|
||||
"dtype": "float16",
|
||||
"distributed_executor_backend": "mp",
|
||||
"enable_chunked_prefill": False,
|
||||
"enable_prefix_caching": False,
|
||||
},
|
||||
}
|
||||
|
||||
return DEVICE_CONFIGS.get(device_type.lower())
|
||||
|
||||
|
||||
def _check_server_arg_exists(args: list, arg_name: str) -> bool:
|
||||
"""检查命令行参数列表中是否已存在指定参数"""
|
||||
return any(arg == f"--{arg_name}" or arg.startswith(f"--{arg_name}=") for arg in args)
|
||||
|
||||
|
||||
def _add_server_arg_if_missing(args: list, arg_name: str, value: str) -> None:
|
||||
"""如果参数不存在,则添加到命令行参数列表"""
|
||||
if not _check_server_arg_exists(args, arg_name):
|
||||
args.extend([f"--{arg_name}", value])
|
||||
|
||||
|
||||
def _add_server_flag_if_missing(args: list, flag_name: str) -> None:
|
||||
"""如果 flag 不存在,则添加到命令行参数列表"""
|
||||
if not _check_server_arg_exists(args, flag_name):
|
||||
args.append(f"--{flag_name}")
|
||||
|
||||
|
||||
def _add_engine_kwarg_if_missing(kwargs: dict, key: str, value) -> None:
|
||||
"""如果参数不存在,则添加到 kwargs 字典"""
|
||||
if key not in kwargs:
|
||||
kwargs[key] = value
|
||||
|
||||
|
||||
def mod_kwargs_by_device_type(kwargs_or_args: dict | list, vllm_mode: str) -> dict | list:
|
||||
"""根据设备类型修改 vllm 配置参数
|
||||
|
||||
Args:
|
||||
kwargs_or_args: 配置参数,server 模式为 list,engine 模式为 dict
|
||||
vllm_mode: vllm 运行模式 ("server", "sync_engine", "async_engine")
|
||||
|
||||
Returns:
|
||||
修改后的配置参数
|
||||
"""
|
||||
device_type = os.getenv("MINERU_VLLM_DEVICE", "")
|
||||
config = _get_device_config(device_type)
|
||||
|
||||
if config is None:
|
||||
return kwargs_or_args
|
||||
|
||||
if vllm_mode == "server":
|
||||
_apply_server_config(kwargs_or_args, config)
|
||||
else:
|
||||
_apply_engine_config(kwargs_or_args, config, vllm_mode)
|
||||
|
||||
return kwargs_or_args
|
||||
|
||||
|
||||
def _apply_server_config(args: list, config: dict) -> None:
|
||||
"""应用 server 模式的配置"""
|
||||
import json
|
||||
|
||||
for key, value in config.items():
|
||||
if key == "compilation_config_dict":
|
||||
_add_server_arg_if_missing(
|
||||
args, "compilation-config",
|
||||
json.dumps(value, separators=(',', ':'))
|
||||
)
|
||||
else:
|
||||
# 转换 key 格式: block_size -> block-size
|
||||
arg_name = key.replace("_", "-")
|
||||
if arg_name in {"enable-chunked-prefill", "enable-prefix-caching"} and value is False:
|
||||
_add_server_flag_if_missing(args, f"no-{arg_name}")
|
||||
continue
|
||||
_add_server_arg_if_missing(args, arg_name, str(value))
|
||||
|
||||
|
||||
def _apply_engine_config(kwargs: dict, config: dict, vllm_mode: str) -> None:
|
||||
"""应用 engine 模式的配置"""
|
||||
try:
|
||||
from vllm.config import CompilationConfig
|
||||
except ImportError:
|
||||
raise ImportError("Please install vllm to use the vllm-async-engine backend.")
|
||||
|
||||
for key, value in config.items():
|
||||
if key == "compilation_config_dict":
|
||||
if vllm_mode == "sync_engine":
|
||||
compilation_config = value
|
||||
elif vllm_mode == "async_engine":
|
||||
compilation_config = CompilationConfig(**value)
|
||||
else:
|
||||
continue
|
||||
_add_engine_kwarg_if_missing(kwargs, "compilation_config", compilation_config)
|
||||
else:
|
||||
_add_engine_kwarg_if_missing(kwargs, key, value)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
# Copyright (c) Opendatalab. All rights reserved.
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from .utils import enable_custom_logits_processors, set_default_gpu_memory_utilization, set_default_batch_size, \
|
||||
set_lmdeploy_backend
|
||||
set_lmdeploy_backend, mod_kwargs_by_device_type
|
||||
from .model_output_to_middle_json import result_to_middle_json
|
||||
from ...data.data_reader_writer import DataWriter
|
||||
from mineru.utils.pdf_image_tools import load_images_from_pdf
|
||||
|
|
@ -99,6 +100,17 @@ class ModelSingleton:
|
|||
import vllm
|
||||
except ImportError:
|
||||
raise ImportError("Please install vllm to use the vllm-engine backend.")
|
||||
|
||||
kwargs = mod_kwargs_by_device_type(kwargs, vllm_mode="sync_engine")
|
||||
|
||||
if "compilation_config" in kwargs:
|
||||
if isinstance(kwargs["compilation_config"], str):
|
||||
try:
|
||||
kwargs["compilation_config"] = json.loads(kwargs["compilation_config"])
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(
|
||||
f"Failed to parse compilation_config as JSON: {kwargs['compilation_config']}")
|
||||
del kwargs["compilation_config"]
|
||||
if "gpu_memory_utilization" not in kwargs:
|
||||
kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
|
||||
if "model" not in kwargs:
|
||||
|
|
@ -112,8 +124,25 @@ class ModelSingleton:
|
|||
try:
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.config import CompilationConfig
|
||||
except ImportError:
|
||||
raise ImportError("Please install vllm to use the vllm-async-engine backend.")
|
||||
|
||||
kwargs = mod_kwargs_by_device_type(kwargs, vllm_mode="async_engine")
|
||||
|
||||
if "compilation_config" in kwargs:
|
||||
if isinstance(kwargs["compilation_config"], dict):
|
||||
# 如果是字典,转换为 CompilationConfig 对象
|
||||
kwargs["compilation_config"] = CompilationConfig(**kwargs["compilation_config"])
|
||||
elif isinstance(kwargs["compilation_config"], str):
|
||||
# 如果是 JSON 字符串,先解析再转换
|
||||
try:
|
||||
config_dict = json.loads(kwargs["compilation_config"])
|
||||
kwargs["compilation_config"] = CompilationConfig(**config_dict)
|
||||
except (json.JSONDecodeError, TypeError) as e:
|
||||
logger.warning(
|
||||
f"Failed to parse compilation_config: {kwargs['compilation_config']}, error: {e}")
|
||||
del kwargs["compilation_config"]
|
||||
if "gpu_memory_utilization" not in kwargs:
|
||||
kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
|
||||
if "model" not in kwargs:
|
||||
|
|
|
|||
|
|
@ -349,7 +349,8 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
|
|||
# 调用通用方法
|
||||
return tie_up_category_by_index(
|
||||
get_subjects,
|
||||
get_objects
|
||||
get_objects,
|
||||
object_block_type=object_block_type
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -651,8 +651,8 @@ def union_make(pdf_info_dict: list,
|
|||
|
||||
def get_title_level(block):
|
||||
title_level = block.get('level', 1)
|
||||
if title_level > 4:
|
||||
title_level = 4
|
||||
if title_level > 6:
|
||||
title_level = 6
|
||||
elif title_level < 1:
|
||||
title_level = 0
|
||||
return title_level
|
||||
|
|
|
|||
|
|
@ -5,12 +5,21 @@ import re
|
|||
import tempfile
|
||||
import asyncio
|
||||
import threading
|
||||
import hashlib
|
||||
import json
|
||||
import uvicorn
|
||||
import click
|
||||
import zipfile
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
import glob
|
||||
from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form, APIRouter, Header
|
||||
import shutil
|
||||
|
||||
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
||||
|
||||
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, UploadFile, File, Form, APIRouter, Header
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse, FileResponse
|
||||
|
|
@ -23,7 +32,9 @@ from base64 import b64encode
|
|||
# MinerU 内部导入
|
||||
from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes, word_suffixes
|
||||
from mineru.utils.cli_parser import arg_parse
|
||||
from mineru.utils.config_reader import get_device
|
||||
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
|
||||
from mineru.utils.model_utils import clean_memory
|
||||
from mineru.version import __version__
|
||||
|
||||
# --- 日志配置 ---
|
||||
|
|
@ -36,13 +47,71 @@ _request_semaphore: Optional[asyncio.Semaphore] = None
|
|||
|
||||
# --- 任务进度跟踪 ---
|
||||
_task_progress: dict = {}
|
||||
_task_progress_dir = Path(
|
||||
os.getenv("MINERU_TASK_PROGRESS_DIR", Path(tempfile.gettempdir()) / "mineru-task-progress")
|
||||
)
|
||||
|
||||
|
||||
def _task_progress_path(task_id: str) -> Path:
|
||||
task_key = hashlib.sha256(task_id.encode("utf-8")).hexdigest()
|
||||
return _task_progress_dir / f"{task_key}.json"
|
||||
|
||||
|
||||
def _store_task_progress(task_id: str, state: dict) -> None:
|
||||
"""Store progress in memory and on disk so API worker processes share it."""
|
||||
state = dict(state)
|
||||
state["task_id"] = task_id
|
||||
_task_progress[task_id] = state
|
||||
|
||||
try:
|
||||
_task_progress_dir.mkdir(parents=True, exist_ok=True)
|
||||
progress_path = _task_progress_path(task_id)
|
||||
temp_path = progress_path.with_name(
|
||||
f"{progress_path.name}.{os.getpid()}.{threading.get_ident()}.tmp"
|
||||
)
|
||||
with open(temp_path, "w", encoding="utf-8") as fp:
|
||||
json.dump(state, fp, ensure_ascii=False)
|
||||
os.replace(temp_path, progress_path)
|
||||
except Exception as exc:
|
||||
logger.warning(f"Failed to persist task progress for {task_id}: {exc}")
|
||||
|
||||
|
||||
def _get_task_progress(task_id: str) -> Optional[dict]:
|
||||
try:
|
||||
with open(_task_progress_path(task_id), "r", encoding="utf-8") as fp:
|
||||
state = json.load(fp)
|
||||
_task_progress[task_id] = state
|
||||
return state
|
||||
except (FileNotFoundError, json.JSONDecodeError, OSError):
|
||||
return _task_progress.get(task_id)
|
||||
|
||||
|
||||
def _update_task_progress(task_id: Optional[str], progress: int, stage: str):
|
||||
"""更新任务进度(安全调用,task_id 为 None 时静默跳过)"""
|
||||
if task_id and task_id in _task_progress:
|
||||
_task_progress[task_id]["progress"] = min(progress, 100)
|
||||
_task_progress[task_id]["stage"] = stage
|
||||
if not task_id:
|
||||
return
|
||||
state = _get_task_progress(task_id)
|
||||
if state is not None:
|
||||
current = int(state.get("progress", 0) or 0)
|
||||
state["progress"] = min(max(progress, current), 100)
|
||||
state["stage"] = stage
|
||||
_store_task_progress(task_id, state)
|
||||
|
||||
|
||||
def _cleanup_runtime_memory():
|
||||
"""Release transient accelerator caches after each API parse request."""
|
||||
try:
|
||||
clean_memory(get_device())
|
||||
except Exception as exc:
|
||||
logger.warning(f"Failed to clean runtime memory: {exc}")
|
||||
|
||||
|
||||
def _format_parse_error(exc: Exception) -> str:
|
||||
message = str(exc)
|
||||
if "CUDA out of memory" in message or exc.__class__.__name__ in ("OutOfMemoryError", "RuntimeError"):
|
||||
if "out of memory" in message.lower():
|
||||
return "GPU显存不足,已尝试清理缓存。请减少最大页数、关闭公式/表格识别,或稍后重试。"
|
||||
return f"Internal Error: {message}"
|
||||
|
||||
|
||||
class ProgressTracker:
|
||||
|
|
@ -119,7 +188,11 @@ class _StderrProgressCapture:
|
|||
|
||||
# tqdm 进度条模式:名称: 百分比|...| 当前/总数
|
||||
_PATTERNS = [
|
||||
(re.compile(r'Two Step Extraction:\s*(\d+)%.*?(\d+)/(\d+)'), 'extract'),
|
||||
(re.compile(r'Layout Preparation:\s*(\d+)%.*?(\d+)/(\d+)'), 'layout_prepare'),
|
||||
(re.compile(r'Layout Output Parsing:\s*(\d+)%.*?(\d+)/(\d+)'), 'layout_parse'),
|
||||
(re.compile(r'Extract Preparation:\s*(\d+)%.*?(\d+)/(\d+)'), 'extract_prepare'),
|
||||
(re.compile(r'Post Processing:\s*(\d+)%.*?(\d+)/(\d+)'), 'post_process'),
|
||||
(re.compile(r'Two Step Extraction:\s*(\d+)%.*?(\d+)/(\d+)'), 'vlm_predict'),
|
||||
(re.compile(r'MFD Predict:\s*(\d+)%.*?(\d+)/(\d+)'), 'mfd'),
|
||||
(re.compile(r'MFR Predict:\s*(\d+)%.*?(\d+)/(\d+)'), 'mfr'),
|
||||
(re.compile(r'OCR-det:\s*(\d+)%.*?(\d+)/(\d+)'), 'ocr_det'),
|
||||
|
|
@ -127,22 +200,35 @@ class _StderrProgressCapture:
|
|||
(re.compile(r'Loading safetensors.*?:\s*(\d+)%'), 'load_model'),
|
||||
(re.compile(r'Capturing CUDA graphs.*?:\s*(\d+)%'), 'cuda_graph'),
|
||||
]
|
||||
_GENERIC_PREDICT_PATTERN = re.compile(r'^Predict:\s*(\d+)%.*?(\d+)/(\d+)')
|
||||
|
||||
# 各阶段的进度映射范围 [start%, end%]
|
||||
_RANGES = {
|
||||
'load_model': (12, 18),
|
||||
'cuda_graph': (33, 37),
|
||||
'extract': (42, 65),
|
||||
'mfd': (75, 80),
|
||||
'mfr': (80, 87),
|
||||
'ocr_det': (87, 92),
|
||||
'ocr_rec': (92, 96),
|
||||
'layout_prepare': (42, 45),
|
||||
'layout_predict': (45, 68),
|
||||
'layout_parse': (68, 70),
|
||||
'extract_prepare': (70, 72),
|
||||
'extract_predict': (72, 88),
|
||||
'vlm_predict': (45, 88),
|
||||
'post_process': (88, 90),
|
||||
'mfd': (90, 92),
|
||||
'mfr': (92, 94),
|
||||
'ocr_det': (94, 96),
|
||||
'ocr_rec': (96, 97),
|
||||
}
|
||||
|
||||
_STAGE_LABELS = {
|
||||
'load_model': '加载模型权重',
|
||||
'cuda_graph': '捕获CUDA计算图',
|
||||
'extract': 'VLM文档分析',
|
||||
'layout_prepare': '准备版面分析',
|
||||
'layout_predict': '版面分析',
|
||||
'layout_parse': '解析版面结果',
|
||||
'extract_prepare': '准备内容抽取',
|
||||
'extract_predict': '内容抽取',
|
||||
'vlm_predict': 'VLM文档分析',
|
||||
'post_process': '后处理',
|
||||
'mfd': '数学公式检测',
|
||||
'mfr': '数学公式识别',
|
||||
'ocr_det': '文字区域检测',
|
||||
|
|
@ -152,55 +238,83 @@ class _StderrProgressCapture:
|
|||
def __init__(self, task_id: str):
|
||||
self.task_id = task_id
|
||||
self._active = False
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._orig_stderr = None
|
||||
self._buf = ""
|
||||
self._last_anchor = ""
|
||||
|
||||
def start(self):
|
||||
self._active = True
|
||||
self._orig_stderr = sys.stderr
|
||||
self._thread = threading.Thread(target=self._reader_loop, daemon=True)
|
||||
self._thread.start()
|
||||
sys.stderr = self
|
||||
|
||||
def stop(self):
|
||||
self._active = False
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=2)
|
||||
self._thread = None
|
||||
if self._buf.strip():
|
||||
self._parse_line(self._buf.strip())
|
||||
self._buf = ""
|
||||
if self._orig_stderr is not None and sys.stderr is self:
|
||||
sys.stderr = self._orig_stderr
|
||||
|
||||
def _reader_loop(self):
|
||||
buf = ""
|
||||
orig = self._orig_stderr
|
||||
while self._active:
|
||||
try:
|
||||
ch = orig.read(1)
|
||||
if not ch:
|
||||
break
|
||||
buf += ch
|
||||
# tqdm 用 \r 更新同一行,\n 表示新行
|
||||
if ch == '\r' or ch == '\n':
|
||||
if buf.strip():
|
||||
self._parse_line(buf.strip())
|
||||
buf = ""
|
||||
except Exception:
|
||||
break
|
||||
def write(self, text):
|
||||
if self._orig_stderr is not None:
|
||||
self._orig_stderr.write(text)
|
||||
if not self._active:
|
||||
return len(text)
|
||||
for ch in text:
|
||||
self._buf += ch
|
||||
# tqdm 用 \r 更新同一行,\n 表示新行
|
||||
if ch == '\r' or ch == '\n':
|
||||
if self._buf.strip():
|
||||
self._parse_line(self._buf.strip())
|
||||
self._buf = ""
|
||||
return len(text)
|
||||
|
||||
def flush(self):
|
||||
if self._orig_stderr is not None:
|
||||
self._orig_stderr.flush()
|
||||
|
||||
def isatty(self):
|
||||
return bool(self._orig_stderr and self._orig_stderr.isatty())
|
||||
|
||||
def fileno(self):
|
||||
if self._orig_stderr is not None:
|
||||
return self._orig_stderr.fileno()
|
||||
raise OSError("stderr is not available")
|
||||
|
||||
def __getattr__(self, name):
|
||||
if self._orig_stderr is not None:
|
||||
return getattr(self._orig_stderr, name)
|
||||
raise AttributeError(name)
|
||||
|
||||
def _parse_line(self, line: str):
|
||||
if "Layout Preparation:" in line:
|
||||
self._last_anchor = "layout"
|
||||
elif "Extract Preparation:" in line:
|
||||
self._last_anchor = "extract"
|
||||
|
||||
generic_predict = self._GENERIC_PREDICT_PATTERN.search(line)
|
||||
if generic_predict:
|
||||
stage = "extract_predict" if self._last_anchor == "extract" else "layout_predict"
|
||||
self._update_from_match(generic_predict, stage)
|
||||
return
|
||||
|
||||
for pattern, stage in self._PATTERNS:
|
||||
m = pattern.search(line)
|
||||
if m:
|
||||
pct = int(m.group(1))
|
||||
lo, hi = self._RANGES.get(stage, (0, 100))
|
||||
mapped = lo + int((hi - lo) * pct / 100)
|
||||
label = self._STAGE_LABELS.get(stage, stage)
|
||||
if stage == 'extract' and len(m.groups()) >= 3:
|
||||
cur, total = m.group(2), m.group(3)
|
||||
label = f"VLM文档分析 ({cur}/{total}页)"
|
||||
elif stage in ('mfd', 'mfr', 'ocr_det', 'ocr_rec') and len(m.groups()) >= 3:
|
||||
cur, total = m.group(2), m.group(3)
|
||||
label = f"{label} ({cur}/{total})"
|
||||
_update_task_progress(self.task_id, mapped, label)
|
||||
self._update_from_match(m, stage)
|
||||
break
|
||||
|
||||
def _update_from_match(self, match, stage: str):
|
||||
pct = int(match.group(1))
|
||||
lo, hi = self._RANGES.get(stage, (0, 100))
|
||||
mapped = lo + int((hi - lo) * pct / 100)
|
||||
label = self._STAGE_LABELS.get(stage, stage)
|
||||
if len(match.groups()) >= 3:
|
||||
cur, total = match.group(2), match.group(3)
|
||||
unit = "页" if stage in ("layout_predict", "vlm_predict") else ""
|
||||
label = f"{label} ({cur}/{total}{unit})"
|
||||
_update_task_progress(self.task_id, mapped, label)
|
||||
|
||||
|
||||
async def limit_concurrency():
|
||||
if _request_semaphore is not None:
|
||||
|
|
@ -225,7 +339,9 @@ def sanitize_filename(filename: str) -> str:
|
|||
|
||||
def cleanup_file(file_path: str) -> None:
|
||||
try:
|
||||
if os.path.exists(file_path):
|
||||
if os.path.isdir(file_path):
|
||||
shutil.rmtree(file_path)
|
||||
elif os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"fail clean file {file_path}: {e}")
|
||||
|
|
@ -246,18 +362,443 @@ def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str)
|
|||
|
||||
# --- 创建 API 路由组 ---
|
||||
api_router = APIRouter(prefix="/api")
|
||||
parser_router = APIRouter()
|
||||
|
||||
|
||||
class MindmapLlmConfig(BaseModel):
|
||||
base_url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
model: Optional[str] = None
|
||||
timeout: Optional[int] = None
|
||||
temperature: Optional[float] = None
|
||||
max_context_tokens: Optional[int] = None
|
||||
max_output_tokens: Optional[int] = None
|
||||
safety_tokens: Optional[int] = None
|
||||
|
||||
|
||||
class MindmapOrganizeRequest(BaseModel):
|
||||
markdown: str
|
||||
mode: str = "smart"
|
||||
prompt: Optional[str] = None
|
||||
llm_config: Optional[MindmapLlmConfig] = None
|
||||
|
||||
|
||||
def _extract_json_object(text: Optional[str]) -> str:
|
||||
content = (text or "").strip()
|
||||
if content.startswith("```"):
|
||||
content = re.sub(r"^```(?:json|markdown|md)?\s*", "", content, flags=re.IGNORECASE)
|
||||
content = re.sub(r"\s*```$", "", content)
|
||||
return content.strip()
|
||||
|
||||
|
||||
def _extract_llm_message_content(message: dict) -> str:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict):
|
||||
text = item.get("text") or item.get("content")
|
||||
if isinstance(text, str):
|
||||
parts.append(text)
|
||||
if parts:
|
||||
return "\n".join(parts)
|
||||
|
||||
for key in ("reasoning_content", "reasoning", "output_text", "text"):
|
||||
value = message.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
DEFAULT_MINDMAP_ORGANIZE_PROMPT = """你是文档结构整理助手。请基于用户提供的 Markdown 生成适合思维导图展示的 Markdown。
|
||||
|
||||
要求:
|
||||
1. 保留原文标题结构,不要重写或打乱主要标题层级。
|
||||
2. 将标题下的段落内容总结为要点,合并相近段落,避免逐段照抄。
|
||||
3. 保留原文语言:英文内容输出英文,中文内容输出中文,多语言内容按原文语言分别保留。
|
||||
4. 不要编造原文没有的信息。
|
||||
5. 保留关键数字、公式、专有名词、步骤和结论。
|
||||
6. 最大层级不超过 6 层。
|
||||
7. 每个父节点下最多 8 个子节点。
|
||||
8. 节点标题尽量简短,正文说明使用短句列表。
|
||||
9. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。"""
|
||||
|
||||
MINDMAP_MERGE_PROMPT = """你是 Markdown 思维导图结构校对助手。下面是多个分块已经整理总结后的局部 Markdown 大纲。
|
||||
|
||||
任务:
|
||||
1. 合并这些局部大纲为一份完整 Markdown。
|
||||
2. 只检查和调整标题层级结构、顺序、重复标题和父子关系。
|
||||
3. 不要重新总结正文,不要扩写内容,不要新增原文没有的信息。
|
||||
4. 保留各局部大纲中的源语言:英文保持英文,中文保持中文,多语言分别保留。
|
||||
5. 最大层级不超过 6 层。
|
||||
6. 每个父节点下最多 8 个子节点,必要时只合并相近标题。
|
||||
7. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。"""
|
||||
|
||||
|
||||
def _estimate_tokens(text: str) -> int:
|
||||
ascii_chars = 0
|
||||
non_ascii_chars = 0
|
||||
for ch in text:
|
||||
if ch.isspace():
|
||||
continue
|
||||
if ord(ch) < 128:
|
||||
ascii_chars += 1
|
||||
else:
|
||||
non_ascii_chars += 1
|
||||
return max(1, int(ascii_chars / 4) + int(non_ascii_chars * 1.5))
|
||||
|
||||
|
||||
def _optional_str(value: Optional[str], env_name: str, default: str = "") -> str:
|
||||
configured = (value or "").strip()
|
||||
return configured or os.getenv(env_name, default)
|
||||
|
||||
|
||||
def _optional_int(value: Optional[int], env_name: str, default: int) -> int:
|
||||
return int(value if value is not None else os.getenv(env_name, str(default)))
|
||||
|
||||
|
||||
def _optional_float(value: Optional[float], env_name: str, default: float) -> float:
|
||||
return float(value if value is not None else os.getenv(env_name, str(default)))
|
||||
|
||||
|
||||
def _get_mindmap_max_output_tokens(llm_config: Optional[MindmapLlmConfig] = None) -> int:
|
||||
value = llm_config.max_output_tokens if llm_config else None
|
||||
return _optional_int(value, "MINDMAP_LLM_MAX_OUTPUT_TOKENS", 4096)
|
||||
|
||||
|
||||
def _get_mindmap_context_budget(
|
||||
prompt: str,
|
||||
reserve_output_tokens: Optional[int] = None,
|
||||
llm_config: Optional[MindmapLlmConfig] = None
|
||||
) -> tuple[int, int]:
|
||||
if reserve_output_tokens is None:
|
||||
reserve_output_tokens = _get_mindmap_max_output_tokens(llm_config)
|
||||
max_context_tokens = _optional_int(llm_config.max_context_tokens if llm_config else None, "MINDMAP_LLM_MAX_CONTEXT_TOKENS", 32768)
|
||||
prompt_tokens = _estimate_tokens(prompt)
|
||||
safety_tokens = _optional_int(llm_config.safety_tokens if llm_config else None, "MINDMAP_LLM_SAFETY_TOKENS", 1024)
|
||||
input_budget_tokens = max(2048, max_context_tokens - prompt_tokens - reserve_output_tokens - safety_tokens)
|
||||
logger.info(
|
||||
"Mindmap context budget max_context_tokens={} prompt_tokens={} reserve_output_tokens={} safety_tokens={} input_budget_tokens={}",
|
||||
max_context_tokens, prompt_tokens, reserve_output_tokens, safety_tokens, input_budget_tokens
|
||||
)
|
||||
return max_context_tokens, input_budget_tokens
|
||||
|
||||
|
||||
def _split_markdown_blocks(markdown: str) -> list[str]:
|
||||
lines = markdown.splitlines()
|
||||
blocks: list[str] = []
|
||||
current: list[str] = []
|
||||
|
||||
heading_pattern = re.compile(r"^#{1,6}\s+")
|
||||
for line in lines:
|
||||
if heading_pattern.match(line) and current:
|
||||
blocks.append("\n".join(current).strip())
|
||||
current = [line]
|
||||
else:
|
||||
current.append(line)
|
||||
|
||||
if current:
|
||||
blocks.append("\n".join(current).strip())
|
||||
|
||||
return [block for block in blocks if block]
|
||||
|
||||
|
||||
def _split_large_block(block: str, max_tokens: int) -> list[str]:
|
||||
paragraphs = re.split(r"\n{2,}", block)
|
||||
chunks: list[str] = []
|
||||
current: list[str] = []
|
||||
current_tokens = 0
|
||||
|
||||
for paragraph in paragraphs:
|
||||
paragraph = paragraph.strip()
|
||||
if not paragraph:
|
||||
continue
|
||||
paragraph_tokens = _estimate_tokens(paragraph)
|
||||
if current and current_tokens + paragraph_tokens > max_tokens:
|
||||
chunks.append("\n\n".join(current))
|
||||
current = [paragraph]
|
||||
current_tokens = paragraph_tokens
|
||||
else:
|
||||
current.append(paragraph)
|
||||
current_tokens += paragraph_tokens
|
||||
|
||||
if current:
|
||||
chunks.append("\n\n".join(current))
|
||||
return chunks or [block]
|
||||
|
||||
|
||||
def _chunk_markdown_by_headings(markdown: str, max_tokens: int) -> list[str]:
|
||||
blocks = _split_markdown_blocks(markdown)
|
||||
chunks: list[str] = []
|
||||
current: list[str] = []
|
||||
current_tokens = 0
|
||||
|
||||
for block in blocks:
|
||||
block_tokens = _estimate_tokens(block)
|
||||
if block_tokens > max_tokens:
|
||||
if current:
|
||||
chunks.append("\n\n".join(current))
|
||||
current = []
|
||||
current_tokens = 0
|
||||
chunks.extend(_split_large_block(block, max_tokens))
|
||||
continue
|
||||
|
||||
if current and current_tokens + block_tokens > max_tokens:
|
||||
chunks.append("\n\n".join(current))
|
||||
current = [block]
|
||||
current_tokens = block_tokens
|
||||
else:
|
||||
current.append(block)
|
||||
current_tokens += block_tokens
|
||||
|
||||
if current:
|
||||
chunks.append("\n\n".join(current))
|
||||
|
||||
return chunks or [markdown]
|
||||
|
||||
|
||||
def _call_mindmap_llm(
|
||||
markdown: str,
|
||||
mode: str = "smart",
|
||||
custom_prompt: Optional[str] = None,
|
||||
task_id: Optional[str] = None,
|
||||
request_role: str = "organize",
|
||||
llm_config: Optional[MindmapLlmConfig] = None
|
||||
) -> str:
|
||||
base_url = _optional_str(llm_config.base_url if llm_config else None, "MINDMAP_LLM_BASE_URL").rstrip("/")
|
||||
model = _optional_str(llm_config.model if llm_config else None, "MINDMAP_LLM_MODEL", "gemma-4-26B")
|
||||
api_key = _optional_str(llm_config.api_key if llm_config else None, "MINDMAP_LLM_API_KEY")
|
||||
timeout = _optional_int(llm_config.timeout if llm_config else None, "MINDMAP_LLM_TIMEOUT", 180)
|
||||
max_output_tokens = _get_mindmap_max_output_tokens(llm_config)
|
||||
temperature = _optional_float(llm_config.temperature if llm_config else None, "MINDMAP_LLM_TEMPERATURE", 0.2)
|
||||
|
||||
if not base_url:
|
||||
raise RuntimeError("未配置智能整理模型服务,请设置 MINDMAP_LLM_BASE_URL")
|
||||
|
||||
compact_markdown = markdown.strip()
|
||||
prompt_template = (custom_prompt or "").strip() or DEFAULT_MINDMAP_ORGANIZE_PROMPT
|
||||
prompt = f"""{prompt_template}
|
||||
|
||||
原始 Markdown:
|
||||
{compact_markdown}
|
||||
"""
|
||||
logger.info(
|
||||
"Mindmap LLM request start task_id={} role={} model={} base_url={} mode={} input_chars={} input_tokens_est={} prompt_chars={} max_tokens={} timeout={} temperature={} api_key_configured={}",
|
||||
task_id or "-", request_role, model, base_url, mode, len(compact_markdown), _estimate_tokens(compact_markdown),
|
||||
len(prompt_template), max_output_tokens, timeout, temperature, bool(api_key)
|
||||
)
|
||||
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "你擅长把长文档整理成结构清晰、层次合理的思维导图 Markdown,并严格保留原文语言。"},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_output_tokens,
|
||||
}
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if api_key:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
url = f"{base_url}/chat/completions"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
result = json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", errors="ignore")
|
||||
raise RuntimeError(f"智能整理模型请求失败: HTTP {exc.code} {detail}") from exc
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"智能整理模型请求失败: {exc}") from exc
|
||||
|
||||
choices = result.get("choices") or []
|
||||
choice = choices[0] if choices else {}
|
||||
message = choice.get("message") or {}
|
||||
finish_reason = choice.get("finish_reason")
|
||||
usage = result.get("usage")
|
||||
content = _extract_llm_message_content(message)
|
||||
if not content:
|
||||
logger.warning(
|
||||
"Mindmap LLM returned empty content task_id={} role={} finish_reason={} usage={} message_keys={}",
|
||||
task_id or "-", request_role, finish_reason, usage, list(message.keys())
|
||||
)
|
||||
raise RuntimeError(f"智能整理模型返回空内容,finish_reason={finish_reason}")
|
||||
organized = _extract_json_object(content)
|
||||
if not organized:
|
||||
logger.warning(
|
||||
"Mindmap LLM returned invalid organized content task_id={} role={} finish_reason={} usage={}",
|
||||
task_id or "-", request_role, finish_reason, usage
|
||||
)
|
||||
raise RuntimeError(f"智能整理模型未返回有效内容,finish_reason={finish_reason}")
|
||||
logger.info(
|
||||
"Mindmap LLM request completed task_id={} role={} finish_reason={} usage={} output_chars={} output_tokens_est={}",
|
||||
task_id or "-", request_role, finish_reason, usage, len(organized), _estimate_tokens(organized)
|
||||
)
|
||||
return organized
|
||||
|
||||
|
||||
def _organize_mindmap_markdown(
|
||||
markdown: str,
|
||||
mode: str,
|
||||
custom_prompt: Optional[str],
|
||||
task_id: str,
|
||||
llm_config: Optional[MindmapLlmConfig]
|
||||
) -> str:
|
||||
prompt_template = (custom_prompt or "").strip() or DEFAULT_MINDMAP_ORGANIZE_PROMPT
|
||||
_, input_budget_tokens = _get_mindmap_context_budget(prompt_template, llm_config=llm_config)
|
||||
source_tokens = _estimate_tokens(markdown)
|
||||
logger.info(
|
||||
"Mindmap organize strategy task_id={} source_chars={} source_tokens_est={} input_budget_tokens={}",
|
||||
task_id, len(markdown), source_tokens, input_budget_tokens
|
||||
)
|
||||
|
||||
if source_tokens <= input_budget_tokens:
|
||||
_update_task_progress(task_id, 35, "调用智能整理模型")
|
||||
return _call_mindmap_llm(markdown, mode, prompt_template, task_id, "single", llm_config)
|
||||
|
||||
chunks = _chunk_markdown_by_headings(markdown, input_budget_tokens)
|
||||
logger.info("Mindmap large input split task_id={} chunks={}", task_id, len(chunks))
|
||||
partial_results: list[str] = []
|
||||
for index, chunk in enumerate(chunks, start=1):
|
||||
progress = 20 + int(index / max(len(chunks), 1) * 55)
|
||||
_update_task_progress(task_id, progress, f"智能整理分块 {index}/{len(chunks)}")
|
||||
logger.info(
|
||||
"Mindmap chunk organize task_id={} chunk={}/{} chars={} tokens_est={}",
|
||||
task_id, index, len(chunks), len(chunk), _estimate_tokens(chunk)
|
||||
)
|
||||
partial = _call_mindmap_llm(chunk, mode, prompt_template, task_id, f"chunk-{index}", llm_config)
|
||||
partial_results.append(partial)
|
||||
|
||||
merged_input = "\n\n".join(
|
||||
f"<!-- chunk {index} -->\n{partial}"
|
||||
for index, partial in enumerate(partial_results, start=1)
|
||||
)
|
||||
_, merge_budget_tokens = _get_mindmap_context_budget(MINDMAP_MERGE_PROMPT, llm_config=llm_config)
|
||||
merge_tokens = _estimate_tokens(merged_input)
|
||||
if merge_tokens > merge_budget_tokens:
|
||||
logger.warning(
|
||||
"Mindmap merged outline still exceeds context task_id={} tokens_est={} budget={} chunks={}",
|
||||
task_id, merge_tokens, merge_budget_tokens, len(partial_results)
|
||||
)
|
||||
merge_chunks = _chunk_markdown_by_headings(merged_input, merge_budget_tokens)
|
||||
merged_round: list[str] = []
|
||||
for index, chunk in enumerate(merge_chunks, start=1):
|
||||
_update_task_progress(task_id, 78 + int(index / max(len(merge_chunks), 1) * 10), f"合并局部大纲 {index}/{len(merge_chunks)}")
|
||||
merged_round.append(_call_mindmap_llm(chunk, mode, MINDMAP_MERGE_PROMPT, task_id, f"merge-round-{index}", llm_config))
|
||||
merged_input = "\n\n".join(merged_round)
|
||||
|
||||
_update_task_progress(task_id, 90, "全局整理标题结构")
|
||||
return _call_mindmap_llm(merged_input, mode, MINDMAP_MERGE_PROMPT, task_id, "merge", llm_config)
|
||||
|
||||
|
||||
async def _run_mindmap_organize_task(
|
||||
task_id: str,
|
||||
markdown: str,
|
||||
mode: str,
|
||||
prompt: Optional[str],
|
||||
llm_config: Optional[MindmapLlmConfig]
|
||||
):
|
||||
try:
|
||||
_store_task_progress(task_id, {
|
||||
"progress": 10,
|
||||
"stage": "准备智能整理",
|
||||
"status": "processing",
|
||||
"error": None,
|
||||
"file_names": "",
|
||||
"result_md": None,
|
||||
})
|
||||
organized = await asyncio.to_thread(_organize_mindmap_markdown, markdown, mode, prompt, task_id, llm_config)
|
||||
state = _get_task_progress(task_id) or {}
|
||||
state.update({
|
||||
"progress": 100,
|
||||
"stage": "智能整理完成",
|
||||
"status": "completed",
|
||||
"error": None,
|
||||
"result_md": organized,
|
||||
})
|
||||
_store_task_progress(task_id, state)
|
||||
except Exception as exc:
|
||||
logger.exception(f"Mindmap organize task failed task_id={task_id}: {exc}")
|
||||
state = _get_task_progress(task_id) or {}
|
||||
state.update({
|
||||
"progress": 100,
|
||||
"stage": "智能整理失败",
|
||||
"status": "failed",
|
||||
"error": str(exc),
|
||||
"result_md": None,
|
||||
})
|
||||
_store_task_progress(task_id, state)
|
||||
|
||||
|
||||
@api_router.post("/parse_tasks/{task_id}", status_code=201)
|
||||
async def create_parse_task(task_id: str):
|
||||
"""Register a task before the multipart upload starts."""
|
||||
state = {
|
||||
"progress": 0,
|
||||
"stage": "等待上传",
|
||||
"status": "pending",
|
||||
"error": None,
|
||||
"file_names": "",
|
||||
}
|
||||
_store_task_progress(task_id, state)
|
||||
logger.info(f"Registered parse task pid={os.getpid()} task_id={task_id}")
|
||||
return state
|
||||
|
||||
|
||||
@api_router.get("/parse_progress/{task_id}")
|
||||
async def get_parse_progress(task_id: str):
|
||||
"""查询解析任务的实时进度"""
|
||||
if task_id not in _task_progress:
|
||||
state = _get_task_progress(task_id)
|
||||
if state is None:
|
||||
logger.warning(f"Parse task not found pid={os.getpid()} task_id={task_id}")
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return _task_progress[task_id]
|
||||
return state
|
||||
|
||||
|
||||
@api_router.post("/mindmap_tasks/{task_id}", status_code=201)
|
||||
async def create_mindmap_task(task_id: str, request: MindmapOrganizeRequest):
|
||||
"""Create an async task that organizes Markdown into summarized mindmap Markdown."""
|
||||
markdown = request.markdown.strip()
|
||||
if not markdown:
|
||||
raise HTTPException(status_code=400, detail="Markdown content is required")
|
||||
|
||||
state = {
|
||||
"progress": 0,
|
||||
"stage": "等待智能整理",
|
||||
"status": "pending",
|
||||
"error": None,
|
||||
"file_names": "",
|
||||
"result_md": None,
|
||||
}
|
||||
_store_task_progress(task_id, state)
|
||||
asyncio.create_task(_run_mindmap_organize_task(task_id, markdown, request.mode, request.prompt, request.llm_config))
|
||||
logger.info(
|
||||
"Registered mindmap organize task pid={} task_id={} mode={} input_chars={} custom_prompt={} request_llm_config={}",
|
||||
os.getpid(), task_id, request.mode, len(markdown), bool((request.prompt or "").strip()), bool(request.llm_config)
|
||||
)
|
||||
return state
|
||||
|
||||
|
||||
@api_router.get("/mindmap_progress/{task_id}")
|
||||
async def get_mindmap_progress(task_id: str):
|
||||
"""Query async mindmap organization progress and result."""
|
||||
state = _get_task_progress(task_id)
|
||||
if state is None:
|
||||
logger.warning(f"Mindmap task not found pid={os.getpid()} task_id={task_id}")
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return state
|
||||
|
||||
|
||||
@api_router.post(path="/file_parse", dependencies=[Depends(limit_concurrency)])
|
||||
@parser_router.post(path="/file_parse", dependencies=[Depends(limit_concurrency)])
|
||||
async def parse_pdf(
|
||||
background_tasks: BackgroundTasks,
|
||||
files: List[UploadFile] = File(..., description="Upload pdf, image, or Word files for parsing"),
|
||||
output_dir: str = Form("./output", description="Output local directory"),
|
||||
lang_list: List[str] = Form(["ch"]),
|
||||
|
|
@ -274,30 +815,36 @@ async def parse_pdf(
|
|||
response_format_zip: bool = Form(False),
|
||||
start_page_id: int = Form(0),
|
||||
end_page_id: int = Form(99999),
|
||||
form_task_id: Optional[str] = Form(None, alias="task_id"),
|
||||
x_task_id: Optional[str] = Header(None),
|
||||
):
|
||||
# 从 app 实例状态中获取配置 (FastAPI 实例会在下方创建)
|
||||
from fastapi import Request
|
||||
config = getattr(app.state, "config", {})
|
||||
config = dict(getattr(app.state, "config", {}))
|
||||
|
||||
# 初始化进度跟踪
|
||||
task_id = x_task_id or str(uuid.uuid4())
|
||||
task_id = x_task_id or form_task_id or str(uuid.uuid4())
|
||||
file_names_str = ", ".join(f.filename or "unknown" for f in files)
|
||||
_task_progress[task_id] = {
|
||||
_store_task_progress(task_id, {
|
||||
"progress": 0, "stage": "准备中", "status": "processing",
|
||||
"error": None, "file_names": file_names_str,
|
||||
}
|
||||
})
|
||||
logger.info(
|
||||
f"Started parse task pid={os.getpid()} task_id={task_id} "
|
||||
f"header_task_id={x_task_id} form_task_id={form_task_id}"
|
||||
)
|
||||
|
||||
try:
|
||||
unique_dir = os.path.join(output_dir, str(uuid.uuid4()))
|
||||
os.makedirs(unique_dir, exist_ok=True)
|
||||
background_tasks.add_task(cleanup_file, unique_dir)
|
||||
|
||||
pdf_file_names = []
|
||||
pdf_bytes_list = []
|
||||
|
||||
for file in files:
|
||||
content = await file.read()
|
||||
file_path = Path(file.filename)
|
||||
file_path = Path((file.filename or 'document.pdf').replace('\\', '/').rsplit('/', 1)[-1])
|
||||
temp_path = Path(unique_dir) / file_path.name
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(content)
|
||||
|
|
@ -307,7 +854,10 @@ async def parse_pdf(
|
|||
try:
|
||||
pdf_bytes = read_fn(temp_path)
|
||||
pdf_bytes_list.append(pdf_bytes)
|
||||
pdf_file_names.append(file_path.stem)
|
||||
name = sanitize_filename(file_path.stem)
|
||||
if name in pdf_file_names:
|
||||
name = f"{name}_{len(pdf_file_names) + 1}"
|
||||
pdf_file_names.append(name)
|
||||
os.remove(temp_path)
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=400, content={"error": f"Failed to load file: {str(e)}"})
|
||||
|
|
@ -353,7 +903,10 @@ async def parse_pdf(
|
|||
_update_task_progress(task_id, 97, "生成结果文件")
|
||||
|
||||
_update_task_progress(task_id, 100, "转换完成")
|
||||
_task_progress[task_id]["status"] = "completed"
|
||||
completed_state = _get_task_progress(task_id) or {}
|
||||
completed_state["status"] = "completed"
|
||||
_store_task_progress(task_id, completed_state)
|
||||
_cleanup_runtime_memory()
|
||||
|
||||
# 清理日志捕获和 stderr 捕获
|
||||
stderr_capture.stop()
|
||||
|
|
@ -379,13 +932,22 @@ async def parse_pdf(
|
|||
path = os.path.join(p_dir, f"{pdf_name}.md")
|
||||
if os.path.exists(path): zf.write(path,
|
||||
arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md"))
|
||||
for enabled, suffix in (
|
||||
(return_middle_json, '_middle.json'),
|
||||
(return_model_output, '_model.json'),
|
||||
(return_content_list, '_content_list.json'),
|
||||
):
|
||||
path = os.path.join(p_dir, pdf_name + suffix)
|
||||
if enabled and os.path.exists(path):
|
||||
zf.write(path, arcname=os.path.join(safe_pdf_name, safe_pdf_name + suffix))
|
||||
if return_images:
|
||||
images_dir = os.path.join(p_dir, "images")
|
||||
for img in glob.glob(os.path.join(glob.escape(images_dir), "*.jpg")):
|
||||
zf.write(img, arcname=os.path.join(safe_pdf_name, "images", os.path.basename(img)))
|
||||
|
||||
background_tasks.add_task(cleanup_file, zip_path)
|
||||
return FileResponse(path=zip_path, media_type="application/zip", filename="results.zip",
|
||||
background=BackgroundTask(cleanup_file, zip_path))
|
||||
background=background_tasks)
|
||||
else:
|
||||
result_dict = {}
|
||||
for pdf_name in pdf_file_names:
|
||||
|
|
@ -400,6 +962,13 @@ async def parse_pdf(
|
|||
|
||||
if os.path.exists(p_dir):
|
||||
if return_md: data["md_content"] = get_infer_result(".md", pdf_name, p_dir)
|
||||
for enabled, key, suffix in (
|
||||
(return_middle_json, 'middle_json', '_middle.json'),
|
||||
(return_model_output, 'model_output', '_model.json'),
|
||||
(return_content_list, 'content_list', '_content_list.json'),
|
||||
):
|
||||
if enabled:
|
||||
data[key] = get_infer_result(suffix, pdf_name, p_dir)
|
||||
if return_images:
|
||||
img_dir = os.path.join(p_dir, "images")
|
||||
data["images"] = {os.path.basename(p): f"data:image/jpeg;base64,{encode_image(p)}"
|
||||
|
|
@ -416,9 +985,12 @@ async def parse_pdf(
|
|||
_current_task_id = None
|
||||
except Exception:
|
||||
pass
|
||||
_task_progress[task_id]["status"] = "failed"
|
||||
_task_progress[task_id]["error"] = str(e)
|
||||
return JSONResponse(status_code=500, content={"error": f"Internal Error: {str(e)}"})
|
||||
failed_state = _get_task_progress(task_id) or {}
|
||||
failed_state["status"] = "failed"
|
||||
failed_state["error"] = _format_parse_error(e)
|
||||
_store_task_progress(task_id, failed_state)
|
||||
_cleanup_runtime_memory()
|
||||
return JSONResponse(status_code=500, content={"error": _format_parse_error(e)})
|
||||
|
||||
|
||||
# --- FastAPI 核心应用 ---
|
||||
|
|
@ -432,7 +1004,7 @@ def create_app():
|
|||
|
||||
global _request_semaphore
|
||||
try:
|
||||
mcr = int(os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "0"))
|
||||
mcr = int(os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "1"))
|
||||
if mcr > 0:
|
||||
_request_semaphore = asyncio.Semaphore(mcr)
|
||||
logger.info(f"Concurrency limited to {mcr}")
|
||||
|
|
@ -445,11 +1017,12 @@ def create_app():
|
|||
|
||||
# 1. 首先挂载 API 路由组 (处理所有 /api/* 请求)
|
||||
app.include_router(api_router)
|
||||
app.include_router(parser_router)
|
||||
|
||||
# 2. 根路径重定向或特定处理 (可选)
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
return {"status": "ok", "version": __version__}
|
||||
|
||||
# 3. 最后挂载静态文件服务 (处理剩下的所有请求,如 /, /index.html, /assets/*)
|
||||
static_dir = Path(__file__).parent / "static" / "web"
|
||||
|
|
@ -472,13 +1045,20 @@ app = create_app()
|
|||
@click.option('--reload', is_flag=True)
|
||||
def main(ctx, host, port, reload, **kwargs):
|
||||
kwargs.update(arg_parse(ctx))
|
||||
utilization = os.getenv('MINERU_GPU_MEMORY_UTILIZATION')
|
||||
if utilization is not None:
|
||||
utilization = float(utilization)
|
||||
if not 0 < utilization <= 1:
|
||||
raise click.BadParameter('MINERU_GPU_MEMORY_UTILIZATION must be greater than 0 and at most 1')
|
||||
kwargs.setdefault('gpu_memory_utilization', utilization)
|
||||
app.state.config = kwargs
|
||||
|
||||
mcr = str(kwargs.get("mineru_api_max_concurrent_requests", "0") or "0")
|
||||
os.environ["MINERU_API_MAX_CONCURRENT_REQUESTS"] = mcr
|
||||
|
||||
uvicorn.run("mineru.cli.fast_api:app", host=host, port=port, reload=reload)
|
||||
mcr = int(kwargs.pop('mineru_api_max_concurrent_requests', os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS', '1')))
|
||||
os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS'] = str(mcr)
|
||||
global _request_semaphore
|
||||
_request_semaphore = asyncio.Semaphore(mcr) if mcr > 0 else None
|
||||
uvicorn.run('mineru.cli.fast_api:app' if reload else app, host=host, port=port, reload=reload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,10 +1,10 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>思维导图</title>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>思维导图</title>
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
|
|
@ -15,14 +15,14 @@
|
|||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
<script type="module" crossorigin src="/assets/index-zcV97yfy.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/vendor-DSv9k51x.js">
|
||||
<link rel="modulepreload" crossorigin href="/assets/markdown-_Dy2zPzC.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-B_viQAxH.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
</body>
|
||||
</style>
|
||||
<script type="module" crossorigin src="./assets/index-D7YNJWSR.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="./assets/vendor-DDOvA1Mb.js">
|
||||
<link rel="modulepreload" crossorigin href="./assets/markdown-_Dy2zPzC.js">
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-CxJ0NebI.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
import os
|
||||
from typing import List, Union
|
||||
|
||||
import torch
|
||||
from tqdm import tqdm
|
||||
from ultralytics import YOLO
|
||||
import numpy as np
|
||||
|
|
@ -18,8 +20,8 @@ class YOLOv8MFDModel:
|
|||
conf: float = 0.25,
|
||||
iou: float = 0.45,
|
||||
):
|
||||
self.model = YOLO(weight).to(device)
|
||||
self.device = device
|
||||
self.device = torch.device(device)
|
||||
self.model = YOLO(weight).to(self.device)
|
||||
self.imgsz = imgsz
|
||||
self.conf = conf
|
||||
self.iou = iou
|
||||
|
|
|
|||
|
|
@ -89,7 +89,11 @@ class FormulaRecognizer(BaseOCRV20):
|
|||
return rec_formula
|
||||
|
||||
def batch_predict(
|
||||
self, images_mfd_res: list, images: list, batch_size: int = 64
|
||||
self,
|
||||
images_mfd_res: list,
|
||||
images: list,
|
||||
batch_size: int = 64,
|
||||
interline_enable: bool = True,
|
||||
) -> list:
|
||||
images_formula_list = []
|
||||
mf_image_list = []
|
||||
|
|
@ -105,6 +109,8 @@ class FormulaRecognizer(BaseOCRV20):
|
|||
for idx, (xyxy, conf, cla) in enumerate(
|
||||
zip(mfd_res.boxes.xyxy, mfd_res.boxes.conf, mfd_res.boxes.cls)
|
||||
):
|
||||
if not interline_enable and cla.item() == 1:
|
||||
continue # Skip interline regions if not enabled
|
||||
xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]
|
||||
new_item = {
|
||||
"category_id": 13 + int(cla.item()),
|
||||
|
|
|
|||
|
|
@ -23,12 +23,12 @@ class MathDataset(Dataset):
|
|||
class UnimernetModel(object):
|
||||
def __init__(self, weight_dir, _device_="cpu"):
|
||||
from .unimernet_hf import UnimernetModel
|
||||
if _device_.startswith("mps") or _device_.startswith("npu"):
|
||||
if _device_.startswith("mps") or _device_.startswith("npu") or _device_.startswith("musa"):
|
||||
self.model = UnimernetModel.from_pretrained(weight_dir, attn_implementation="eager")
|
||||
else:
|
||||
self.model = UnimernetModel.from_pretrained(weight_dir)
|
||||
self.device = _device_
|
||||
self.model.to(_device_)
|
||||
self.device = torch.device(_device_)
|
||||
self.model.to(self.device)
|
||||
if not _device_.startswith("cpu"):
|
||||
self.model = self.model.to(dtype=torch.float16)
|
||||
self.model.eval()
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import cv2
|
|||
import numpy as np
|
||||
from scipy.spatial import distance as dist
|
||||
from skimage import measure
|
||||
from skimage import __version__ as skimage_version
|
||||
from packaging import version
|
||||
|
||||
|
||||
def transform_preds(coords, center, scale, output_size, rot=0):
|
||||
|
|
@ -295,7 +297,11 @@ def min_area_rect_box(
|
|||
"""
|
||||
boxes = []
|
||||
for region in regions:
|
||||
if region.bbox_area > H * W * 3 / 4: # 过滤大的单元格
|
||||
if version.parse(skimage_version) >= version.parse("0.26.0"):
|
||||
region_bbox_area = region.area_bbox
|
||||
else:
|
||||
region_bbox_area = region.bbox_area
|
||||
if region_bbox_area > H * W * 3 / 4: # 过滤大的单元格
|
||||
continue
|
||||
rect = cv2.minAreaRect(region.coords[:, ::-1])
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import os
|
||||
import sys
|
||||
|
||||
from mineru.backend.vlm.utils import set_default_gpu_memory_utilization, enable_custom_logits_processors
|
||||
from mineru.backend.vlm.utils import set_default_gpu_memory_utilization, enable_custom_logits_processors, \
|
||||
mod_kwargs_by_device_type
|
||||
from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
|
||||
|
||||
from vllm.entrypoints.cli.main import main as vllm_main
|
||||
|
|
@ -50,6 +51,8 @@ def main():
|
|||
if (not has_logits_processors_arg) and custom_logits_processors:
|
||||
args.extend(["--logits-processors", "mineru_vl_utils:MinerULogitsProcessor"])
|
||||
|
||||
args = mod_kwargs_by_device_type(args, vllm_mode="server")
|
||||
|
||||
# 重构参数,将模型路径作为位置参数
|
||||
sys.argv = [sys.argv[0]] + ["serve", model_path] + args
|
||||
|
||||
|
|
|
|||
|
|
@ -186,6 +186,26 @@ def model_init(model_name: str):
|
|||
bf_16_support = True
|
||||
elif device_name.startswith("mps"):
|
||||
bf_16_support = True
|
||||
elif device_name.startswith("gcu"):
|
||||
if hasattr(torch, 'gcu') and torch.gcu.is_available():
|
||||
if torch.gcu.is_bf16_supported():
|
||||
bf_16_support = True
|
||||
elif device_name.startswith("musa"):
|
||||
if hasattr(torch, 'musa') and torch.musa.is_available():
|
||||
if torch.musa.is_bf16_supported():
|
||||
bf_16_support = True
|
||||
elif device_name.startswith("npu"):
|
||||
if hasattr(torch, 'npu') and torch.npu.is_available():
|
||||
if torch.npu.is_bf16_supported():
|
||||
bf_16_support = True
|
||||
elif device_name.startswith("mlu"):
|
||||
if hasattr(torch, 'mlu') and torch.mlu.is_available():
|
||||
if torch.mlu.is_bf16_supported():
|
||||
bf_16_support = True
|
||||
elif device_name.startswith("sdaa"):
|
||||
if hasattr(torch, 'sdaa') and torch.sdaa.is_available():
|
||||
if torch.sdaa.is_bf16_supported():
|
||||
bf_16_support = True
|
||||
|
||||
if model_name == 'layoutreader':
|
||||
# 检测modelscope的缓存目录是否存在
|
||||
|
|
|
|||
|
|
@ -86,7 +86,24 @@ def get_device():
|
|||
if torch_npu.npu.is_available():
|
||||
return "npu"
|
||||
except Exception as e:
|
||||
pass
|
||||
try:
|
||||
if torch.gcu.is_available():
|
||||
return "gcu"
|
||||
except Exception as e:
|
||||
try:
|
||||
if torch.musa.is_available():
|
||||
return "musa"
|
||||
except Exception as e:
|
||||
try:
|
||||
if torch.mlu.is_available():
|
||||
return "mlu"
|
||||
except Exception as e:
|
||||
try:
|
||||
if torch.sdaa.is_available():
|
||||
return "sdaa"
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
return "cpu"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ def llm_aided_title(page_info_list, title_aided_config):
|
|||
- 根据标题内容的语义为每个标题元素添加适当的层次结构
|
||||
- 行高较大的标题一般是更高级别的标题
|
||||
- 标题从前至后的层级必须是连续的,不能跳过层级
|
||||
- 标题层级最多为4级,不要添加过多的层级
|
||||
- 标题层级最多为6级,不要添加过多的层级
|
||||
- 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息
|
||||
|
||||
5. 合理性检查与微调:
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
包含两个MagicModel类中重复使用的方法和逻辑
|
||||
"""
|
||||
from typing import List, Dict, Any, Callable
|
||||
|
||||
from loguru import logger
|
||||
from mineru.utils.boxbase import bbox_distance, bbox_center_distance, is_in
|
||||
|
||||
|
||||
|
|
@ -172,11 +174,15 @@ def tie_up_category_by_index(
|
|||
get_subjects_func: Callable,
|
||||
get_objects_func: Callable,
|
||||
extract_subject_func: Callable = None,
|
||||
extract_object_func: Callable = None
|
||||
extract_object_func: Callable = None,
|
||||
object_block_type: str = "object",
|
||||
):
|
||||
"""
|
||||
基于index的类别关联方法,用于将主体对象与客体对象进行关联
|
||||
客体优先匹配给index最接近的主体,index差值相同时使用bbox中心点距离作为tiebreaker
|
||||
客体优先匹配给index最接近的主体,匹配优先级为:
|
||||
1. index差值(最高优先级)
|
||||
2. bbox边缘距离(相邻边距离)
|
||||
3. bbox中心点距离(最低优先级,作为最终tiebreaker)
|
||||
|
||||
参数:
|
||||
get_subjects_func: 函数,提取主体对象
|
||||
|
|
@ -207,6 +213,29 @@ def tie_up_category_by_index(
|
|||
"sub_idx": i,
|
||||
}
|
||||
|
||||
# 提取所有客体的index集合,用于计算有效index差值
|
||||
object_indices = set(obj["index"] for obj in objects)
|
||||
|
||||
def calc_effective_index_diff(obj_index: int, sub_index: int) -> int:
|
||||
"""
|
||||
计算有效的index差值
|
||||
有效差值 = 绝对差值 - 区间内其他客体的数量
|
||||
即:如果obj_index和sub_index之间的差值是由其他客体造成的,则应该扣除这部分差值
|
||||
"""
|
||||
if obj_index == sub_index:
|
||||
return 0
|
||||
|
||||
start, end = min(obj_index, sub_index), max(obj_index, sub_index)
|
||||
abs_diff = end - start
|
||||
|
||||
# 计算区间(start, end)内有多少个其他客体的index
|
||||
other_objects_count = 0
|
||||
for idx in range(start + 1, end):
|
||||
if idx in object_indices:
|
||||
other_objects_count += 1
|
||||
|
||||
return abs_diff - other_objects_count
|
||||
|
||||
# 为每个客体找到最匹配的主体
|
||||
for obj in objects:
|
||||
if len(subjects) == 0:
|
||||
|
|
@ -217,10 +246,10 @@ def tie_up_category_by_index(
|
|||
min_index_diff = float("inf")
|
||||
best_subject_indices = []
|
||||
|
||||
# 找出index差值最小的所有主体
|
||||
# 找出有效index差值最小的所有主体
|
||||
for i, subject in enumerate(subjects):
|
||||
sub_index = subject["index"]
|
||||
index_diff = abs(obj_index - sub_index)
|
||||
index_diff = calc_effective_index_diff(obj_index, sub_index)
|
||||
|
||||
if index_diff < min_index_diff:
|
||||
min_index_diff = index_diff
|
||||
|
|
@ -228,18 +257,37 @@ def tie_up_category_by_index(
|
|||
elif index_diff == min_index_diff:
|
||||
best_subject_indices.append(i)
|
||||
|
||||
# 如果有多个主体的index差值相同,使用中心点距离作为tiebreaker
|
||||
if len(best_subject_indices) > 1:
|
||||
min_center_dist = float("inf")
|
||||
if len(best_subject_indices) == 1:
|
||||
best_subject_idx = best_subject_indices[0]
|
||||
# 如果有多个主体的index差值相同(最多两个),根据边缘距离进行筛选
|
||||
elif len(best_subject_indices) == 2:
|
||||
# 计算所有候选主体的边缘距离
|
||||
edge_distances = [(idx, bbox_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices]
|
||||
edge_dist_diff = abs(edge_distances[0][1] - edge_distances[1][1])
|
||||
|
||||
for idx in best_subject_indices:
|
||||
center_dist = bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])
|
||||
if center_dist < min_center_dist:
|
||||
min_center_dist = center_dist
|
||||
best_subject_idx = idx
|
||||
for idx, edge_dist in edge_distances:
|
||||
logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Edge distance: {edge_dist}")
|
||||
|
||||
if edge_dist_diff > 2:
|
||||
# 边缘距离差值大于2,匹配边缘距离更小的主体
|
||||
best_subject_idx = min(edge_distances, key=lambda x: x[1])[0]
|
||||
logger.debug(f"Obj index: {obj_index}, edge_dist_diff > 2, matching to subject with min edge distance, index: {subjects[best_subject_idx]['index']}")
|
||||
elif object_block_type == "table_caption":
|
||||
# 边缘距离差值<=2且为table_caption,匹配index更大的主体
|
||||
best_subject_idx = max(best_subject_indices, key=lambda idx: subjects[idx]["index"])
|
||||
logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and table_caption, matching to later subject with index: {subjects[best_subject_idx]['index']}")
|
||||
elif object_block_type.endswith("footnote"):
|
||||
# 边缘距离差值<=2且为footnote,匹配index更小的主体
|
||||
best_subject_idx = min(best_subject_indices, key=lambda idx: subjects[idx]["index"])
|
||||
logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and footnote, matching to earlier subject with index: {subjects[best_subject_idx]['index']}")
|
||||
else:
|
||||
# 边缘距离差值<=2 且不适用特殊匹配规则,使用中心点距离匹配
|
||||
center_distances = [(idx, bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices]
|
||||
for idx, center_dist in center_distances:
|
||||
logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Center distance: {center_dist}")
|
||||
best_subject_idx = min(center_distances, key=lambda x: x[1])[0]
|
||||
else:
|
||||
best_subject_idx = best_subject_indices[0]
|
||||
raise ValueError("More than two subjects have the same minimal index difference, which is unexpected.")
|
||||
|
||||
# 将客体添加到最佳主体的obj_bboxes中
|
||||
result_dict[best_subject_idx]["obj_bboxes"].append(extract_object_func(obj))
|
||||
|
|
|
|||
|
|
@ -414,7 +414,7 @@ def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshol
|
|||
|
||||
|
||||
def clean_memory(device='cuda'):
|
||||
if device == 'cuda':
|
||||
if str(device).startswith("cuda"):
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
torch.cuda.ipc_collect()
|
||||
|
|
@ -423,6 +423,18 @@ def clean_memory(device='cuda'):
|
|||
torch_npu.npu.empty_cache()
|
||||
elif str(device).startswith("mps"):
|
||||
torch.mps.empty_cache()
|
||||
elif str(device).startswith("gcu"):
|
||||
if torch.gcu.is_available():
|
||||
torch.gcu.empty_cache()
|
||||
elif str(device).startswith("musa"):
|
||||
if torch.musa.is_available():
|
||||
torch.musa.empty_cache()
|
||||
elif str(device).startswith("mlu"):
|
||||
if torch.mlu.is_available():
|
||||
torch.mlu.empty_cache()
|
||||
elif str(device).startswith("sdaa"):
|
||||
if torch.sdaa.is_available():
|
||||
torch.sdaa.empty_cache()
|
||||
gc.collect()
|
||||
|
||||
|
||||
|
|
@ -458,5 +470,17 @@ def get_vram(device) -> int:
|
|||
elif str(device).startswith("npu"):
|
||||
if torch_npu.npu.is_available():
|
||||
total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB
|
||||
elif str(device).startswith("gcu"):
|
||||
if torch.gcu.is_available():
|
||||
total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB
|
||||
elif str(device).startswith("musa"):
|
||||
if torch.musa.is_available():
|
||||
total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB
|
||||
elif str(device).startswith("mlu"):
|
||||
if torch.mlu.is_available():
|
||||
total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB
|
||||
elif str(device).startswith("sdaa"):
|
||||
if torch.sdaa.is_available():
|
||||
total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB
|
||||
|
||||
return total_memory
|
||||
|
|
|
|||
|
|
@ -11,6 +11,11 @@ def get_load_images_timeout() -> int:
|
|||
return get_value_from_string(env_value, 300)
|
||||
|
||||
|
||||
def get_load_images_threads() -> int:
|
||||
env_value = os.getenv('MINERU_PDF_RENDER_THREADS', None)
|
||||
return get_value_from_string(env_value, 4)
|
||||
|
||||
|
||||
def get_value_from_string(env_value: str, default_value: int) -> int:
|
||||
if env_value is not None:
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
# Copyright (c) Opendatalab. All rights reserved.
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from io import BytesIO
|
||||
|
||||
import numpy as np
|
||||
|
|
@ -9,13 +11,13 @@ from PIL import Image, ImageOps
|
|||
|
||||
from mineru.data.data_reader_writer import FileBasedDataWriter
|
||||
from mineru.utils.check_sys_env import is_windows_environment
|
||||
from mineru.utils.os_env_config import get_load_images_timeout
|
||||
from mineru.utils.os_env_config import get_load_images_timeout, get_load_images_threads
|
||||
from mineru.utils.pdf_reader import image_to_b64str, image_to_bytes, page_to_image
|
||||
from mineru.utils.enum_class import ImageType
|
||||
from mineru.utils.hash_utils import str_sha256
|
||||
from mineru.utils.pdf_page_id import get_end_page_id
|
||||
|
||||
from concurrent.futures import ProcessPoolExecutor, TimeoutError as FuturesTimeoutError
|
||||
from concurrent.futures import ProcessPoolExecutor, wait, ALL_COMPLETED
|
||||
|
||||
|
||||
def pdf_page_to_image(page: pdfium.PdfPage, dpi=200, image_type=ImageType.PIL) -> dict:
|
||||
|
|
@ -57,7 +59,7 @@ def load_images_from_pdf(
|
|||
end_page_id=None,
|
||||
image_type=ImageType.PIL,
|
||||
timeout=None,
|
||||
threads=4,
|
||||
threads=None,
|
||||
):
|
||||
"""带超时控制的 PDF 转图片函数,支持多进程加速
|
||||
|
||||
|
|
@ -67,8 +69,8 @@ def load_images_from_pdf(
|
|||
start_page_id (int, optional): 起始页码. Defaults to 0.
|
||||
end_page_id (int | None, optional): 结束页码. Defaults to None.
|
||||
image_type (ImageType, optional): 图片类型. Defaults to ImageType.PIL.
|
||||
timeout (int | None, optional): 超时时间(秒)。如果为 None,则从环境变量 MINERU_PDF_LOAD_IMAGES_TIMEOUT 读取,若未设置则默认为 300 秒。
|
||||
threads (int): 进程数,默认 4
|
||||
timeout (int | None, optional): 超时时间(秒)。如果为 None,则从环境变量 MINERU_PDF_RENDER_TIMEOUT 读取,若未设置则默认为 300 秒。
|
||||
threads (int): 进程数, 如果为 None,则从环境变量 MINERU_PDF_RENDER_THREADS 读取,若未设置则默认为 4.
|
||||
|
||||
Raises:
|
||||
TimeoutError: 当转换超时时抛出
|
||||
|
|
@ -86,6 +88,9 @@ def load_images_from_pdf(
|
|||
else:
|
||||
if timeout is None:
|
||||
timeout = get_load_images_timeout()
|
||||
if threads is None:
|
||||
threads = get_load_images_threads()
|
||||
|
||||
end_page_id = get_end_page_id(end_page_id, len(pdf_doc))
|
||||
|
||||
# 计算总页数
|
||||
|
|
@ -108,11 +113,13 @@ def load_images_from_pdf(
|
|||
|
||||
page_ranges.append((range_start, range_end))
|
||||
|
||||
# logger.debug(f"PDF to images using {actual_threads} processes, page ranges: {page_ranges}")
|
||||
logger.debug(f"PDF to images using {actual_threads} processes, page ranges: {page_ranges}")
|
||||
|
||||
with ProcessPoolExecutor(max_workers=actual_threads) as executor:
|
||||
executor = ProcessPoolExecutor(max_workers=actual_threads)
|
||||
try:
|
||||
# 提交所有任务
|
||||
futures = []
|
||||
future_to_range = {}
|
||||
for range_start, range_end in page_ranges:
|
||||
future = executor.submit(
|
||||
_load_images_from_pdf_worker,
|
||||
|
|
@ -122,27 +129,68 @@ def load_images_from_pdf(
|
|||
range_end,
|
||||
image_type,
|
||||
)
|
||||
futures.append((range_start, future))
|
||||
futures.append(future)
|
||||
future_to_range[future] = range_start
|
||||
|
||||
try:
|
||||
# 收集结果并按页码排序
|
||||
all_results = []
|
||||
for range_start, future in futures:
|
||||
images_list = future.result(timeout=timeout)
|
||||
all_results.append((range_start, images_list))
|
||||
# 使用 wait() 设置单一全局超时
|
||||
done, not_done = wait(futures, timeout=timeout, return_when=ALL_COMPLETED)
|
||||
|
||||
# 按起始页码排序并合并结果
|
||||
all_results.sort(key=lambda x: x[0])
|
||||
images_list = []
|
||||
for _, imgs in all_results:
|
||||
images_list.extend(imgs)
|
||||
|
||||
return images_list, pdf_doc
|
||||
except FuturesTimeoutError:
|
||||
# 检查是否有未完成的任务(超时情况)
|
||||
if not_done:
|
||||
# 超时:强制终止所有子进程
|
||||
_terminate_executor_processes(executor)
|
||||
pdf_doc.close()
|
||||
executor.shutdown(wait=False, cancel_futures=True)
|
||||
raise TimeoutError(f"PDF to images conversion timeout after {timeout}s")
|
||||
|
||||
# 所有任务完成,收集结果
|
||||
all_results = []
|
||||
for future in futures:
|
||||
range_start = future_to_range[future]
|
||||
# 这里不需要 timeout,因为任务已完成
|
||||
images_list = future.result()
|
||||
all_results.append((range_start, images_list))
|
||||
|
||||
# 按起始页码排序并合并结果
|
||||
all_results.sort(key=lambda x: x[0])
|
||||
images_list = []
|
||||
for _, imgs in all_results:
|
||||
images_list.extend(imgs)
|
||||
|
||||
return images_list, pdf_doc
|
||||
|
||||
except Exception as e:
|
||||
# 发生任何异常时,确保清理子进程
|
||||
_terminate_executor_processes(executor)
|
||||
pdf_doc.close()
|
||||
if isinstance(e, TimeoutError):
|
||||
raise
|
||||
raise
|
||||
finally:
|
||||
executor.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
|
||||
def _terminate_executor_processes(executor):
|
||||
"""强制终止 ProcessPoolExecutor 中的所有子进程"""
|
||||
if hasattr(executor, '_processes'):
|
||||
for pid, process in executor._processes.items():
|
||||
if process.is_alive():
|
||||
try:
|
||||
# 先发送 SIGTERM 允许优雅退出
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
except (ProcessLookupError, OSError):
|
||||
pass
|
||||
|
||||
# 给子进程一点时间响应 SIGTERM
|
||||
time.sleep(0.1)
|
||||
|
||||
# 对仍然存活的进程发送 SIGKILL 强制终止
|
||||
for pid, process in executor._processes.items():
|
||||
if process.is_alive():
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except (ProcessLookupError, OSError):
|
||||
pass
|
||||
|
||||
|
||||
def load_images_from_pdf_core(
|
||||
pdf_bytes: bytes,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ CONTINUATION_END_MARKERS = [
|
|||
"(cont.)",
|
||||
"(cont’d)",
|
||||
"(…continued)",
|
||||
"续表",
|
||||
]
|
||||
|
||||
CONTINUATION_INLINE_MARKERS = [
|
||||
|
|
@ -69,6 +70,69 @@ def calculate_table_total_columns(soup):
|
|||
return max_cols
|
||||
|
||||
|
||||
def build_table_occupied_matrix(soup):
|
||||
"""构建表格的占用矩阵,返回每行的有效列数
|
||||
|
||||
Args:
|
||||
soup: BeautifulSoup解析的表格
|
||||
|
||||
Returns:
|
||||
dict: {row_idx: effective_columns} 每行的有效列数(考虑rowspan占用)
|
||||
"""
|
||||
rows = soup.find_all("tr")
|
||||
if not rows:
|
||||
return {}
|
||||
|
||||
occupied = {} # {row_idx: {col_idx: True}}
|
||||
row_effective_cols = {} # {row_idx: effective_columns}
|
||||
|
||||
for row_idx, row in enumerate(rows):
|
||||
col_idx = 0
|
||||
cells = row.find_all(["td", "th"])
|
||||
|
||||
if row_idx not in occupied:
|
||||
occupied[row_idx] = {}
|
||||
|
||||
for cell in cells:
|
||||
# 找到下一个未被占用的列位置
|
||||
while col_idx in occupied[row_idx]:
|
||||
col_idx += 1
|
||||
|
||||
colspan = int(cell.get("colspan", 1))
|
||||
rowspan = int(cell.get("rowspan", 1))
|
||||
|
||||
# 标记被这个单元格占用的所有位置
|
||||
for r in range(row_idx, row_idx + rowspan):
|
||||
if r not in occupied:
|
||||
occupied[r] = {}
|
||||
for c in range(col_idx, col_idx + colspan):
|
||||
occupied[r][c] = True
|
||||
|
||||
col_idx += colspan
|
||||
|
||||
# 该行的有效列数为已占用的最大列索引+1
|
||||
if occupied[row_idx]:
|
||||
row_effective_cols[row_idx] = max(occupied[row_idx].keys()) + 1
|
||||
else:
|
||||
row_effective_cols[row_idx] = 0
|
||||
|
||||
return row_effective_cols
|
||||
|
||||
|
||||
def calculate_row_effective_columns(soup, row_idx):
|
||||
"""计算指定行的有效列数(考虑rowspan占用)
|
||||
|
||||
Args:
|
||||
soup: BeautifulSoup解析的表格
|
||||
row_idx: 行索引
|
||||
|
||||
Returns:
|
||||
int: 该行的有效列数
|
||||
"""
|
||||
row_effective_cols = build_table_occupied_matrix(soup)
|
||||
return row_effective_cols.get(row_idx, 0)
|
||||
|
||||
|
||||
def calculate_row_columns(row):
|
||||
"""
|
||||
计算表格行的实际列数,考虑colspan属性
|
||||
|
|
@ -118,6 +182,10 @@ def detect_table_headers(soup1, soup2, max_header_rows=5):
|
|||
rows1 = soup1.find_all("tr")
|
||||
rows2 = soup2.find_all("tr")
|
||||
|
||||
# 构建两个表格的有效列数矩阵
|
||||
effective_cols1 = build_table_occupied_matrix(soup1)
|
||||
effective_cols2 = build_table_occupied_matrix(soup2)
|
||||
|
||||
min_rows = min(len(rows1), len(rows2), max_header_rows)
|
||||
header_rows = 0
|
||||
headers_match = True
|
||||
|
|
@ -135,20 +203,24 @@ def detect_table_headers(soup1, soup2, max_header_rows=5):
|
|||
if len(cells1) != len(cells2):
|
||||
structure_match = False
|
||||
else:
|
||||
# 然后检查单元格的属性和内容
|
||||
for cell1, cell2 in zip(cells1, cells2):
|
||||
colspan1 = int(cell1.get("colspan", 1))
|
||||
rowspan1 = int(cell1.get("rowspan", 1))
|
||||
colspan2 = int(cell2.get("colspan", 1))
|
||||
rowspan2 = int(cell2.get("rowspan", 1))
|
||||
# 检查有效列数是否一致(考虑rowspan影响)
|
||||
if effective_cols1.get(i, 0) != effective_cols2.get(i, 0):
|
||||
structure_match = False
|
||||
else:
|
||||
# 然后检查单元格的属性和内容
|
||||
for cell1, cell2 in zip(cells1, cells2):
|
||||
colspan1 = int(cell1.get("colspan", 1))
|
||||
rowspan1 = int(cell1.get("rowspan", 1))
|
||||
colspan2 = int(cell2.get("colspan", 1))
|
||||
rowspan2 = int(cell2.get("rowspan", 1))
|
||||
|
||||
# 去除所有空白字符(包括空格、换行、制表符等)
|
||||
text1 = ''.join(full_to_half(cell1.get_text()).split())
|
||||
text2 = ''.join(full_to_half(cell2.get_text()).split())
|
||||
# 去除所有空白字符(包括空格、换行、制表符等)
|
||||
text1 = ''.join(full_to_half(cell1.get_text()).split())
|
||||
text2 = ''.join(full_to_half(cell2.get_text()).split())
|
||||
|
||||
if colspan1 != colspan2 or rowspan1 != rowspan2 or text1 != text2:
|
||||
structure_match = False
|
||||
break
|
||||
if colspan1 != colspan2 or rowspan1 != rowspan2 or text1 != text2:
|
||||
structure_match = False
|
||||
break
|
||||
|
||||
if structure_match:
|
||||
header_rows += 1
|
||||
|
|
@ -158,7 +230,54 @@ def detect_table_headers(soup1, soup2, max_header_rows=5):
|
|||
headers_match = header_rows > 0 # 只有当至少匹配了一行时,才认为表头匹配
|
||||
break
|
||||
|
||||
# 如果没有找到匹配的表头行,则返回失败
|
||||
# 如果严格匹配失败,尝试视觉一致性匹配(只比较文本内容)
|
||||
if header_rows == 0:
|
||||
header_rows, headers_match, header_texts = _detect_table_headers_visual(soup1, soup2, rows1, rows2, max_header_rows)
|
||||
|
||||
return header_rows, headers_match, header_texts
|
||||
|
||||
|
||||
def _detect_table_headers_visual(soup1, soup2, rows1, rows2, max_header_rows=5):
|
||||
"""
|
||||
基于视觉一致性检测表头(只比较文本内容,忽略colspan/rowspan差异)
|
||||
|
||||
Args:
|
||||
soup1: 第一个表格的BeautifulSoup对象
|
||||
soup2: 第二个表格的BeautifulSoup对象
|
||||
rows1: 第一个表格的行列表
|
||||
rows2: 第二个表格的行列表
|
||||
max_header_rows: 最大可能的表头行数
|
||||
|
||||
Returns:
|
||||
tuple: (表头行数, 表头是否一致, 表头文本列表)
|
||||
"""
|
||||
# 构建两个表格的有效列数矩阵
|
||||
effective_cols1 = build_table_occupied_matrix(soup1)
|
||||
effective_cols2 = build_table_occupied_matrix(soup2)
|
||||
|
||||
min_rows = min(len(rows1), len(rows2), max_header_rows)
|
||||
header_rows = 0
|
||||
headers_match = True
|
||||
header_texts = []
|
||||
|
||||
for i in range(min_rows):
|
||||
cells1 = rows1[i].find_all(["td", "th"])
|
||||
cells2 = rows2[i].find_all(["td", "th"])
|
||||
|
||||
# 提取每行的文本内容列表(去除空白字符)
|
||||
texts1 = [''.join(full_to_half(cell.get_text()).split()) for cell in cells1]
|
||||
texts2 = [''.join(full_to_half(cell.get_text()).split()) for cell in cells2]
|
||||
|
||||
# 检查视觉一致性:文本内容完全相同,且有效列数一致
|
||||
effective_cols_match = effective_cols1.get(i, 0) == effective_cols2.get(i, 0)
|
||||
if texts1 == texts2 and effective_cols_match:
|
||||
header_rows += 1
|
||||
row_texts = [full_to_half(cell.get_text().strip()) for cell in cells1]
|
||||
header_texts.append(row_texts)
|
||||
else:
|
||||
headers_match = header_rows > 0
|
||||
break
|
||||
|
||||
if header_rows == 0:
|
||||
headers_match = False
|
||||
|
||||
|
|
@ -243,34 +362,44 @@ def check_rows_match(soup1, soup2):
|
|||
if not (rows1 and rows2):
|
||||
return False
|
||||
|
||||
# 获取第一个表的最后一行数据行
|
||||
# 获取第一个表的最后一行数据行索引
|
||||
last_row_idx = None
|
||||
last_row = None
|
||||
for row in reversed(rows1):
|
||||
if row.find_all(["td", "th"]):
|
||||
last_row = row
|
||||
for idx in range(len(rows1) - 1, -1, -1):
|
||||
if rows1[idx].find_all(["td", "th"]):
|
||||
last_row_idx = idx
|
||||
last_row = rows1[idx]
|
||||
break
|
||||
|
||||
# 检测表头行数,以便获取第二个表的首个数据行
|
||||
header_count, _, _ = detect_table_headers(soup1, soup2)
|
||||
|
||||
# 获取第二个表的首个数据行
|
||||
first_data_row_idx = None
|
||||
first_data_row = None
|
||||
if len(rows2) > header_count:
|
||||
first_data_row_idx = header_count
|
||||
first_data_row = rows2[header_count] # 第一个非表头行
|
||||
|
||||
if not (last_row and first_data_row):
|
||||
return False
|
||||
|
||||
# 计算实际列数(考虑colspan)和视觉列数
|
||||
# 计算有效列数(考虑rowspan和colspan)
|
||||
last_row_effective_cols = calculate_row_effective_columns(soup1, last_row_idx)
|
||||
first_row_effective_cols = calculate_row_effective_columns(soup2, first_data_row_idx)
|
||||
|
||||
# 计算实际列数(仅考虑colspan)和视觉列数
|
||||
last_row_cols = calculate_row_columns(last_row)
|
||||
first_row_cols = calculate_row_columns(first_data_row)
|
||||
last_row_visual_cols = calculate_visual_columns(last_row)
|
||||
first_row_visual_cols = calculate_visual_columns(first_data_row)
|
||||
|
||||
# logger.debug(f"行列数 - 前表最后一行: {last_row_cols}(视觉列数:{last_row_visual_cols}), 当前表首行: {first_row_cols}(视觉列数:{first_row_visual_cols})")
|
||||
# logger.debug(f"行列数 - 前表最后一行: {last_row_cols}(有效列数:{last_row_effective_cols}, 视觉列数:{last_row_visual_cols}), 当前表首行: {first_row_cols}(有效列数:{first_row_effective_cols}, 视觉列数:{first_row_visual_cols})")
|
||||
|
||||
# 同时考虑实际列数匹配和视觉列数匹配
|
||||
return last_row_cols == first_row_cols or last_row_visual_cols == first_row_visual_cols
|
||||
# 同时考虑有效列数匹配、实际列数匹配和视觉列数匹配
|
||||
return (last_row_effective_cols == first_row_effective_cols or
|
||||
last_row_cols == first_row_cols or
|
||||
last_row_visual_cols == first_row_visual_cols)
|
||||
|
||||
|
||||
def check_row_columns_match(row1, row2):
|
||||
|
|
@ -287,12 +416,13 @@ def check_row_columns_match(row1, row2):
|
|||
return True
|
||||
|
||||
|
||||
def adjust_table_rows_colspan(rows, start_idx, end_idx,
|
||||
def adjust_table_rows_colspan(soup, rows, start_idx, end_idx,
|
||||
reference_structure, reference_visual_cols,
|
||||
target_cols, current_cols, reference_row):
|
||||
"""调整表格行的colspan属性以匹配目标列数
|
||||
|
||||
Args:
|
||||
soup: BeautifulSoup解析的表格对象(用于计算有效列数)
|
||||
rows: 表格行列表
|
||||
start_idx: 起始行索引
|
||||
end_idx: 结束行索引(不包含)
|
||||
|
|
@ -304,14 +434,21 @@ def adjust_table_rows_colspan(rows, start_idx, end_idx,
|
|||
"""
|
||||
reference_row_copy = deepcopy(reference_row)
|
||||
|
||||
# 构建有效列数矩阵
|
||||
effective_cols_matrix = build_table_occupied_matrix(soup)
|
||||
|
||||
for i in range(start_idx, end_idx):
|
||||
row = rows[i]
|
||||
cells = row.find_all(["td", "th"])
|
||||
if not cells:
|
||||
continue
|
||||
|
||||
# 使用有效列数(考虑rowspan)判断是否需要调整
|
||||
current_row_effective_cols = effective_cols_matrix.get(i, 0)
|
||||
current_row_cols = calculate_row_columns(row)
|
||||
if current_row_cols >= target_cols:
|
||||
|
||||
# 如果有效列数或实际列数已经达到目标,则跳过
|
||||
if current_row_effective_cols >= target_cols or current_row_cols >= target_cols:
|
||||
continue
|
||||
|
||||
# 检查是否与参考行结构匹配
|
||||
|
|
@ -323,9 +460,12 @@ def adjust_table_rows_colspan(rows, start_idx, end_idx,
|
|||
cell["colspan"] = str(reference_structure[j])
|
||||
else:
|
||||
# 扩展最后一个单元格以填补列数差异
|
||||
last_cell = cells[-1]
|
||||
current_last_span = int(last_cell.get("colspan", 1))
|
||||
last_cell["colspan"] = str(current_last_span + (target_cols - current_cols))
|
||||
# 使用有效列数来计算差异
|
||||
cols_diff = target_cols - current_row_effective_cols
|
||||
if cols_diff > 0:
|
||||
last_cell = cells[-1]
|
||||
current_last_span = int(last_cell.get("colspan", 1))
|
||||
last_cell["colspan"] = str(current_last_span + cols_diff)
|
||||
|
||||
|
||||
def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_footnotes):
|
||||
|
|
@ -356,7 +496,7 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo
|
|||
reference_visual_cols = calculate_visual_columns(last_row1)
|
||||
# 以表1的最后一行为参考,调整表2的行
|
||||
adjust_table_rows_colspan(
|
||||
rows2, header_count, len(rows2),
|
||||
soup2, rows2, header_count, len(rows2),
|
||||
reference_structure, reference_visual_cols,
|
||||
table_cols1, table_cols2, first_data_row2
|
||||
)
|
||||
|
|
@ -366,7 +506,7 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo
|
|||
reference_visual_cols = calculate_visual_columns(first_data_row2)
|
||||
# 以表2的第一个数据行为参考,调整表1的行
|
||||
adjust_table_rows_colspan(
|
||||
rows1, 0, len(rows1),
|
||||
soup1, rows1, 0, len(rows1),
|
||||
reference_structure, reference_visual_cols,
|
||||
table_cols2, table_cols1, last_row1
|
||||
)
|
||||
|
|
@ -445,4 +585,4 @@ def merge_table(page_info_list):
|
|||
# 删除当前页的table
|
||||
for block in current_table_block["blocks"]:
|
||||
block['lines'] = []
|
||||
block[SplitFlag.LINES_DELETED] = True
|
||||
block[SplitFlag.LINES_DELETED] = True
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
__version__ = "2.7.1"
|
||||
__version__ = "2.7.6"
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# 天枢项目依赖
|
||||
|
||||
# Core MinerU
|
||||
mineru[core]>=2.5.0
|
||||
mineru[core]==2.7.6
|
||||
|
||||
# Image Augmentation (Version Pinned for Compatibility)
|
||||
albumentations>=1.4.4,<2.0.0
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ dependencies = [
|
|||
"pypdfium2>=4.30.0",
|
||||
"pypdf>=5.6.0",
|
||||
"reportlab",
|
||||
"python-docx>=1.2,<2",
|
||||
"pydantic>=2.12,<3",
|
||||
"pdftext>=0.6.3",
|
||||
"modelscope>=1.26.0",
|
||||
"huggingface-hub>=0.32.4",
|
||||
|
|
@ -99,7 +101,7 @@ all = [
|
|||
"mineru[core]",
|
||||
"mineru[mlx] ; sys_platform == 'darwin'",
|
||||
"mineru[vllm] ; sys_platform == 'linux'",
|
||||
"mineru[lmdeploy] ; sys_platform == 'windows'",
|
||||
"mineru[lmdeploy] ; sys_platform == 'win32'",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
|
@ -125,7 +127,7 @@ include = ["mineru*"]
|
|||
namespaces = false
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"mineru" = ["resources/**"]
|
||||
"mineru" = ["resources/**", "cli/static/**"]
|
||||
"mineru.model.utils.pytorchocr.utils" = ["resources/**"]
|
||||
|
||||
[tool.setuptools]
|
||||
|
|
@ -162,4 +164,4 @@ exclude_also = [
|
|||
'if TYPE_CHECKING:',
|
||||
'class .*\bProtocol\):',
|
||||
'@(abc\.)?abstractmethod',
|
||||
]
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
"""Keep the base image's accelerator wheels while resolving application dependencies."""
|
||||
import argparse
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def accelerator_versions():
|
||||
packages = {}
|
||||
for name in ('torch', 'torchvision', 'torchaudio', 'vllm', 'triton', 'xformers'):
|
||||
try:
|
||||
packages[name] = version(name)
|
||||
except PackageNotFoundError:
|
||||
if name in ('torch', 'torchvision', 'vllm'):
|
||||
raise RuntimeError(f'The accelerator base image must provide {name}') from None
|
||||
return packages
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('path', type=Path)
|
||||
parser.add_argument('--check', action='store_true')
|
||||
args = parser.parse_args()
|
||||
installed = accelerator_versions()
|
||||
if args.check:
|
||||
expected = dict(line.split('==', 1) for line in args.path.read_text().splitlines() if line)
|
||||
if installed != expected:
|
||||
raise RuntimeError('Accelerator packages changed during dependency installation')
|
||||
else:
|
||||
args.path.write_text(''.join(f'{name}=={value}\n' for name, value in installed.items()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
VERSION=${VERSION:-2.7.6}
|
||||
API_FLAVOR=${API_FLAVOR:-corex}
|
||||
ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd)
|
||||
DOCKER=${DOCKER:-docker}
|
||||
cd "$ROOT_DIR"
|
||||
case "$API_FLAVOR" in
|
||||
corex) API_DOCKERFILE=docker/china/Dockerfile.corex ;;
|
||||
cuda) API_DOCKERFILE=docker/global/Dockerfile.cuda ;;
|
||||
*) echo 'API_FLAVOR must be corex or cuda.' >&2; exit 1 ;;
|
||||
esac
|
||||
"$DOCKER" build -f "$API_DOCKERFILE" -t "unis-mindmap-api:${VERSION}-${API_FLAVOR}" -t "unis-mindmap-api:${API_FLAVOR}" .
|
||||
"$DOCKER" build -f web_ui/Dockerfile.portable -t "unis-mindmap-web:${VERSION}" web_ui
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
"""Start the checked-out MinerU 2.7.6 application with its normal CLI options."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
if __name__ == '__main__':
|
||||
from mineru.version import __version__
|
||||
if __version__ != '2.7.6':
|
||||
raise RuntimeError('This launcher requires MinerU 2.7.6')
|
||||
from mineru.cli.fast_api import main
|
||||
main()
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
DOCKER=${DOCKER:-docker}
|
||||
API_FLAVOR=${API_FLAVOR:-corex}
|
||||
VERSION=${VERSION:-2.7.6}
|
||||
NETWORK=${NETWORK:-unis-ai}
|
||||
API_NAME=${API_NAME:-mineru-276-api}
|
||||
WEB_NAME=${WEB_NAME:-mindmap-276-web}
|
||||
WEB_PORT=${WEB_PORT:-9898}
|
||||
API_PORT=${API_PORT:-8100}
|
||||
MINERU_MODEL_DIR=${MINERU_MODEL_DIR:-/data/unis/mineru-models}
|
||||
case "$API_FLAVOR" in
|
||||
cuda)
|
||||
GPU_ARGS=(--gpus "device=${GPU_IDS:-0}")
|
||||
;;
|
||||
corex)
|
||||
GPU_ARGS=(--privileged --pid=host --group-add video
|
||||
-v /dev:/dev -v /usr/src:/usr/src:ro -v /lib/modules:/lib/modules:ro
|
||||
-e MINERU_VLLM_DEVICE=corex -e "CUDA_VISIBLE_DEVICES=${GPU_IDS:-0}")
|
||||
;;
|
||||
*) echo 'API_FLAVOR must be corex or cuda.' >&2; exit 1 ;;
|
||||
esac
|
||||
for name in "$API_NAME" "$WEB_NAME"; do
|
||||
if "$DOCKER" container inspect "$name" >/dev/null 2>&1; then
|
||||
echo "Container $name already exists. Set a new name or manage it explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ ! -d "$MINERU_MODEL_DIR/pipeline" ] || [ ! -d "$MINERU_MODEL_DIR/vlm" ]; then
|
||||
echo 'Prepare the pipeline and vlm model directories before starting.' >&2
|
||||
exit 1
|
||||
fi
|
||||
"$DOCKER" network inspect "$NETWORK" >/dev/null 2>&1 || "$DOCKER" network create "$NETWORK"
|
||||
"$DOCKER" run -d --name "$API_NAME" --network "$NETWORK" "${GPU_ARGS[@]}" --ipc=host --shm-size=32g \
|
||||
-p "127.0.0.1:${API_PORT}:8000" -v "${MINERU_MODEL_DIR}:/models:ro" \
|
||||
-e MINERU_MODEL_SOURCE=local -e "MINERU_GPU_MEMORY_UTILIZATION=${MINERU_GPU_MEMORY_UTILIZATION:-0.5}" \
|
||||
"unis-mindmap-api:${VERSION}-${API_FLAVOR}"
|
||||
"$DOCKER" run -d --name "$WEB_NAME" --network "$NETWORK" -p "${WEB_PORT}:9898" \
|
||||
-e "MINERU_API_URL=http://${API_NAME}:8000" "unis-mindmap-web:${VERSION}"
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
"""Protocol regressions without loading models or accelerator runtimes."""
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
from types import ModuleType
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
class HeadingTests(unittest.TestCase):
|
||||
def test_markdown_and_content_lists_keep_levels_five_and_six(self):
|
||||
from mineru.utils.enum_class import BlockType, ContentType, MakeMode
|
||||
for backend, render in (
|
||||
('pipeline', 'make_blocks_to_markdown'), ('vlm', 'mk_blocks_to_markdown'),
|
||||
):
|
||||
path = ROOT / f'mineru/backend/{backend}/{backend}_middle_json_mkcontent.py'
|
||||
source = ast.parse(path.read_text(encoding='utf-8'))
|
||||
names = {'get_title_level', render, 'make_blocks_to_content_list'}
|
||||
functions = ast.Module(body=[node for node in source.body if isinstance(node, ast.FunctionDef)
|
||||
and node.name in names], type_ignores=[])
|
||||
scope = {'BlockType': BlockType, 'ContentType': ContentType, 'MakeMode': MakeMode,
|
||||
'merge_para_with_text': lambda block: block['text']}
|
||||
exec(compile(functions, str(path), 'exec'), scope)
|
||||
for level in (1, 4, 5, 6, 9):
|
||||
with self.subTest(backend=backend, level=level):
|
||||
block = {'type': BlockType.TITLE, 'level': level, 'text': 'Heading', 'bbox': [0, 0, 10, 10]}
|
||||
args = ([block], MakeMode.MM_MD)
|
||||
if backend == 'vlm':
|
||||
args += (True, True)
|
||||
self.assertEqual(scope[render](*args), ['#' * min(level, 6) + ' Heading'])
|
||||
content = scope['make_blocks_to_content_list'](block, '', 0, [100, 100])
|
||||
self.assertEqual(content['text_level'], min(level, 6))
|
||||
|
||||
|
||||
class ProtocolTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
common = ModuleType('mineru.cli.common')
|
||||
common.aio_do_parse = Mock()
|
||||
common.read_fn = lambda path: Path(path).read_bytes()
|
||||
common.pdf_suffixes, common.image_suffixes, common.word_suffixes = ['pdf'], ['png'], ['docx', 'doc']
|
||||
config = ModuleType('mineru.utils.config_reader')
|
||||
config.get_device = lambda: 'cpu'
|
||||
models = ModuleType('mineru.utils.model_utils')
|
||||
models.clean_memory = Mock()
|
||||
suffixes = ModuleType('mineru.utils.guess_suffix_or_lang')
|
||||
suffixes.guess_suffix_by_path = lambda path: Path(path).suffix.lstrip('.')
|
||||
cls.stubs = patch.dict(sys.modules, {module.__name__: module for module in (common, config, models, suffixes)})
|
||||
cls.stubs.start()
|
||||
spec = importlib.util.spec_from_file_location('parser276_api_test', ROOT / 'mineru/cli/fast_api.py')
|
||||
cls.api = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(cls.api)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.stubs.stop()
|
||||
|
||||
def setUp(self):
|
||||
from fastapi.testclient import TestClient
|
||||
self.temp = tempfile.TemporaryDirectory(dir=ROOT / 'tests')
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.directory = Path(self.temp.name)
|
||||
temp_patch = patch.object(tempfile, 'tempdir', self.temp.name)
|
||||
temp_patch.start()
|
||||
self.addCleanup(temp_patch.stop)
|
||||
self.api._task_progress_dir = self.directory / 'progress'
|
||||
self.api._task_progress.clear()
|
||||
self.api.app = self.api.create_app()
|
||||
self.client = TestClient(self.api.app)
|
||||
self.addCleanup(self.client.close)
|
||||
|
||||
async def fake_parse(**kwargs):
|
||||
self.engine_options = kwargs
|
||||
for name in kwargs['pdf_file_names']:
|
||||
backend = kwargs['backend']
|
||||
subdir = kwargs['parse_method'] if backend == 'pipeline' else (
|
||||
'vlm' if backend.startswith('vlm') else 'hybrid_' + kwargs['parse_method'])
|
||||
folder = Path(kwargs['output_dir']) / name / subdir
|
||||
(folder / 'images').mkdir(parents=True)
|
||||
(folder / f'{name}.md').write_text('# Chapter\n##### Detail\n###### Leaf\n')
|
||||
for suffix, data in (('_middle.json', {'pdf_info': [{'level': 6}]}),
|
||||
('_model.json', [{'level': 6}]), ('_content_list.json', [{'text_level': 6}])):
|
||||
(folder / (name + suffix)).write_text(json.dumps(data))
|
||||
(folder / 'images/a.jpg').write_bytes(b'test-image')
|
||||
self.parse_patch = patch.object(self.api, 'aio_do_parse', fake_parse)
|
||||
self.parse_patch.start()
|
||||
self.addCleanup(self.parse_patch.stop)
|
||||
|
||||
def request(self, route='/file_parse', **options):
|
||||
fields = {'backend': 'pipeline', 'output_dir': str(self.directory / 'output'),
|
||||
'return_md': 'true', 'return_middle_json': 'true', 'return_images': 'true',
|
||||
'return_model_output': 'true', 'return_content_list': 'true', **options}
|
||||
return self.client.post(route, files={'files': ('test276.pdf', b'%PDF-test', 'application/pdf')}, data=fields)
|
||||
|
||||
def test_maxkb_and_application_routes_return_complete_results_and_clean_outputs(self):
|
||||
for route in ('/file_parse', '/api/file_parse'):
|
||||
with self.subTest(route=route):
|
||||
response = self.request(route)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(response.json()['version'], '2.7.6')
|
||||
data = response.json()['results']['test276']
|
||||
self.assertIn('###### Leaf', data['md_content'])
|
||||
self.assertEqual(json.loads(data['middle_json'])['pdf_info'][0]['level'], 6)
|
||||
self.assertEqual(json.loads(data['content_list'])[0]['text_level'], 6)
|
||||
self.assertTrue(data['images']['a.jpg'].startswith('data:image/jpeg;base64,'))
|
||||
self.assertEqual(list((self.directory / 'output').iterdir()), [])
|
||||
|
||||
def test_zip_contains_requested_json_and_images(self):
|
||||
response = self.request(response_format_zip='true')
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
with zipfile.ZipFile(BytesIO(response.content)) as archive:
|
||||
self.assertEqual(set(archive.namelist()), {
|
||||
'test276/test276.md', 'test276/test276_middle.json', 'test276/test276_model.json',
|
||||
'test276/test276_content_list.json', 'test276/images/a.jpg'})
|
||||
|
||||
def test_gpu_option_reaches_the_served_app_and_invalid_value_fails(self):
|
||||
from click.testing import CliRunner
|
||||
with patch.object(self.api.uvicorn, 'run') as serve, patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': '0.4'}):
|
||||
result = CliRunner().invoke(self.api.main, ['--host', '127.0.0.1'])
|
||||
self.assertEqual(result.exit_code, 0, result.output)
|
||||
self.assertIs(serve.call_args.args[0], self.api.app)
|
||||
self.assertEqual(self.api.app.state.config['gpu_memory_utilization'], 0.4)
|
||||
with patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': '1.1'}):
|
||||
self.assertNotEqual(CliRunner().invoke(self.api.main, []).exit_code, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
node_modules
|
||||
dist
|
||||
.git
|
||||
.idea
|
||||
*.log
|
||||
*.pid
|
||||
.env
|
||||
.env.*
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# Portable Web UI image for UnisMindMap.
|
||||
# Runtime API upstream is configured by MINERU_API_URL, defaulting to Docker DNS name mineru-api.
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
COPY package*.json ./
|
||||
RUN npm config set registry https://registry.npmmirror.com && npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
ENV MINERU_API_URL=http://mineru-api:8000
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
|
||||
EXPOSE 9898
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
server {
|
||||
listen 9898;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log;
|
||||
|
||||
location ~* ^/(assets|mindmap/assets)/.*\.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
|
||||
rewrite ^/mindmap/(.*)$ /$1 break;
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /mindmap {
|
||||
return 301 /mindmap/;
|
||||
}
|
||||
|
||||
location = /mindmap/api/health {
|
||||
proxy_pass ${MINERU_API_URL}/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /api/health {
|
||||
proxy_pass ${MINERU_API_URL}/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location ^~ /mindmap/api/ {
|
||||
rewrite ^/mindmap/api/(.*)$ /api/$1 break;
|
||||
proxy_pass ${MINERU_API_URL};
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location = /file_parse {
|
||||
proxy_pass ${MINERU_API_URL}/file_parse;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass ${MINERU_API_URL}/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location ^~ /mindmap/ {
|
||||
rewrite ^/mindmap/(.*)$ /$1 break;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
|
@ -32,11 +32,15 @@ export interface ParseResult {
|
|||
export interface ParseProgress {
|
||||
progress: number
|
||||
stage: string
|
||||
status: 'processing' | 'completed' | 'failed'
|
||||
status: 'pending' | 'processing' | 'completed' | 'failed'
|
||||
error: string | null
|
||||
file_names: string
|
||||
}
|
||||
|
||||
export interface MindmapOrganizeProgress extends ParseProgress {
|
||||
result_md?: string | null
|
||||
}
|
||||
|
||||
export const documentApi = {
|
||||
/**
|
||||
* 解析文档
|
||||
|
|
@ -65,8 +69,11 @@ export const documentApi = {
|
|||
if (params.server_url) {
|
||||
formData.append('server_url', params.server_url)
|
||||
}
|
||||
if (taskId) {
|
||||
formData.append('task_id', taskId)
|
||||
}
|
||||
|
||||
return request.post('/api/file_parse', formData, {
|
||||
return request.post('/file_parse', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
...(taskId ? { 'X-Task-ID': taskId } : {})
|
||||
|
|
@ -80,12 +87,34 @@ export const documentApi = {
|
|||
})
|
||||
},
|
||||
|
||||
createParseTask(taskId: string): Promise<ParseProgress> {
|
||||
return request.post(`/parse_tasks/${encodeURIComponent(taskId)}`).then(result => {
|
||||
return result as unknown as ParseProgress
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 查询解析进度
|
||||
*/
|
||||
getParseProgress(taskId: string): Promise<ParseProgress> {
|
||||
return request.get(`/api/parse_progress/${taskId}`).then(result => {
|
||||
return request.get(`/parse_progress/${taskId}`).then(result => {
|
||||
return result as unknown as ParseProgress
|
||||
})
|
||||
},
|
||||
|
||||
createMindmapTask(taskId: string, markdown: string, mode = 'smart', prompt?: string): Promise<MindmapOrganizeProgress> {
|
||||
return request.post(`/mindmap_tasks/${encodeURIComponent(taskId)}`, {
|
||||
markdown,
|
||||
mode,
|
||||
prompt
|
||||
}).then(result => {
|
||||
return result as unknown as MindmapOrganizeProgress
|
||||
})
|
||||
},
|
||||
|
||||
getMindmapProgress(taskId: string): Promise<MindmapOrganizeProgress> {
|
||||
return request.get(`/mindmap_progress/${encodeURIComponent(taskId)}`).then(result => {
|
||||
return result as unknown as MindmapOrganizeProgress
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
class="slider"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
|
||||
<!-- 解析后端 -->
|
||||
<el-form-item :label="$t('config.backend')" class="form-item">
|
||||
<el-select
|
||||
|
|
@ -50,8 +50,6 @@
|
|||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- 识别选项 -->
|
||||
<div class="section-title">{{ $t('config.recognitionOptions') }}</div>
|
||||
|
||||
|
|
@ -104,6 +102,139 @@
|
|||
</div>
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="section-title">导出与智能整理</div>
|
||||
|
||||
<el-form-item label="导出分辨率" class="form-item">
|
||||
<el-select v-model="exportResolutionPreset" style="width: 100%" class="select">
|
||||
<el-option
|
||||
v-for="option in exportResolutionOptions"
|
||||
:key="option.value"
|
||||
:label="option.label"
|
||||
:value="option.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input-number
|
||||
v-if="exportResolutionPreset === 'custom'"
|
||||
v-model="draftConfig.exportResolution"
|
||||
:min="720"
|
||||
:max="16384"
|
||||
:step="100"
|
||||
controls-position="right"
|
||||
class="export-resolution-input"
|
||||
/>
|
||||
<div class="form-item-description">
|
||||
PNG/JPEG 导出长边上限;默认 8K,导出文件会按该最大长边生效。
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="大模型服务地址" class="form-item">
|
||||
<el-input
|
||||
v-model="draftConfig.mindmapLlmBaseUrl"
|
||||
placeholder="例如:http://10.100.53.199:9527/v1"
|
||||
class="input"
|
||||
clearable
|
||||
/>
|
||||
<div class="form-item-description">
|
||||
OpenAI 兼容接口地址,后端会请求该地址下的 /chat/completions;留空时使用服务端 MINDMAP_LLM_BASE_URL。
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="大模型 API Key" class="form-item">
|
||||
<el-input
|
||||
v-model="draftConfig.mindmapLlmApiKey"
|
||||
type="password"
|
||||
placeholder="留空则使用服务端 MINDMAP_LLM_API_KEY"
|
||||
class="input"
|
||||
show-password
|
||||
clearable
|
||||
/>
|
||||
<div class="form-item-description">
|
||||
仅随智能整理请求发送给后端,后端日志不会输出明文 Key。
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="大模型名称" class="form-item">
|
||||
<el-input
|
||||
v-model="draftConfig.mindmapLlmModel"
|
||||
placeholder="gemma-4-26B"
|
||||
class="input"
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<div class="llm-grid">
|
||||
<el-form-item label="请求超时(秒)" class="form-item">
|
||||
<el-input-number
|
||||
v-model="draftConfig.mindmapLlmTimeout"
|
||||
:min="30"
|
||||
:max="3600"
|
||||
:step="30"
|
||||
controls-position="right"
|
||||
class="number-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="温度" class="form-item">
|
||||
<el-input-number
|
||||
v-model="draftConfig.mindmapLlmTemperature"
|
||||
:min="0"
|
||||
:max="2"
|
||||
:step="0.1"
|
||||
:precision="1"
|
||||
controls-position="right"
|
||||
class="number-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="最大上下文 Token" class="form-item">
|
||||
<el-input-number
|
||||
v-model="draftConfig.mindmapLlmMaxContextTokens"
|
||||
:min="4096"
|
||||
:max="262144"
|
||||
:step="1024"
|
||||
controls-position="right"
|
||||
class="number-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="最大输出 Token" class="form-item">
|
||||
<el-input-number
|
||||
v-model="draftConfig.mindmapLlmMaxOutputTokens"
|
||||
:min="512"
|
||||
:max="32768"
|
||||
:step="512"
|
||||
controls-position="right"
|
||||
class="number-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="安全预留 Token" class="form-item">
|
||||
<el-input-number
|
||||
v-model="draftConfig.mindmapLlmSafetyTokens"
|
||||
:min="0"
|
||||
:max="8192"
|
||||
:step="256"
|
||||
controls-position="right"
|
||||
class="number-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="智能整理提示词" class="form-item">
|
||||
<el-input
|
||||
v-model="draftConfig.mindmapPrompt"
|
||||
type="textarea"
|
||||
:rows="10"
|
||||
resize="vertical"
|
||||
class="input"
|
||||
/>
|
||||
<div class="form-item-description">
|
||||
切换到“智能整理”时发送给后端大模型;默认保留标题结构、总结段落要点,并保持原文语言。
|
||||
</div>
|
||||
</el-form-item>
|
||||
<div class="config-actions">
|
||||
<el-button @click="resetDraft">重置</el-button>
|
||||
<el-button type="primary" @click="confirmConfig">确认</el-button>
|
||||
|
|
@ -113,9 +244,9 @@
|
|||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, watch } from 'vue'
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { DocumentConfig } from '@/composables/useDocumentProcessor'
|
||||
import { DEFAULT_DOCUMENT_CONFIG, type DocumentConfig } from '@/composables/useDocumentProcessor'
|
||||
|
||||
interface Props {
|
||||
modelValue: DocumentConfig
|
||||
|
|
@ -126,16 +257,45 @@ interface Props {
|
|||
interface Emits {
|
||||
(e: 'update:modelValue', value: DocumentConfig): void
|
||||
(e: 'backendChange', backend: string): void
|
||||
(e: 'close'): void
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const exportResolutionOptions = [
|
||||
{ label: '1080P', value: 1080 },
|
||||
{ label: '2K', value: 2560 },
|
||||
{ label: '4K', value: 3840 },
|
||||
{ label: '8K', value: 7680 },
|
||||
{ label: '自定义', value: 'custom' }
|
||||
] as const
|
||||
|
||||
const createDraft = (value: DocumentConfig): DocumentConfig => ({ ...value })
|
||||
const draftConfig = reactive<DocumentConfig>(createDraft(props.modelValue))
|
||||
|
||||
const getExportResolutionPreset = (resolution: number): number | 'custom' => {
|
||||
const isPreset = exportResolutionOptions.some((option) => {
|
||||
return typeof option.value === 'number' && option.value === resolution
|
||||
})
|
||||
return isPreset ? resolution : 'custom'
|
||||
}
|
||||
|
||||
const exportResolutionPreset = ref<number | 'custom'>(getExportResolutionPreset(props.modelValue.exportResolution))
|
||||
|
||||
watch(exportResolutionPreset, (value) => {
|
||||
if (value === 'custom') {
|
||||
if (getExportResolutionPreset(draftConfig.exportResolution) !== 'custom') {
|
||||
draftConfig.exportResolution = 3840
|
||||
}
|
||||
return
|
||||
}
|
||||
draftConfig.exportResolution = value
|
||||
})
|
||||
|
||||
const syncDraft = (value: DocumentConfig) => {
|
||||
Object.assign(draftConfig, createDraft(value))
|
||||
exportResolutionPreset.value = getExportResolutionPreset(value.exportResolution)
|
||||
}
|
||||
|
||||
watch(
|
||||
|
|
@ -159,7 +319,12 @@ const onBackendChange = (backend: string) => {
|
|||
}
|
||||
|
||||
const resetDraft = () => {
|
||||
syncDraft(props.modelValue)
|
||||
const defaults = createDraft(DEFAULT_DOCUMENT_CONFIG)
|
||||
syncDraft(defaults)
|
||||
emit('update:modelValue', defaults)
|
||||
emit('backendChange', defaults.backend)
|
||||
ElMessage.success('已恢复默认设置')
|
||||
emit('close')
|
||||
}
|
||||
|
||||
const confirmConfig = () => {
|
||||
|
|
@ -167,6 +332,7 @@ const confirmConfig = () => {
|
|||
emit('update:modelValue', confirmed)
|
||||
emit('backendChange', confirmed.backend)
|
||||
ElMessage.success('设置已确认')
|
||||
emit('close')
|
||||
}
|
||||
|
||||
const getFormulaLabel = (backend: string) => {
|
||||
|
|
@ -250,6 +416,16 @@ const getBackendDescription = (backend: string) => {
|
|||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.llm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0 12px;
|
||||
}
|
||||
|
||||
.number-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.config-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<template>
|
||||
<div class="markdown-renderer">
|
||||
<template v-if="content">
|
||||
<div class="render-actions">
|
||||
<div class="content-toolbar render-actions">
|
||||
<div class="render-actions-left">
|
||||
<el-segmented
|
||||
v-if="mode === 'markdown'"
|
||||
|
|
@ -16,12 +16,14 @@
|
|||
size="small"
|
||||
/>
|
||||
</div>
|
||||
<el-button type="primary" size="small" class="action-button primary" @click="handleDownload()">
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
</el-button>
|
||||
<div class="render-actions-right">
|
||||
<el-button type="primary" size="small" class="action-button primary" @click="handleDownload()">
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="render-content">
|
||||
<div v-if="mode === 'markdown'" class="render-shell">
|
||||
|
|
@ -52,11 +54,7 @@
|
|||
</div>
|
||||
|
||||
<div v-else class="render-shell">
|
||||
<div class="richtext-stage">
|
||||
<article ref="richtextRef" class="richtext-document">
|
||||
<div class="markdown-content richtext-content" v-html="renderedContent"></div>
|
||||
</article>
|
||||
</div>
|
||||
<div ref="richtextRef" class="markdown-content rendered-html richtext-content" v-html="renderedContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -390,22 +388,35 @@ async function handleDownload() {
|
|||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
|
||||
border-radius: 4px;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.render-actions {
|
||||
.content-toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 10px 16px;
|
||||
flex-shrink: 0;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.content-toolbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.render-actions {
|
||||
padding: 0 0 12px;
|
||||
background-color: #FFFFFF;
|
||||
}
|
||||
|
||||
|
|
@ -414,6 +425,15 @@ async function handleDownload() {
|
|||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 32px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.render-actions-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
|
|
@ -447,7 +467,7 @@ async function handleDownload() {
|
|||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0 16px 16px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.render-header {
|
||||
|
|
@ -473,7 +493,7 @@ async function handleDownload() {
|
|||
.markdown-content {
|
||||
padding: 20px;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
border-radius: 4px;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
|
|
@ -483,10 +503,9 @@ async function handleDownload() {
|
|||
|
||||
.pdf-stage {
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(22, 93, 255, 0.08), transparent 30%),
|
||||
#eef2f7;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
background: #F8F9FA;
|
||||
}
|
||||
|
||||
.pdf-preview-pages {
|
||||
|
|
@ -522,17 +541,18 @@ async function handleDownload() {
|
|||
|
||||
.richtext-stage {
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(180deg, #f3f4f6 0%, #eef2f7 100%);
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
background: #F8F9FA;
|
||||
}
|
||||
|
||||
.richtext-document {
|
||||
min-height: 100%;
|
||||
background: white;
|
||||
border: 1px solid #dde3ea;
|
||||
border-radius: 12px;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.richtext-content {
|
||||
|
|
@ -633,9 +653,19 @@ async function handleDownload() {
|
|||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.render-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.render-actions-left {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.render-actions-right {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.pdf-page {
|
||||
|
|
|
|||
|
|
@ -1,38 +1,43 @@
|
|||
<template>
|
||||
<div class="mindmap-container">
|
||||
<div class="mindmap-actions">
|
||||
<span class="mindmap-subtitle" v-if="content">已生成 {{ nodeCount }} 个节点</span>
|
||||
<el-dropdown @command="handleDownload">
|
||||
<div class="content-toolbar mindmap-actions">
|
||||
<div class="mindmap-actions-left">
|
||||
<span class="content-toolbar-meta">{{ nodeSummary }}</span>
|
||||
</div>
|
||||
<div class="mindmap-actions-right">
|
||||
<el-dropdown @command="handleDownload">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
class="action-button primary"
|
||||
:disabled="!content"
|
||||
>
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||
</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="svg">SVG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="png">PNG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="jpeg">JPEG 格式</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button
|
||||
type="primary"
|
||||
type="default"
|
||||
size="small"
|
||||
class="action-button primary"
|
||||
@click="resetView"
|
||||
class="action-button secondary"
|
||||
>
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
<el-icon><Refresh /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||
重置视图
|
||||
</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="svg">SVG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="png">PNG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="jpeg">JPEG 格式</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button
|
||||
type="default"
|
||||
size="small"
|
||||
@click="resetView"
|
||||
class="action-button secondary"
|
||||
>
|
||||
<template #icon>
|
||||
<el-icon><Refresh /></el-icon>
|
||||
</template>
|
||||
重置视图
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mindmap-content" @wheel.prevent="handleWheel" @click="handleNodeClick">
|
||||
<div class="empty-state" v-if="!content">
|
||||
|
|
@ -62,6 +67,10 @@ const props = defineProps({
|
|||
content: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
exportResolution: {
|
||||
type: Number,
|
||||
default: 0
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -75,12 +84,66 @@ let renderTimer: number | undefined
|
|||
const transformer = new Transformer()
|
||||
const scale = ref(1)
|
||||
const isRendering = ref(false)
|
||||
const totalNodeCount = ref(0)
|
||||
const hiddenNodeCount = ref(0)
|
||||
|
||||
const nodeCount = computed(() => {
|
||||
if (!props.content) return 0
|
||||
return (props.content.match(/^#{1,6}\s+/gm) || []).length
|
||||
type MarkmapNode = {
|
||||
content?: string
|
||||
children?: MarkmapNode[]
|
||||
payload?: {
|
||||
fold?: number
|
||||
}
|
||||
}
|
||||
|
||||
const nodeSummary = computed(() => {
|
||||
if (!props.content) return '暂无节点'
|
||||
return hiddenNodeCount.value > 0
|
||||
? `已生成 ${totalNodeCount.value} 个节点,隐藏 ${hiddenNodeCount.value} 个节点`
|
||||
: `已生成 ${totalNodeCount.value} 个节点`
|
||||
})
|
||||
|
||||
const updateNodeStats = () => {
|
||||
const root = mmInstance?.state?.data as MarkmapNode | undefined
|
||||
if (!root || !props.content) {
|
||||
totalNodeCount.value = 0
|
||||
hiddenNodeCount.value = 0
|
||||
return
|
||||
}
|
||||
|
||||
const countSubtree = (node: MarkmapNode): number => {
|
||||
const children = node.children || []
|
||||
return 1 + children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
}
|
||||
|
||||
const walkVisible = (node: MarkmapNode): { total: number; hidden: number } => {
|
||||
const children = node.children || []
|
||||
const total = 1 + children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
|
||||
if (node.payload?.fold && children.length > 0) {
|
||||
return {
|
||||
total,
|
||||
hidden: children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
}
|
||||
}
|
||||
|
||||
const childStats = children.reduce(
|
||||
(stats, child) => {
|
||||
const childStat = walkVisible(child)
|
||||
return {
|
||||
total: stats.total + childStat.total,
|
||||
hidden: stats.hidden + childStat.hidden
|
||||
}
|
||||
},
|
||||
{ total: 1, hidden: 0 }
|
||||
)
|
||||
return childStats
|
||||
}
|
||||
|
||||
const stats = walkVisible(root)
|
||||
totalNodeCount.value = Math.max(0, stats.total - 1)
|
||||
hiddenNodeCount.value = Math.max(0, stats.hidden)
|
||||
}
|
||||
|
||||
const initMarkmap = async () => {
|
||||
if (!svgRef.value) return
|
||||
|
||||
|
|
@ -104,11 +167,12 @@ const initMarkmap = async () => {
|
|||
|
||||
await nextTick()
|
||||
|
||||
const initialExpandLevel = nodeCount.value > 80 ? 2 : -1
|
||||
const sourceNodeCount = (props.content.match(/^#{1,6}\s+/gm) || []).length
|
||||
const initialExpandLevel = sourceNodeCount > 80 ? 2 : -1
|
||||
|
||||
if (mmInstance) {
|
||||
if (typeof mmInstance.setData === 'function') {
|
||||
mmInstance.setData(root)
|
||||
await mmInstance.setData(root, { initialExpandLevel })
|
||||
mmInstance.fit()
|
||||
} else {
|
||||
mmInstance = Markmap.create(svgRef.value, {
|
||||
|
|
@ -129,6 +193,7 @@ const initMarkmap = async () => {
|
|||
svgRef.value?.querySelectorAll('text').forEach((text) => {
|
||||
text.setAttribute('data-editable-node', 'true')
|
||||
})
|
||||
updateNodeStats()
|
||||
} catch (error) {
|
||||
console.error('Error initializing markmap:', error)
|
||||
mmInstance = null
|
||||
|
|
@ -176,14 +241,114 @@ function downloadBlob(blob: Blob, fileName: string) {
|
|||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function createExportSvg() {
|
||||
type ExportFormat = 'svg' | 'png' | 'jpeg'
|
||||
|
||||
interface ExportBox {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
function getViewportSize(svg: SVGElement) {
|
||||
const rect = svg.getBoundingClientRect()
|
||||
return {
|
||||
width: Math.ceil(Math.max(rect.width, 320)),
|
||||
height: Math.ceil(Math.max(rect.height, 240))
|
||||
}
|
||||
}
|
||||
|
||||
function cleanExportSvg(svg: SVGElement) {
|
||||
if (!svg.getAttribute('xmlns')) {
|
||||
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
|
||||
}
|
||||
svg.querySelectorAll('[style*="cursor"]').forEach((node) => node.removeAttribute('style'))
|
||||
}
|
||||
|
||||
function getBoxFromSvgRect(rect: DOMRect): ExportBox {
|
||||
return {
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height
|
||||
}
|
||||
}
|
||||
|
||||
function transformBox(box: ExportBox, matrix: DOMMatrix): ExportBox {
|
||||
const points = [
|
||||
new DOMPoint(box.x, box.y).matrixTransform(matrix),
|
||||
new DOMPoint(box.x + box.width, box.y).matrixTransform(matrix),
|
||||
new DOMPoint(box.x, box.y + box.height).matrixTransform(matrix),
|
||||
new DOMPoint(box.x + box.width, box.y + box.height).matrixTransform(matrix)
|
||||
]
|
||||
const xs = points.map((point) => point.x)
|
||||
const ys = points.map((point) => point.y)
|
||||
const minX = Math.min(...xs)
|
||||
const minY = Math.min(...ys)
|
||||
const maxX = Math.max(...xs)
|
||||
const maxY = Math.max(...ys)
|
||||
return {
|
||||
x: minX,
|
||||
y: minY,
|
||||
width: maxX - minX,
|
||||
height: maxY - minY
|
||||
}
|
||||
}
|
||||
|
||||
function getIntersection(a: ExportBox, b: ExportBox): ExportBox | null {
|
||||
const x = Math.max(a.x, b.x)
|
||||
const y = Math.max(a.y, b.y)
|
||||
const right = Math.min(a.x + a.width, b.x + b.width)
|
||||
const bottom = Math.min(a.y + a.height, b.y + b.height)
|
||||
if (right <= x || bottom <= y) return null
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: right - x,
|
||||
height: bottom - y
|
||||
}
|
||||
}
|
||||
|
||||
function padBox(box: ExportBox, padding: number, boundary?: ExportBox): ExportBox {
|
||||
const padded = {
|
||||
x: box.x - padding,
|
||||
y: box.y - padding,
|
||||
width: box.width + padding * 2,
|
||||
height: box.height + padding * 2
|
||||
}
|
||||
|
||||
if (!boundary) return padded
|
||||
const clipped = getIntersection(padded, boundary)
|
||||
return clipped || box
|
||||
}
|
||||
|
||||
function normalizeBox(box: ExportBox): ExportBox {
|
||||
const x = Math.min(box.x, box.x + box.width)
|
||||
const y = Math.min(box.y, box.y + box.height)
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: Math.abs(box.width),
|
||||
height: Math.abs(box.height)
|
||||
}
|
||||
}
|
||||
|
||||
function isCompleteInViewport(contentBox: ExportBox, viewportBox: ExportBox) {
|
||||
const tolerance = 4
|
||||
return (
|
||||
contentBox.x >= viewportBox.x - tolerance &&
|
||||
contentBox.y >= viewportBox.y - tolerance &&
|
||||
contentBox.x + contentBox.width <= viewportBox.x + viewportBox.width + tolerance &&
|
||||
contentBox.y + contentBox.height <= viewportBox.y + viewportBox.height + tolerance
|
||||
)
|
||||
}
|
||||
|
||||
function createFullExportSvg() {
|
||||
const svg = svgRef.value
|
||||
if (!svg) return null
|
||||
|
||||
const svgCopy = svg.cloneNode(true) as SVGElement
|
||||
if (!svgCopy.getAttribute('xmlns')) {
|
||||
svgCopy.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
|
||||
}
|
||||
cleanExportSvg(svgCopy)
|
||||
|
||||
const contentGroup = svg.querySelector('g')
|
||||
const bbox = contentGroup
|
||||
|
|
@ -195,10 +360,53 @@ function createExportSvg() {
|
|||
const height = Math.ceil(Math.max(bbox.height + padding * 2, 240))
|
||||
const viewBox = `${Math.floor(bbox.x - padding)} ${Math.floor(bbox.y - padding)} ${width} ${height}`
|
||||
|
||||
const viewportGroupCopy = svgCopy.querySelector('g')
|
||||
viewportGroupCopy?.removeAttribute('transform')
|
||||
svgCopy.setAttribute('viewBox', viewBox)
|
||||
svgCopy.setAttribute('width', String(width))
|
||||
svgCopy.setAttribute('height', String(height))
|
||||
svgCopy.querySelectorAll('[style*="cursor"]').forEach((node) => node.removeAttribute('style'))
|
||||
|
||||
return {
|
||||
data: new XMLSerializer().serializeToString(svgCopy),
|
||||
width,
|
||||
height
|
||||
}
|
||||
}
|
||||
|
||||
function createVisibleExportSvg() {
|
||||
const svg = svgRef.value
|
||||
if (!svg) return null
|
||||
|
||||
const contentGroup = svg.querySelector('g') as SVGGElement | null
|
||||
if (!contentGroup) return createFullExportSvg()
|
||||
|
||||
const viewport = getViewportSize(svg)
|
||||
const viewportBox = { x: 0, y: 0, width: viewport.width, height: viewport.height }
|
||||
const ctm = contentGroup.getCTM()
|
||||
if (!ctm) return createFullExportSvg()
|
||||
|
||||
const contentBox = transformBox(getBoxFromSvgRect(contentGroup.getBBox()), ctm)
|
||||
if (isCompleteInViewport(contentBox, viewportBox)) {
|
||||
return createFullExportSvg()
|
||||
}
|
||||
|
||||
const svgCopy = svg.cloneNode(true) as SVGElement
|
||||
cleanExportSvg(svgCopy)
|
||||
|
||||
const screenVisibleBox = padBox(getIntersection(contentBox, viewportBox) || viewportBox, 24, viewportBox)
|
||||
const localVisibleBox = normalizeBox(transformBox(screenVisibleBox, ctm.inverse()))
|
||||
const localContentBox = getBoxFromSvgRect(contentGroup.getBBox())
|
||||
const clippedLocalBox = getIntersection(localVisibleBox, localContentBox) || localVisibleBox
|
||||
const visibleBox = padBox(clippedLocalBox, 24)
|
||||
const width = Math.ceil(Math.max(visibleBox.width, 320))
|
||||
const height = Math.ceil(Math.max(visibleBox.height, 240))
|
||||
const viewBox = `${Math.floor(visibleBox.x)} ${Math.floor(visibleBox.y)} ${width} ${height}`
|
||||
|
||||
const viewportGroupCopy = svgCopy.querySelector('g')
|
||||
viewportGroupCopy?.removeAttribute('transform')
|
||||
svgCopy.setAttribute('width', String(width))
|
||||
svgCopy.setAttribute('height', String(height))
|
||||
svgCopy.setAttribute('viewBox', viewBox)
|
||||
|
||||
return {
|
||||
data: new XMLSerializer().serializeToString(svgCopy),
|
||||
|
|
@ -208,8 +416,8 @@ function createExportSvg() {
|
|||
}
|
||||
|
||||
// 下载思维导图
|
||||
const downloadMindMap = async (format: 'svg' | 'png' | 'jpeg' = 'svg') => {
|
||||
const exportSvg = createExportSvg()
|
||||
const downloadMindMap = async (format: ExportFormat = 'svg') => {
|
||||
const exportSvg = createVisibleExportSvg()
|
||||
if (!exportSvg) return
|
||||
|
||||
const time = new Date().getTime()
|
||||
|
|
@ -218,8 +426,12 @@ const downloadMindMap = async (format: 'svg' | 'png' | 'jpeg' = 'svg') => {
|
|||
return
|
||||
}
|
||||
|
||||
const maxCanvasPixels = 16_000_000
|
||||
const scaleFactor = Math.min(3, Math.max(1, Math.sqrt(maxCanvasPixels / (exportSvg.width * exportSvg.height))))
|
||||
const baseScale = 3
|
||||
const maxResolution = Number(props.exportResolution) || 0
|
||||
const longEdge = Math.max(exportSvg.width, exportSvg.height)
|
||||
const scaleFactor = maxResolution > 0
|
||||
? Math.min(baseScale, Math.max(0.1, maxResolution / longEdge))
|
||||
: baseScale
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
|
@ -245,6 +457,10 @@ const downloadMindMap = async (format: 'svg' | 'png' | 'jpeg' = 'svg') => {
|
|||
|
||||
// 处理下载命令
|
||||
const handleDownload = (command: string) => {
|
||||
if (!props.content) {
|
||||
ElMessage.warning('暂无思维导图内容可下载')
|
||||
return
|
||||
}
|
||||
if (command === 'svg' || command === 'png' || command === 'jpeg') {
|
||||
downloadMindMap(command)
|
||||
}
|
||||
|
|
@ -254,6 +470,7 @@ const handleDownload = (command: string) => {
|
|||
const resetView = () => {
|
||||
mmInstance?.fit()
|
||||
scale.value = 1
|
||||
window.setTimeout(updateNodeStats, 0)
|
||||
}
|
||||
|
||||
// 放大
|
||||
|
|
@ -292,6 +509,7 @@ const handleWheel = (event: WheelEvent) => {
|
|||
}
|
||||
|
||||
const handleNodeClick = async (event: MouseEvent) => {
|
||||
window.setTimeout(updateNodeStats, 0)
|
||||
const textNode = (event.target as Element | null)?.closest?.('text')
|
||||
const oldText = textNode?.textContent?.trim()
|
||||
if (!oldText || !props.content || oldText === '文档思维导图') return
|
||||
|
|
@ -319,28 +537,52 @@ const handleNodeClick = async (event: MouseEvent) => {
|
|||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
|
||||
background-color: transparent;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.mindmap-actions {
|
||||
.content-toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px 16px;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mindmap-subtitle {
|
||||
.mindmap-actions {
|
||||
padding: 0 0 12px;
|
||||
}
|
||||
|
||||
.mindmap-actions-left,
|
||||
.mindmap-actions-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mindmap-actions-left {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.mindmap-actions-right {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
background-color: #F2F3F5;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
margin-right: auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
|
|
@ -382,6 +624,8 @@ const handleNodeClick = async (event: MouseEvent) => {
|
|||
background-color: #F9FAFC;
|
||||
cursor: grab;
|
||||
min-height: 0;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.mindmap-content:active {
|
||||
|
|
@ -449,16 +693,18 @@ const handleNodeClick = async (event: MouseEvent) => {
|
|||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.mindmap-header {
|
||||
padding: 12px 16px;
|
||||
.mindmap-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.mindmap-title {
|
||||
font-size: 14px;
|
||||
|
||||
.mindmap-actions-left,
|
||||
.mindmap-actions-right {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.mindmap-subtitle {
|
||||
font-size: 10px;
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ref, reactive } from 'vue'
|
||||
import { ref, reactive, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
import { documentApi, type ParseParams } from '@/api/document'
|
||||
import { convertWordToPdf, isWordFile } from '@/utils/wordToPdf'
|
||||
|
|
@ -13,6 +13,16 @@ export interface DocumentConfig {
|
|||
maxPages: number
|
||||
backend: string
|
||||
serverUrl: string
|
||||
exportResolution: number
|
||||
mindmapPrompt: string
|
||||
mindmapLlmBaseUrl: string
|
||||
mindmapLlmApiKey: string
|
||||
mindmapLlmModel: string
|
||||
mindmapLlmTimeout: number
|
||||
mindmapLlmTemperature: number
|
||||
mindmapLlmMaxContextTokens: number
|
||||
mindmapLlmMaxOutputTokens: number
|
||||
mindmapLlmSafetyTokens: number
|
||||
tableEnable: boolean
|
||||
formulaEnable: boolean
|
||||
language: string
|
||||
|
|
@ -26,21 +36,73 @@ export interface ProcessResult {
|
|||
downloadUrl?: string
|
||||
}
|
||||
|
||||
export const DOCUMENT_CONFIG_STORAGE_KEY = 'mineru.documentProcessor.config.v4'
|
||||
|
||||
export const DEFAULT_MINDMAP_PROMPT = `你是文档结构整理助手。请基于用户提供的 Markdown 生成适合思维导图展示的 Markdown。
|
||||
|
||||
要求:
|
||||
1. 保留原文标题结构,不要重写或打乱主要标题层级。
|
||||
2. 将标题下的段落内容总结为要点,合并相近段落,避免逐段照抄。
|
||||
3. 保留原文语言:英文内容输出英文,中文内容输出中文,多语言内容按原文语言分别保留。
|
||||
4. 不要编造原文没有的信息。
|
||||
5. 保留关键数字、公式、专有名词、步骤和结论。
|
||||
6. 最大层级不超过 4 层。
|
||||
7. 每个父节点下最多 8 个子节点。
|
||||
8. 节点标题尽量简短,正文说明使用短句列表。
|
||||
9. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。`
|
||||
|
||||
export const DEFAULT_DOCUMENT_CONFIG: DocumentConfig = {
|
||||
maxPages: 1000,
|
||||
backend: 'hybrid-auto-engine',
|
||||
serverUrl: 'http://localhost:30000',
|
||||
exportResolution: 7680,
|
||||
mindmapPrompt: DEFAULT_MINDMAP_PROMPT,
|
||||
mindmapLlmBaseUrl: '',
|
||||
mindmapLlmApiKey: '',
|
||||
mindmapLlmModel: 'gemma-4-26B',
|
||||
mindmapLlmTimeout: 180,
|
||||
mindmapLlmTemperature: 0.2,
|
||||
mindmapLlmMaxContextTokens: 32768,
|
||||
mindmapLlmMaxOutputTokens: 4096,
|
||||
mindmapLlmSafetyTokens: 1024,
|
||||
tableEnable: true,
|
||||
formulaEnable: true,
|
||||
language: 'ch',
|
||||
forceOcr: false
|
||||
}
|
||||
|
||||
function loadCachedConfig(): Partial<DocumentConfig> {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(DOCUMENT_CONFIG_STORAGE_KEY)
|
||||
return raw ? JSON.parse(raw) : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function useDocumentProcessor() {
|
||||
// 文件相关
|
||||
const uploadedFiles: Ref<File[]> = ref([])
|
||||
const uploadedDisplayFiles: Ref<File[]> = ref([])
|
||||
const isUploading = ref(false)
|
||||
|
||||
// 配置相关
|
||||
const config = reactive<DocumentConfig>({
|
||||
maxPages: 1000,
|
||||
backend: 'hybrid-auto-engine',
|
||||
serverUrl: 'http://localhost:30000',
|
||||
tableEnable: true,
|
||||
formulaEnable: true,
|
||||
language: 'ch',
|
||||
forceOcr: false
|
||||
...DEFAULT_DOCUMENT_CONFIG,
|
||||
...loadCachedConfig()
|
||||
})
|
||||
|
||||
watch(
|
||||
config,
|
||||
(value) => {
|
||||
try {
|
||||
window.localStorage.setItem(DOCUMENT_CONFIG_STORAGE_KEY, JSON.stringify(value))
|
||||
} catch {
|
||||
// 浏览器禁用本地存储时不影响当前页面使用。
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
// 结果相关
|
||||
const results = ref<ProcessResult | null>(null)
|
||||
|
|
@ -82,64 +144,95 @@ export function useDocumentProcessor() {
|
|||
if (!files || files.length === 0) return
|
||||
|
||||
const validFiles: File[] = []
|
||||
const displayFiles: File[] = []
|
||||
const file = files[0]
|
||||
uploadedFiles.value = []
|
||||
uploadedDisplayFiles.value = []
|
||||
results.value = null
|
||||
error.value = null
|
||||
if (files.length > 1) {
|
||||
error.value = '一次只能选择一个文件,已使用第一个文件'
|
||||
}
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i]
|
||||
const fileType = file.type
|
||||
const fileName = file.name.toLowerCase()
|
||||
|
||||
console.log('Processing file:', fileName, 'type:', fileType)
|
||||
|
||||
// 验证文件类型 - 支持 PDF、图片和 Word 文档
|
||||
const isImage = fileType.startsWith('image/')
|
||||
const isPdf = fileType === 'application/pdf'
|
||||
const isWord = fileName.endsWith('.docx') || fileName.endsWith('.doc') || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
|
||||
console.log('File type checks - isImage:', isImage, 'isPdf:', isPdf, 'isWord:', isWord)
|
||||
|
||||
if (!isImage && !isPdf && !isWord) {
|
||||
error.value = '不支持的文件类型'
|
||||
console.log('Unsupported file type:', fileName, fileType)
|
||||
continue
|
||||
}
|
||||
|
||||
// 验证文件大小 (100MB)
|
||||
if (file.size > 100 * 1024 * 1024) {
|
||||
error.value = '文件大小超出限制'
|
||||
console.log('File too large:', fileName, file.size)
|
||||
continue
|
||||
}
|
||||
|
||||
// 如果是 Word 文档,转换为 PDF
|
||||
if (isWord) {
|
||||
try {
|
||||
isUploading.value = true
|
||||
error.value = '正在将 Word 文档转换为 PDF...'
|
||||
console.log('Converting Word to PDF:', fileName)
|
||||
const pdfFile = await convertWordToPdf(file)
|
||||
console.log('Conversion successful, PDF file:', pdfFile.name, pdfFile.size)
|
||||
validFiles.push(pdfFile)
|
||||
error.value = null
|
||||
} catch (err) {
|
||||
error.value = 'Word 转换为 PDF 失败: ' + (err as Error).message
|
||||
console.error('Conversion failed:', (err as Error).message)
|
||||
continue
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
} else {
|
||||
const fileType = file.type
|
||||
const fileName = file.name.toLowerCase()
|
||||
|
||||
console.log('Processing file:', fileName, 'type:', fileType)
|
||||
|
||||
// 验证文件类型 - 支持 Markdown、PDF、Word 和后端可转换为 PDF 的图片格式
|
||||
const supportedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff', '.gif', '.jp2']
|
||||
const isImage = fileType.startsWith('image/') && supportedImageExtensions.some((ext) => fileName.endsWith(ext))
|
||||
const isPdf = fileType === 'application/pdf'
|
||||
const isWord = fileName.endsWith('.docx') || fileName.endsWith('.doc') || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
const isMarkdown = fileName.endsWith('.md') || fileType === 'text/markdown'
|
||||
|
||||
console.log('File type checks - isImage:', isImage, 'isPdf:', isPdf, 'isWord:', isWord, 'isMarkdown:', isMarkdown)
|
||||
|
||||
if (!isImage && !isPdf && !isWord && !isMarkdown) {
|
||||
error.value = '不支持的文件类型,请选择 MD、PDF、Word、JPG、PNG、WEBP、BMP、TIFF、GIF 或 JP2 文件'
|
||||
console.log('Unsupported file type:', fileName, fileType)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证文件大小 (100MB)
|
||||
if (file.size > 100 * 1024 * 1024) {
|
||||
error.value = '文件大小超出限制'
|
||||
console.log('File too large:', fileName, file.size)
|
||||
return
|
||||
}
|
||||
|
||||
if (isMarkdown) {
|
||||
try {
|
||||
isUploading.value = true
|
||||
const markdown = await file.text()
|
||||
validFiles.push(file)
|
||||
console.log('Adding file directly:', fileName)
|
||||
displayFiles.push(file)
|
||||
results.value = {
|
||||
markdown,
|
||||
source: markdown,
|
||||
mindmap: buildMindmapMarkdown(markdown)
|
||||
}
|
||||
error.value = null
|
||||
console.log('Markdown file loaded directly:', fileName, markdown.length)
|
||||
} catch (err) {
|
||||
error.value = 'Markdown 文件读取失败: ' + (err as Error).message
|
||||
console.error('Markdown read failed:', (err as Error).message)
|
||||
return
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
} else if (isWord) {
|
||||
try {
|
||||
isUploading.value = true
|
||||
error.value = '正在将 Word 文档转换为 PDF...'
|
||||
console.log('Converting Word to PDF:', fileName)
|
||||
const pdfFile = await convertWordToPdf(file)
|
||||
console.log('Conversion successful, PDF file:', pdfFile.name, pdfFile.size)
|
||||
validFiles.push(pdfFile)
|
||||
displayFiles.push(file)
|
||||
error.value = null
|
||||
} catch (err) {
|
||||
error.value = 'Word 转换为 PDF 失败: ' + (err as Error).message
|
||||
console.error('Conversion failed:', (err as Error).message)
|
||||
return
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
} else {
|
||||
validFiles.push(file)
|
||||
displayFiles.push(file)
|
||||
console.log('Adding file directly:', fileName)
|
||||
}
|
||||
|
||||
uploadedFiles.value = validFiles
|
||||
uploadedDisplayFiles.value = displayFiles
|
||||
console.log('Final uploaded files:', validFiles.map(f => f.name))
|
||||
}
|
||||
|
||||
// 清除所有数据
|
||||
const clearAll = () => {
|
||||
uploadedFiles.value = []
|
||||
uploadedDisplayFiles.value = []
|
||||
results.value = null
|
||||
error.value = null
|
||||
processingStage.value = ''
|
||||
|
|
@ -193,6 +286,14 @@ export function useDocumentProcessor() {
|
|||
error.value = '请先上传文件'
|
||||
return
|
||||
}
|
||||
|
||||
const firstFileName = uploadedFiles.value[0]?.name.toLowerCase() || ''
|
||||
if (firstFileName.endsWith('.md')) {
|
||||
if (!results.value) {
|
||||
error.value = 'Markdown 文件内容为空,请重新上传'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
isProcessing.value = true
|
||||
error.value = null
|
||||
|
|
@ -200,9 +301,10 @@ export function useDocumentProcessor() {
|
|||
|
||||
// 生成任务ID
|
||||
const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
startProgressPolling(taskId)
|
||||
|
||||
try {
|
||||
await documentApi.createParseTask(taskId)
|
||||
startProgressPolling(taskId)
|
||||
processingStage.value = '提交文档到解析服务'
|
||||
const params: ParseParams = {
|
||||
files: uploadedFiles.value,
|
||||
|
|
@ -274,6 +376,7 @@ export function useDocumentProcessor() {
|
|||
return {
|
||||
// 数据
|
||||
uploadedFiles,
|
||||
uploadedDisplayFiles,
|
||||
config,
|
||||
results,
|
||||
isUploading,
|
||||
|
|
|
|||
|
|
@ -1,167 +1,156 @@
|
|||
const MAX_NODE_TEXT_LENGTH = 72
|
||||
const MAX_PARAGRAPH_SUMMARY_LENGTH = 90
|
||||
const MAX_CHILDREN_PER_HEADING = 18
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import type Token from 'markdown-it/lib/token.mjs'
|
||||
|
||||
const ROOT_TITLE = '文档思维导图'
|
||||
const MAX_HEADING_LEVEL = 6
|
||||
|
||||
type BlockType = 'paragraph' | 'list' | 'table' | 'code' | 'math' | 'image'
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
breaks: true
|
||||
})
|
||||
|
||||
interface HeadingState {
|
||||
level: number
|
||||
childCount: number
|
||||
function normalizeNodeText(text: string) {
|
||||
return text
|
||||
.replace(/\r?\n/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function normalizeWhitespace(text: string) {
|
||||
return text.replace(/\s+/g, ' ').trim()
|
||||
function clampHeadingLevel(level: number) {
|
||||
return Math.min(Math.max(level, 1), MAX_HEADING_LEVEL)
|
||||
}
|
||||
|
||||
function stripMarkdownInline(text: string) {
|
||||
return normalizeWhitespace(text)
|
||||
.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
.replace(/[*_`~>#]/g, '')
|
||||
function pushHeading(result: string[], level: number, text: string) {
|
||||
const normalized = normalizeNodeText(text)
|
||||
if (!normalized) return
|
||||
result.push(`${'#'.repeat(clampHeadingLevel(level))} ${normalized}`)
|
||||
}
|
||||
|
||||
function truncateText(text: string, maxLength = MAX_NODE_TEXT_LENGTH) {
|
||||
const normalized = normalizeWhitespace(text)
|
||||
if (normalized.length <= maxLength) return normalized
|
||||
return `${normalized.slice(0, maxLength - 1)}...`
|
||||
function getHeadingLevel(token: Token) {
|
||||
const tagLevel = Number(token.tag.replace(/^h/i, ''))
|
||||
return Number.isFinite(tagLevel) && tagLevel > 0 ? tagLevel : 1
|
||||
}
|
||||
|
||||
function summarizeParagraph(text: string) {
|
||||
const cleaned = stripMarkdownInline(text)
|
||||
const sentence = cleaned.match(/^(.+?[。!?!?;;::]|\S.{20,}?[,,])/)
|
||||
return truncateText(sentence?.[1] || cleaned, MAX_PARAGRAPH_SUMMARY_LENGTH)
|
||||
function getNextInlineContent(tokens: Token[], index: number) {
|
||||
const next = tokens[index + 1]
|
||||
return next?.type === 'inline' ? next.content : ''
|
||||
}
|
||||
|
||||
function isHeading(line: string) {
|
||||
return /^#{1,6}\s+/.test(line.trim())
|
||||
function getFenceContent(token: Token) {
|
||||
const info = normalizeNodeText(token.info || '')
|
||||
const content = token.content.trim()
|
||||
if (!content) return info ? `代码块 ${info}` : '代码块'
|
||||
return info ? `代码块 ${info}: ${content}` : `代码块: ${content}`
|
||||
}
|
||||
|
||||
function getHeadingLevel(line: string) {
|
||||
return line.trim().match(/^#{1,6}/)?.[0].length || 0
|
||||
}
|
||||
function collectTableRows(tokens: Token[], startIndex: number) {
|
||||
const rows: string[][] = []
|
||||
let currentRow: string[] | null = null
|
||||
let endIndex = startIndex
|
||||
|
||||
function getHeadingText(line: string) {
|
||||
return stripMarkdownInline(line.trim().replace(/^#{1,6}\s+/, ''))
|
||||
}
|
||||
for (let i = startIndex + 1; i < tokens.length; i += 1) {
|
||||
const token = tokens[i]
|
||||
endIndex = i
|
||||
|
||||
function getListText(line: string) {
|
||||
return stripMarkdownInline(line.trim().replace(/^[-*+]\s+|^\d+[.)、]\s+/, ''))
|
||||
}
|
||||
|
||||
function countHeadingChildren(stack: HeadingState[], level: number) {
|
||||
while (stack.length && stack[stack.length - 1].level >= level) {
|
||||
stack.pop()
|
||||
if (token.type === 'table_close') break
|
||||
if (token.type === 'tr_open') {
|
||||
currentRow = []
|
||||
continue
|
||||
}
|
||||
if (token.type === 'tr_close') {
|
||||
if (currentRow && currentRow.some((cell) => cell.trim())) {
|
||||
rows.push(currentRow)
|
||||
}
|
||||
currentRow = null
|
||||
continue
|
||||
}
|
||||
if ((token.type === 'th_open' || token.type === 'td_open') && currentRow) {
|
||||
currentRow.push(getNextInlineContent(tokens, i))
|
||||
}
|
||||
}
|
||||
|
||||
const parent = stack[stack.length - 1]
|
||||
if (!parent) return true
|
||||
parent.childCount += 1
|
||||
return parent.childCount <= MAX_CHILDREN_PER_HEADING
|
||||
}
|
||||
|
||||
function pushBlock(result: string[], stack: HeadingState[], blockType: BlockType, text: string) {
|
||||
const cleaned = text.trim()
|
||||
if (!cleaned) return
|
||||
|
||||
const parentLevel = stack.length ? stack[stack.length - 1].level : 1
|
||||
const level = Math.min(parentLevel + 1, 6)
|
||||
if (!countHeadingChildren(stack, level)) return
|
||||
|
||||
const prefixMap: Record<BlockType, string> = {
|
||||
paragraph: '摘要',
|
||||
list: '要点',
|
||||
table: '表格',
|
||||
code: '代码',
|
||||
math: '公式',
|
||||
image: '图片'
|
||||
}
|
||||
|
||||
result.push(`${'#'.repeat(level)} ${prefixMap[blockType]}:${cleaned}`)
|
||||
return { rows, endIndex }
|
||||
}
|
||||
|
||||
export function buildMindmapMarkdown(markdown: string) {
|
||||
const lines = markdown.split(/\r?\n/)
|
||||
if (!markdown.trim()) return ''
|
||||
|
||||
const tokens = md.parse(markdown, {})
|
||||
const result: string[] = [`# ${ROOT_TITLE}`]
|
||||
const stack: HeadingState[] = [{ level: 1, childCount: 0 }]
|
||||
let paragraphBuffer: string[] = []
|
||||
let inCodeBlock = false
|
||||
let codeBlockTitle = ''
|
||||
let currentHeadingLevel = 1
|
||||
let listDepth = 0
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (paragraphBuffer.length === 0) return
|
||||
const text = summarizeParagraph(paragraphBuffer.join(' '))
|
||||
pushBlock(result, stack, 'paragraph', text)
|
||||
paragraphBuffer = []
|
||||
for (let i = 0; i < tokens.length; i += 1) {
|
||||
const token = tokens[i]
|
||||
|
||||
if (token.type === 'heading_open') {
|
||||
currentHeadingLevel = clampHeadingLevel(getHeadingLevel(token) + 1)
|
||||
pushHeading(result, currentHeadingLevel, getNextInlineContent(tokens, i) || '未命名章节')
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'bullet_list_open' || token.type === 'ordered_list_open') {
|
||||
listDepth += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'bullet_list_close' || token.type === 'ordered_list_close') {
|
||||
listDepth = Math.max(0, listDepth - 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'paragraph_open') {
|
||||
const level = currentHeadingLevel + Math.max(listDepth, 1)
|
||||
pushHeading(result, level, getNextInlineContent(tokens, i))
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'fence' || token.type === 'code_block') {
|
||||
pushHeading(result, currentHeadingLevel + 1, getFenceContent(token))
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'html_block') {
|
||||
pushHeading(result, currentHeadingLevel + 1, token.content)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'blockquote_open') {
|
||||
pushHeading(result, currentHeadingLevel + 1, '引用')
|
||||
currentHeadingLevel = clampHeadingLevel(currentHeadingLevel + 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'blockquote_close') {
|
||||
currentHeadingLevel = Math.max(1, currentHeadingLevel - 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'hr') {
|
||||
pushHeading(result, currentHeadingLevel + 1, '---')
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'table_open') {
|
||||
const tableLevel = currentHeadingLevel + 1
|
||||
const { rows, endIndex } = collectTableRows(tokens, i)
|
||||
pushHeading(result, tableLevel, '表格')
|
||||
rows.forEach((row) => {
|
||||
pushHeading(result, tableLevel + 1, row.map(normalizeNodeText).join(' | '))
|
||||
})
|
||||
i = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
|
||||
if (/^```/.test(trimmed)) {
|
||||
if (inCodeBlock) {
|
||||
pushBlock(result, stack, 'code', codeBlockTitle || '代码块')
|
||||
codeBlockTitle = ''
|
||||
} else {
|
||||
flushParagraph()
|
||||
codeBlockTitle = trimmed.replace(/^```/, '').trim()
|
||||
}
|
||||
inCodeBlock = !inCodeBlock
|
||||
continue
|
||||
}
|
||||
|
||||
if (inCodeBlock) continue
|
||||
|
||||
if (!trimmed) {
|
||||
flushParagraph()
|
||||
continue
|
||||
}
|
||||
|
||||
if (isHeading(trimmed)) {
|
||||
flushParagraph()
|
||||
const rawLevel = getHeadingLevel(trimmed)
|
||||
const level = Math.min(rawLevel + 1, 6)
|
||||
while (stack.length && stack[stack.length - 1].level >= level) {
|
||||
stack.pop()
|
||||
}
|
||||
result.push(`${'#'.repeat(level)} ${truncateText(getHeadingText(trimmed)) || '未命名章节'}`)
|
||||
stack.push({ level, childCount: 0 })
|
||||
continue
|
||||
}
|
||||
|
||||
if (/^\|.+\|$/.test(trimmed)) {
|
||||
flushParagraph()
|
||||
pushBlock(result, stack, 'table', '表格内容')
|
||||
continue
|
||||
}
|
||||
|
||||
if (/^!\[[^\]]*]\([^)]+\)/.test(trimmed)) {
|
||||
flushParagraph()
|
||||
pushBlock(result, stack, 'image', stripMarkdownInline(trimmed) || '图片')
|
||||
continue
|
||||
}
|
||||
|
||||
if (/^\$\$.*\$\$$/.test(trimmed) || /^\$[^$].*\$$/.test(trimmed)) {
|
||||
flushParagraph()
|
||||
pushBlock(result, stack, 'math', truncateText(trimmed, 80))
|
||||
continue
|
||||
}
|
||||
|
||||
if (/^[-*+]\s+|^\d+[.)、]\s+/.test(trimmed)) {
|
||||
flushParagraph()
|
||||
pushBlock(result, stack, 'list', truncateText(getListText(trimmed)))
|
||||
continue
|
||||
}
|
||||
|
||||
paragraphBuffer.push(trimmed)
|
||||
}
|
||||
|
||||
flushParagraph()
|
||||
return result.join('\n')
|
||||
}
|
||||
|
||||
export function replaceFirstMindmapText(markdown: string, oldText: string, newText: string) {
|
||||
const normalizedOld = oldText.replace(/^(摘要|要点|表格|代码|公式|图片):/, '').trim()
|
||||
const normalizedOld = oldText.replace(/^(引用|表格|代码块)(\s|:|:)?/, '').trim()
|
||||
if (!normalizedOld || !newText.trim()) return markdown
|
||||
|
||||
const escaped = normalizedOld.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
|
@ -171,7 +160,7 @@ export function replaceFirstMindmapText(markdown: string, oldText: string, newTe
|
|||
}
|
||||
|
||||
const lines = markdown.split(/\r?\n/)
|
||||
const targetLineIndex = lines.findIndex((line) => stripMarkdownInline(line).includes(normalizedOld))
|
||||
const targetLineIndex = lines.findIndex((line) => normalizeNodeText(line).includes(normalizedOld))
|
||||
if (targetLineIndex >= 0) {
|
||||
lines[targetLineIndex] = lines[targetLineIndex].replace(normalizedOld, newText.trim())
|
||||
return lines.join('\n')
|
||||
|
|
|
|||
|
|
@ -1,18 +1,24 @@
|
|||
import axios from 'axios'
|
||||
|
||||
// 创建 axios 实例
|
||||
const getApiBaseURL = () => {
|
||||
const pathname = window.location.pathname
|
||||
const basePath = pathname === '/mindmap' || pathname.startsWith('/mindmap/') ? '/mindmap' : ''
|
||||
return `${basePath}/api`
|
||||
}
|
||||
|
||||
// ?? axios ??
|
||||
const request = axios.create({
|
||||
baseURL: '',
|
||||
timeout: 300000, // 5分钟超时
|
||||
baseURL: getApiBaseURL(),
|
||||
timeout: 300000, // 5????
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
// 请求拦截器
|
||||
// ?????
|
||||
request.interceptors.request.use(
|
||||
(config) => {
|
||||
// 可以在这里添加认证token等
|
||||
// ?????????token?
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
|
|
@ -20,48 +26,54 @@ request.interceptors.request.use(
|
|||
}
|
||||
)
|
||||
|
||||
// 响应拦截器
|
||||
// ?????
|
||||
request.interceptors.response.use(
|
||||
(response) => {
|
||||
return response.data
|
||||
},
|
||||
(error) => {
|
||||
// 统一错误处理
|
||||
// ??????
|
||||
if (error.response) {
|
||||
const serverMessage = error.response.data?.error || error.response.data?.detail
|
||||
if (serverMessage) {
|
||||
error.message = serverMessage
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
switch (error.response.status) {
|
||||
case 400:
|
||||
error.message = '请求参数错误'
|
||||
error.message = '??????'
|
||||
break
|
||||
case 401:
|
||||
error.message = '未授权,请重新登录'
|
||||
error.message = '?????????'
|
||||
break
|
||||
case 403:
|
||||
error.message = '拒绝访问'
|
||||
error.message = '????'
|
||||
break
|
||||
case 404:
|
||||
error.message = '请求资源不存在'
|
||||
error.message = '???????'
|
||||
break
|
||||
case 500:
|
||||
error.message = '服务器内部错误'
|
||||
error.message = '???????'
|
||||
break
|
||||
case 502:
|
||||
error.message = '网关错误'
|
||||
error.message = '????'
|
||||
break
|
||||
case 503:
|
||||
error.message = '服务不可用'
|
||||
error.message = '?????'
|
||||
break
|
||||
case 504:
|
||||
error.message = '网关超时'
|
||||
error.message = '????'
|
||||
break
|
||||
default:
|
||||
error.message = `连接错误${error.response.status}`
|
||||
error.message = `????${error.response.status}`
|
||||
}
|
||||
} else {
|
||||
error.message = '网络连接异常'
|
||||
error.message = '??????'
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default request
|
||||
export default request
|
||||
|
|
|
|||
|
|
@ -17,14 +17,16 @@
|
|||
@dragleave="isDragging = false"
|
||||
@click="triggerUpload"
|
||||
>
|
||||
<div class="upload-content" v-show="!isUploadAreaCollapsed">
|
||||
<div class="upload-content" v-if="uploadedFiles.length === 0">
|
||||
<el-icon class="upload-icon"><Folder /></el-icon>
|
||||
<div class="upload-text">文件导入</div>
|
||||
<div class="upload-hint">支持 PDF、Word、PNG 格式文件,可转换为 Markdown 和思维导图,也可手动粘贴 Markdown 源码</div>
|
||||
<div class="upload-copy">
|
||||
<div class="upload-text">文件导入</div>
|
||||
<div class="upload-hint">支持 MD、PDF、Word、JPG、PNG、BMP、TIFF 等格式文件</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="uploaded-files">
|
||||
<div class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
|
||||
<div class="uploaded-files" v-else>
|
||||
<div class="file-item" v-for="(file, index) in uploadedDisplayFiles" :key="index">
|
||||
<el-icon class="file-icon"><Document /></el-icon>
|
||||
<span class="file-name">{{ file.name }}</span>
|
||||
<el-button
|
||||
|
|
@ -33,15 +35,15 @@
|
|||
@click.stop="removeFile(index)"
|
||||
class="remove-button"
|
||||
/>
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="isProcessing || isUploading"
|
||||
@click.stop="handleProcessDocument"
|
||||
>
|
||||
开始转换
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="upload-actions" v-if="uploadedFiles.length > 0">
|
||||
<el-button type="primary" :loading="isProcessing || isUploading" @click.stop="handleProcessDocument">
|
||||
开始转换
|
||||
</el-button>
|
||||
<el-button @click.stop="clearAllFiles">清空</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showSettings" class="settings-panel">
|
||||
|
|
@ -52,10 +54,12 @@
|
|||
</el-button>
|
||||
</div>
|
||||
<ConfigPanel
|
||||
v-model="config"
|
||||
:model-value="config"
|
||||
:backend-options="backendOptions"
|
||||
:language-options="languageOptions"
|
||||
@update:model-value="applyConfig"
|
||||
@backend-change="handleBackendChange"
|
||||
@close="closeSettings"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -136,16 +140,35 @@
|
|||
</div>
|
||||
|
||||
<div v-show="activeTab === 'source'" class="source-content">
|
||||
<div class="source-toolbar">
|
||||
<el-button
|
||||
:type="hasActiveReplacementRules ? 'primary' : 'default'"
|
||||
class="replacement-config-button"
|
||||
@click="openReplacementDialog"
|
||||
>
|
||||
{{ hasActiveReplacementRules ? `动态模板渲染(已配置${activeReplacementRuleCount}条)` : '动态模板渲染' }}
|
||||
</el-button>
|
||||
<div v-if="templateRenderError" class="template-error-inline">
|
||||
{{ templateRenderError }}
|
||||
<div class="content-toolbar source-toolbar">
|
||||
<div class="content-toolbar-info source-mode-toolbar">
|
||||
<el-segmented
|
||||
v-model="sourceContentMode"
|
||||
:options="sourceContentModeOptions"
|
||||
size="small"
|
||||
:disabled="sourceViewMode === 'ast' || isSmartOrganizing"
|
||||
/>
|
||||
<span v-if="isSmartOrganizing" class="smart-organize-status">
|
||||
{{ smartOrganizeStage || '智能整理中' }} {{ smartOrganizeProgress }}%
|
||||
</span>
|
||||
<span v-else-if="smartOrganizeError" class="template-error-inline">
|
||||
{{ smartOrganizeError }}
|
||||
</span>
|
||||
<span v-else-if="sourceContentMode === 'smart' && smartMarkdownContent" class="smart-organize-status">
|
||||
智能整理结果
|
||||
</span>
|
||||
<span v-else-if="templateRenderError" class="template-error-inline">
|
||||
{{ templateRenderError }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="content-toolbar-actions">
|
||||
<el-button
|
||||
:type="hasActiveReplacementRules ? 'primary' : 'default'"
|
||||
class="replacement-config-button"
|
||||
@click="openReplacementDialog"
|
||||
>
|
||||
{{ hasActiveReplacementRules ? `动态模板渲染(已配置${activeReplacementRuleCount}条)` : '动态模板渲染' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -163,7 +186,11 @@
|
|||
|
||||
<div v-show="activeTab === 'mindmap'" class="mindmap-content">
|
||||
<div class="mindmap-box">
|
||||
<MindMapRenderer :content="renderedMindmapContent" @node-edit="handleMindmapNodeEdit" />
|
||||
<MindMapRenderer
|
||||
:content="renderedMindmapContent"
|
||||
:export-resolution="config.exportResolution"
|
||||
@node-edit="handleMindmapNodeEdit"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -174,8 +201,7 @@
|
|||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
multiple
|
||||
accept=".pdf,.doc,.docx,.png"
|
||||
accept=".md,.pdf,.doc,.docx,.png,.jpg,.jpeg,.webp,.bmp,.tiff,.gif,.jp2"
|
||||
style="position: absolute; width: 0; height: 0; overflow: hidden;"
|
||||
@change="handleFileInputChange"
|
||||
/>
|
||||
|
|
@ -219,19 +245,51 @@
|
|||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { Delete, Document, Folder, Close, Loading, ArrowDown } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import ConfigPanel from '@/components/ConfigPanel.vue'
|
||||
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
|
||||
import MindMapRenderer from '@/components/MindMapRenderer.vue'
|
||||
import { useDocumentProcessor } from '@/composables/useDocumentProcessor'
|
||||
import { documentApi } from '@/api/document'
|
||||
import { DOCUMENT_CONFIG_STORAGE_KEY, useDocumentProcessor } from '@/composables/useDocumentProcessor'
|
||||
import { markdownToAstString } from '@/utils/markdownAst'
|
||||
import { buildMindmapMarkdown, replaceFirstMindmapText } from '@/utils/mindmapMarkdown'
|
||||
import { createEmptyReplacementRule, renderMarkdownTemplate, type ReplacementRule } from '@/utils/markdownTemplate'
|
||||
|
||||
const MARKDOWN_RENDER_MODE_KEY = 'mineru.documentProcessor.markdownRenderMode'
|
||||
const SOURCE_VIEW_MODE_KEY = 'mineru.documentProcessor.sourceViewMode'
|
||||
|
||||
function loadStoredValue<T>(key: string, fallback: T, validate?: (value: unknown) => value is T): T {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(key)
|
||||
if (!raw) return fallback
|
||||
const value = JSON.parse(raw)
|
||||
return validate ? (validate(value) ? value : fallback) : value
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function storeValue(key: string, value: unknown) {
|
||||
try {
|
||||
window.localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
// 浏览器禁用本地存储时不影响当前页面使用。
|
||||
}
|
||||
}
|
||||
|
||||
function isMarkdownRenderMode(value: unknown): value is 'markdown' | 'html' | 'pdf' | 'richtext' {
|
||||
return value === 'markdown' || value === 'html' || value === 'pdf' || value === 'richtext'
|
||||
}
|
||||
|
||||
function isSourceViewMode(value: unknown): value is 'markdown' | 'ast' {
|
||||
return value === 'markdown' || value === 'ast'
|
||||
}
|
||||
|
||||
const {
|
||||
uploadedFiles,
|
||||
uploadedDisplayFiles,
|
||||
config,
|
||||
results,
|
||||
isUploading,
|
||||
|
|
@ -253,16 +311,41 @@ const fileInput = ref<HTMLInputElement | null>(null)
|
|||
const isDragging = ref(false)
|
||||
const activeTab = ref('markdown')
|
||||
const isUploadAreaCollapsed = ref(false)
|
||||
const markdownRenderMode = ref<'markdown' | 'html' | 'pdf' | 'richtext'>('markdown')
|
||||
const markdownRenderMode = ref<'markdown' | 'html' | 'pdf' | 'richtext'>(
|
||||
loadStoredValue(MARKDOWN_RENDER_MODE_KEY, 'markdown', isMarkdownRenderMode)
|
||||
)
|
||||
const markdownCompatibilityFlavor = ref<'commonmark' | 'gfm'>('gfm')
|
||||
const sourceViewMode = ref<'markdown' | 'ast'>('markdown')
|
||||
const sourceViewMode = ref<'markdown' | 'ast'>(
|
||||
loadStoredValue(SOURCE_VIEW_MODE_KEY, 'markdown', isSourceViewMode)
|
||||
)
|
||||
const sourceContentMode = ref<'source' | 'smart'>('source')
|
||||
const sourceContentModeOptions = [
|
||||
{ label: '源码', value: 'source' },
|
||||
{ label: '智能整理', value: 'smart' }
|
||||
]
|
||||
const showReplacementDialog = ref(false)
|
||||
const isMobileDialog = ref(false)
|
||||
const replacementRules = ref<ReplacementRule[]>([])
|
||||
const draftReplacementRules = ref<ReplacementRule[]>([])
|
||||
const smartMarkdownContent = ref('')
|
||||
const smartOrganizeTaskId = ref('')
|
||||
const isSmartOrganizing = ref(false)
|
||||
const smartOrganizeProgress = ref(0)
|
||||
const smartOrganizeStage = ref('')
|
||||
const smartOrganizeError = ref('')
|
||||
let smartOrganizeTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
watch(markdownRenderMode, (value) => storeValue(MARKDOWN_RENDER_MODE_KEY, value))
|
||||
watch(sourceViewMode, (value) => storeValue(SOURCE_VIEW_MODE_KEY, value))
|
||||
|
||||
const manualMarkdownContent = computed(() => results.value?.source || '')
|
||||
const templateRenderResult = computed(() => renderMarkdownTemplate(manualMarkdownContent.value, replacementRules.value))
|
||||
const activeSourceMarkdownContent = computed(() => {
|
||||
if (sourceContentMode.value === 'smart' && smartMarkdownContent.value) {
|
||||
return smartMarkdownContent.value
|
||||
}
|
||||
return manualMarkdownContent.value
|
||||
})
|
||||
const templateRenderResult = computed(() => renderMarkdownTemplate(activeSourceMarkdownContent.value, replacementRules.value))
|
||||
const renderedMarkdownContent = computed(() => templateRenderResult.value.markdown)
|
||||
const renderedMindmapContent = computed(() => buildMindmapMarkdown(renderedMarkdownContent.value))
|
||||
const templateRenderError = computed(() => templateRenderResult.value.error)
|
||||
|
|
@ -290,15 +373,114 @@ const sourcePanelContent = computed({
|
|||
if (sourceViewMode.value === 'ast') {
|
||||
return markdownToAstString(renderedMarkdownContent.value)
|
||||
}
|
||||
return manualMarkdownContent.value
|
||||
return activeSourceMarkdownContent.value
|
||||
},
|
||||
set: (value: string) => {
|
||||
if (sourceViewMode.value === 'markdown' && results.value) {
|
||||
if (sourceViewMode.value !== 'markdown') return
|
||||
if (sourceContentMode.value === 'smart') {
|
||||
smartMarkdownContent.value = value
|
||||
return
|
||||
}
|
||||
if (results.value) {
|
||||
results.value.source = value
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const stopSmartOrganizePolling = () => {
|
||||
if (smartOrganizeTimer) {
|
||||
clearInterval(smartOrganizeTimer)
|
||||
smartOrganizeTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const resetSmartOrganizeState = () => {
|
||||
stopSmartOrganizePolling()
|
||||
sourceContentMode.value = 'source'
|
||||
smartMarkdownContent.value = ''
|
||||
smartOrganizeTaskId.value = ''
|
||||
isSmartOrganizing.value = false
|
||||
smartOrganizeProgress.value = 0
|
||||
smartOrganizeStage.value = ''
|
||||
smartOrganizeError.value = ''
|
||||
}
|
||||
|
||||
const startSmartOrganizePolling = (taskId: string) => {
|
||||
stopSmartOrganizePolling()
|
||||
smartOrganizeTimer = setInterval(async () => {
|
||||
try {
|
||||
const data = await documentApi.getMindmapProgress(taskId)
|
||||
smartOrganizeProgress.value = data.progress
|
||||
smartOrganizeStage.value = data.stage
|
||||
if (data.status === 'completed') {
|
||||
stopSmartOrganizePolling()
|
||||
isSmartOrganizing.value = false
|
||||
smartMarkdownContent.value = data.result_md || ''
|
||||
smartOrganizeError.value = ''
|
||||
sourceContentMode.value = 'smart'
|
||||
ElMessage.success('智能整理完成')
|
||||
} else if (data.status === 'failed') {
|
||||
stopSmartOrganizePolling()
|
||||
isSmartOrganizing.value = false
|
||||
sourceContentMode.value = 'source'
|
||||
smartOrganizeError.value = data.error || '智能整理失败'
|
||||
ElMessage.error(smartOrganizeError.value)
|
||||
}
|
||||
} catch (err) {
|
||||
stopSmartOrganizePolling()
|
||||
isSmartOrganizing.value = false
|
||||
sourceContentMode.value = 'source'
|
||||
smartOrganizeError.value = (err as Error).message || '智能整理进度查询失败'
|
||||
ElMessage.error(smartOrganizeError.value)
|
||||
}
|
||||
}, 1500)
|
||||
}
|
||||
|
||||
const startSmartOrganize = async () => {
|
||||
const markdown = manualMarkdownContent.value.trim()
|
||||
if (!markdown) {
|
||||
sourceContentMode.value = 'source'
|
||||
ElMessage.warning('暂无 Markdown 源码可整理')
|
||||
return
|
||||
}
|
||||
if (smartMarkdownContent.value) {
|
||||
sourceContentMode.value = 'smart'
|
||||
return
|
||||
}
|
||||
|
||||
const taskId = `mindmap-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
smartOrganizeTaskId.value = taskId
|
||||
isSmartOrganizing.value = true
|
||||
smartOrganizeProgress.value = 0
|
||||
smartOrganizeStage.value = '创建智能整理任务'
|
||||
smartOrganizeError.value = ''
|
||||
|
||||
try {
|
||||
await documentApi.createMindmapTask(taskId, markdown, 'hybrid', config.mindmapPrompt, {
|
||||
base_url: config.mindmapLlmBaseUrl || undefined,
|
||||
api_key: config.mindmapLlmApiKey || undefined,
|
||||
model: config.mindmapLlmModel || undefined,
|
||||
timeout: config.mindmapLlmTimeout,
|
||||
temperature: config.mindmapLlmTemperature,
|
||||
max_context_tokens: config.mindmapLlmMaxContextTokens,
|
||||
max_output_tokens: config.mindmapLlmMaxOutputTokens,
|
||||
safety_tokens: config.mindmapLlmSafetyTokens
|
||||
})
|
||||
startSmartOrganizePolling(taskId)
|
||||
} catch (err) {
|
||||
isSmartOrganizing.value = false
|
||||
sourceContentMode.value = 'source'
|
||||
smartOrganizeError.value = (err as Error).message || '智能整理任务创建失败'
|
||||
ElMessage.error(smartOrganizeError.value)
|
||||
}
|
||||
}
|
||||
|
||||
watch(sourceContentMode, (value) => {
|
||||
if (value === 'smart') {
|
||||
startSmartOrganize()
|
||||
}
|
||||
})
|
||||
|
||||
const toggleSettings = () => {
|
||||
if (showSettings.value) {
|
||||
const settingsPanel = document.querySelector('.settings-panel')
|
||||
|
|
@ -323,6 +505,12 @@ const toggleSettings = () => {
|
|||
}
|
||||
}
|
||||
|
||||
const closeSettings = () => {
|
||||
if (showSettings.value) {
|
||||
toggleSettings()
|
||||
}
|
||||
}
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
const settingsPanel = document.querySelector('.settings-panel')
|
||||
const settingsButton = document.querySelector('.settings-button')
|
||||
|
|
@ -347,7 +535,17 @@ const handleBackendChange = (backend: string) => {
|
|||
console.log('Backend changed to:', backend)
|
||||
}
|
||||
|
||||
const applyConfig = (nextConfig: typeof config) => {
|
||||
Object.assign(config, nextConfig)
|
||||
try {
|
||||
window.localStorage.setItem(DOCUMENT_CONFIG_STORAGE_KEY, JSON.stringify(nextConfig))
|
||||
} catch {
|
||||
// 浏览器禁用本地存储时不影响当前页面使用。
|
||||
}
|
||||
}
|
||||
|
||||
const handleProcessDocument = async () => {
|
||||
resetSmartOrganizeState()
|
||||
await processDocument()
|
||||
if (error.value) {
|
||||
ElMessage.error(error.value)
|
||||
|
|
@ -403,13 +601,18 @@ const saveReplacementRules = () => {
|
|||
|
||||
const handleMindmapNodeEdit = ({ oldText, newText }: { oldText: string; newText: string }) => {
|
||||
if (!results.value) return
|
||||
const updated = replaceFirstMindmapText(results.value.source || results.value.markdown, oldText, newText)
|
||||
if (updated === (results.value.source || results.value.markdown)) {
|
||||
const currentMarkdown = activeSourceMarkdownContent.value
|
||||
const updated = replaceFirstMindmapText(currentMarkdown, oldText, newText)
|
||||
if (updated === currentMarkdown) {
|
||||
ElMessage.warning('未在 Markdown 中定位到该节点文本,可在源码区直接编辑')
|
||||
return
|
||||
}
|
||||
results.value.source = updated
|
||||
results.value.markdown = updated
|
||||
if (sourceContentMode.value === 'smart') {
|
||||
smartMarkdownContent.value = updated
|
||||
} else {
|
||||
results.value.source = updated
|
||||
results.value.markdown = updated
|
||||
}
|
||||
ElMessage.success('节点已同步到 Markdown')
|
||||
}
|
||||
|
||||
|
|
@ -417,20 +620,17 @@ const triggerUpload = () => {
|
|||
fileInput.value?.click()
|
||||
}
|
||||
|
||||
const resetReplacementConfig = () => {
|
||||
replacementRules.value = []
|
||||
draftReplacementRules.value = []
|
||||
}
|
||||
|
||||
const handleFileInputChange = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
if (input.files) {
|
||||
await handleFileUpload(input.files)
|
||||
input.value = ''
|
||||
if (uploadedFiles.value.length > 0) {
|
||||
resetSmartOrganizeState()
|
||||
isUploadAreaCollapsed.value = true
|
||||
initializeManualResult()
|
||||
resetReplacementConfig()
|
||||
if (!results.value) {
|
||||
initializeManualResult()
|
||||
}
|
||||
markdownRenderMode.value = 'markdown'
|
||||
sourceViewMode.value = 'markdown'
|
||||
activeTab.value = 'source'
|
||||
|
|
@ -445,9 +645,11 @@ const handleDrop = async (event: DragEvent) => {
|
|||
if (event.dataTransfer?.files) {
|
||||
await handleFileUpload(event.dataTransfer.files)
|
||||
if (uploadedFiles.value.length > 0) {
|
||||
resetSmartOrganizeState()
|
||||
isUploadAreaCollapsed.value = true
|
||||
initializeManualResult()
|
||||
resetReplacementConfig()
|
||||
if (!results.value) {
|
||||
initializeManualResult()
|
||||
}
|
||||
markdownRenderMode.value = 'markdown'
|
||||
sourceViewMode.value = 'markdown'
|
||||
activeTab.value = 'source'
|
||||
|
|
@ -457,14 +659,15 @@ const handleDrop = async (event: DragEvent) => {
|
|||
|
||||
const removeFile = (index: number) => {
|
||||
uploadedFiles.value.splice(index, 1)
|
||||
uploadedDisplayFiles.value.splice(index, 1)
|
||||
if (uploadedFiles.value.length === 0) {
|
||||
isUploadAreaCollapsed.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const clearAllFiles = () => {
|
||||
resetSmartOrganizeState()
|
||||
clearAll()
|
||||
resetReplacementConfig()
|
||||
isUploadAreaCollapsed.value = false
|
||||
}
|
||||
|
||||
|
|
@ -474,6 +677,7 @@ onMounted(() => {
|
|||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopSmartOrganizePolling()
|
||||
window.removeEventListener('resize', updateViewportState)
|
||||
})
|
||||
</script>
|
||||
|
|
@ -522,7 +726,7 @@ onUnmounted(() => {
|
|||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
padding: 24px;
|
||||
padding: 0 24px;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
|
|
@ -537,19 +741,23 @@ onUnmounted(() => {
|
|||
.drag-upload-area {
|
||||
border: 2px dashed #CED4DA;
|
||||
border-radius: 8px;
|
||||
padding: 20px 24px;
|
||||
padding: 8px 16px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
background-color: #FFFFFF;
|
||||
margin-bottom: 16px;
|
||||
margin-bottom: 0;
|
||||
overflow: hidden;
|
||||
height: 52px;
|
||||
min-height: 52px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.drag-upload-area.collapsed {
|
||||
padding: 8px 16px;
|
||||
min-height: 36px;
|
||||
display: block;
|
||||
min-height: 52px;
|
||||
}
|
||||
|
||||
.drag-upload-area:hover,
|
||||
|
|
@ -560,56 +768,52 @@ onUnmounted(() => {
|
|||
|
||||
.upload-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
font-size: 48px;
|
||||
font-size: 24px;
|
||||
color: #165DFF;
|
||||
}
|
||||
|
||||
.upload-copy {
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
font-size: 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #343A40;
|
||||
}
|
||||
|
||||
.upload-hint {
|
||||
font-size: 14px;
|
||||
font-size: 12px;
|
||||
color: #6C757D;
|
||||
line-height: 1.5;
|
||||
max-width: 400px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.uploaded-files {
|
||||
margin-top: 24px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.upload-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.drag-upload-area.collapsed .uploaded-files {
|
||||
margin-top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
padding: 0;
|
||||
background-color: #F8F9FA;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 2px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 0;
|
||||
transition: all 0.3s ease;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
|
@ -625,15 +829,16 @@ onUnmounted(() => {
|
|||
|
||||
.file-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: calc(100% - 40px);
|
||||
}
|
||||
|
||||
.remove-button {
|
||||
flex-shrink: 0;
|
||||
color: #6C757D;
|
||||
padding: 4px;
|
||||
}
|
||||
|
|
@ -710,6 +915,10 @@ onUnmounted(() => {
|
|||
border-bottom: 1px solid #E9ECEF;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__header) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__nav) {
|
||||
padding-left: 16px;
|
||||
}
|
||||
|
|
@ -857,23 +1066,21 @@ onUnmounted(() => {
|
|||
.markdown-box {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
background-color: white;
|
||||
overflow: hidden;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.mindmap-box {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
background-color: white;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.source-content {
|
||||
|
|
@ -892,6 +1099,45 @@ onUnmounted(() => {
|
|||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-info,
|
||||
.content-toolbar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-info {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.source-mode-toolbar {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.smart-organize-status {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-actions {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.replacement-config-button {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
|
@ -994,7 +1240,10 @@ onUnmounted(() => {
|
|||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.main-content,
|
||||
.main-content {
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.result-content {
|
||||
padding: 16px;
|
||||
}
|
||||
|
|
@ -1004,11 +1253,11 @@ onUnmounted(() => {
|
|||
}
|
||||
|
||||
.drag-upload-area {
|
||||
padding: 32px 16px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
font-size: 32px;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
|
|
@ -1033,6 +1282,14 @@ onUnmounted(() => {
|
|||
align-items: stretch;
|
||||
}
|
||||
|
||||
.content-toolbar-info {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.content-toolbar-actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.replacement-dialog-body {
|
||||
max-height: none;
|
||||
padding-right: 0;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import vue from '@vitejs/plugin-vue'
|
|||
import { resolve } from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
|
|
@ -13,8 +14,13 @@ export default defineConfig({
|
|||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
target: process.env.VITE_API_PROXY || 'http://127.0.0.1:8000',
|
||||
changeOrigin: true
|
||||
},
|
||||
'/mindmap/api': {
|
||||
target: process.env.VITE_API_PROXY || 'http://127.0.0.1:8000',
|
||||
changeOrigin: true,
|
||||
rewrite: path => path.replace(/^\/mindmap\/api/, '/api')
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -30,4 +36,4 @@ export default defineConfig({
|
|||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue