feat(思维导图助手):升级mineru解析到2.7.6版本
parent
846739cf77
commit
94d2f22b3c
|
|
@ -15,6 +15,11 @@ tmp
|
|||
node_modules
|
||||
web_ui/node_modules
|
||||
web_ui/dist
|
||||
mineru/cli/static/web
|
||||
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,108 +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.12,<3" \
|
||||
"modelscope" \
|
||||
"magic-pdf" \
|
||||
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
|
||||
|
||||
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"]
|
||||
|
|
|
|||
|
|
@ -1,65 +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
|
||||
ENV MINERU_MODEL_SOURCE=local
|
||||
ENV MINERU_MODEL_DIR=/models
|
||||
ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json
|
||||
|
||||
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/*
|
||||
|
||||
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 && \
|
||||
python3 -m pip install \
|
||||
"numpy==1.26.4" \
|
||||
"opencv-python==4.11.0.86" \
|
||||
"pydantic>=2.12,<3" \
|
||||
"modelscope" \
|
||||
"magic-pdf" \
|
||||
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
|
||||
|
||||
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 . .
|
||||
COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"]
|
||||
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,29 +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 install --force-reinstall --no-cache-dir "pydantic>=2.12,<3" -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python3 -c "import pydantic; print('pydantic', pydantic.__version__); from pydantic import TypeAdapter; print('pydantic TypeAdapter ok')" && \
|
||||
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
|
||||
|
|
@ -1,47 +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}"
|
||||
|
||||
MODEL_DIR=${MINERU_MODEL_DIR:-/models}
|
||||
PIPELINE_MODEL_DIR=${MINERU_PIPELINE_MODEL_DIR:-${MODEL_DIR}/pipeline}
|
||||
VLM_MODEL_DIR=${MINERU_VLM_MODEL_DIR:-${MODEL_DIR}/vlm}
|
||||
CONFIG_PATH=${MINERU_TOOLS_CONFIG_JSON:-/root/mineru.json}
|
||||
|
||||
mkdir -p "$PIPELINE_MODEL_DIR" "$VLM_MODEL_DIR" "$(dirname "$CONFIG_PATH")"
|
||||
|
||||
export CONFIG_PATH PIPELINE_MODEL_DIR VLM_MODEL_DIR
|
||||
|
||||
# Preserve mounted settings, including optional title-aided configuration.
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
config_path = Path(os.environ["CONFIG_PATH"])
|
||||
config = {
|
||||
"bucket_info": {"[default]": [None, None, None]},
|
||||
"latex-delimiter-config": {
|
||||
"display": {"left": "$$", "right": "$$"},
|
||||
"inline": {"left": "$", "right": "$"},
|
||||
},
|
||||
"llm-aided-config": {
|
||||
"title_aided": {
|
||||
"api_key": "",
|
||||
"base_url": "",
|
||||
"model": "",
|
||||
"enable_thinking": False,
|
||||
"enable": False,
|
||||
}
|
||||
},
|
||||
"models-dir": {
|
||||
"pipeline": os.environ["PIPELINE_MODEL_DIR"],
|
||||
"vlm": os.environ["VLM_MODEL_DIR"],
|
||||
},
|
||||
"config_version": "1.3.1",
|
||||
}
|
||||
config_path.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
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
|
||||
|
||||
export MINERU_TOOLS_CONFIG_JSON="$CONFIG_PATH"
|
||||
export MINERU_MODEL_SOURCE=${MINERU_MODEL_SOURCE:-local}
|
||||
export PYTHONPATH=${PYTHONPATH:-/app}
|
||||
|
||||
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"]
|
||||
|
|
|
|||
|
|
@ -1,67 +1,26 @@
|
|||
FROM pytorch/pytorch:2.7.1-cuda12.6-cudnn9-runtime
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV MINERU_MODEL_SOURCE=local
|
||||
ENV MINERU_MODEL_DIR=/models
|
||||
ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fontconfig \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
git \
|
||||
&& fc-cache -fv \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN ln -sf "$(command -v python)" /usr/local/bin/python3 && \
|
||||
python -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python -m pip install \
|
||||
'mineru[core]>=2.7.4' \
|
||||
'vllm==0.11.2' \
|
||||
'pydantic>=2.12,<3' \
|
||||
modelscope \
|
||||
magic-pdf \
|
||||
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-gpu \
|
||||
python-pptx \
|
||||
python-docx \
|
||||
openpyxl \
|
||||
xlrd \
|
||||
xlwt \
|
||||
pylatexenc \
|
||||
mammoth \
|
||||
-i https://mirrors.aliyun.com/pypi/simple && \
|
||||
python -m pip cache purge
|
||||
# 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
|
||||
COPY . .
|
||||
COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"]
|
||||
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
|
||||
|
|
@ -71,16 +80,6 @@ def set_lmdeploy_backend(device_type: str) -> str:
|
|||
|
||||
|
||||
def set_default_gpu_memory_utilization() -> float:
|
||||
override = os.getenv("MINERU_GPU_MEMORY_UTILIZATION")
|
||||
if override:
|
||||
try:
|
||||
value = float(override)
|
||||
except ValueError:
|
||||
raise ValueError("MINERU_GPU_MEMORY_UTILIZATION must be a float between 0 and 1")
|
||||
if not 0 < value < 1:
|
||||
raise ValueError("MINERU_GPU_MEMORY_UTILIZATION must be a float between 0 and 1")
|
||||
return value
|
||||
|
||||
from vllm import __version__ as vllm_version
|
||||
device = get_device()
|
||||
gpu_memory = get_vram(device)
|
||||
|
|
@ -107,3 +106,127 @@ def set_default_batch_size() -> int:
|
|||
logger.warning(f'Error determining VRAM: {e}, using default batch_ratio: 1')
|
||||
batch_size = 1
|
||||
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:
|
||||
|
|
@ -110,11 +122,27 @@ class ModelSingleton:
|
|||
vllm_llm = vllm.LLM(**kwargs)
|
||||
elif backend == "vllm-async-engine":
|
||||
try:
|
||||
import inspect
|
||||
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:
|
||||
|
|
@ -123,8 +151,6 @@ class ModelSingleton:
|
|||
from mineru_vl_utils import MinerULogitsProcessor
|
||||
kwargs["logits_processors"] = [MinerULogitsProcessor]
|
||||
# 使用kwargs为 vllm初始化参数
|
||||
supported_args = set(inspect.signature(AsyncEngineArgs).parameters)
|
||||
kwargs = {k: v for k, v in kwargs.items() if k in supported_args}
|
||||
vllm_async_llm = AsyncLLM.from_engine_args(AsyncEngineArgs(**kwargs))
|
||||
elif backend == "lmdeploy-engine":
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -14,10 +14,11 @@ import urllib.request
|
|||
import urllib.error
|
||||
from pathlib import Path
|
||||
import glob
|
||||
import shutil
|
||||
|
||||
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form, APIRouter, Header
|
||||
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
|
||||
|
|
@ -338,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}")
|
||||
|
|
@ -359,6 +362,7 @@ 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):
|
||||
|
|
@ -418,7 +422,7 @@ DEFAULT_MINDMAP_ORGANIZE_PROMPT = """你是文档结构整理助手。请基于
|
|||
3. 保留原文语言:英文内容输出英文,中文内容输出中文,多语言内容按原文语言分别保留。
|
||||
4. 不要编造原文没有的信息。
|
||||
5. 保留关键数字、公式、专有名词、步骤和结论。
|
||||
6. 最大层级不超过 4 层。
|
||||
6. 最大层级不超过 6 层。
|
||||
7. 每个父节点下最多 8 个子节点。
|
||||
8. 节点标题尽量简短,正文说明使用短句列表。
|
||||
9. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。"""
|
||||
|
|
@ -430,7 +434,7 @@ MINDMAP_MERGE_PROMPT = """你是 Markdown 思维导图结构校对助手。下
|
|||
2. 只检查和调整标题层级结构、顺序、重复标题和父子关系。
|
||||
3. 不要重新总结正文,不要扩写内容,不要新增原文没有的信息。
|
||||
4. 保留各局部大纲中的源语言:英文保持英文,中文保持中文,多语言分别保留。
|
||||
5. 最大层级不超过 4 层。
|
||||
5. 最大层级不超过 6 层。
|
||||
6. 每个父节点下最多 8 个子节点,必要时只合并相近标题。
|
||||
7. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。"""
|
||||
|
||||
|
|
@ -792,7 +796,9 @@ async def get_mindmap_progress(task_id: str):
|
|||
|
||||
|
||||
@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"]),
|
||||
|
|
@ -814,7 +820,7 @@ async def parse_pdf(
|
|||
):
|
||||
# 从 app 实例状态中获取配置 (FastAPI 实例会在下方创建)
|
||||
from fastapi import Request
|
||||
config = getattr(app.state, "config", {})
|
||||
config = dict(getattr(app.state, "config", {}))
|
||||
|
||||
# 初始化进度跟踪
|
||||
task_id = x_task_id or form_task_id or str(uuid.uuid4())
|
||||
|
|
@ -831,13 +837,14 @@ async def parse_pdf(
|
|||
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)
|
||||
|
|
@ -847,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)}"})
|
||||
|
|
@ -922,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:
|
||||
|
|
@ -943,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)}"
|
||||
|
|
@ -978,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}")
|
||||
|
|
@ -991,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"
|
||||
|
|
@ -1018,12 +1045,19 @@ 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__":
|
||||
|
|
|
|||
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()
|
||||
|
|
@ -1,34 +1,14 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
VERSION=${VERSION:-$(date +%Y%m%d%H%M%S)}
|
||||
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 "Unsupported API_FLAVOR: $API_FLAVOR. Use corex or cuda." >&2
|
||||
exit 1
|
||||
;;
|
||||
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
|
||||
|
||||
echo "Building UnisMindMap API image (${API_FLAVOR}): unis-mindmap-api:${VERSION}"
|
||||
sudo docker build -f "$API_DOCKERFILE" \
|
||||
-t unis-mindmap-api:${VERSION} \
|
||||
-t unis-mindmap-api:${API_FLAVOR} \
|
||||
-t unis-mindmap-api:latest \
|
||||
.
|
||||
|
||||
echo "Building UnisMindMap Web image: unis-mindmap-web:${VERSION}"
|
||||
sudo docker build -f web_ui/Dockerfile.portable \
|
||||
-t unis-mindmap-web:${VERSION} \
|
||||
-t unis-mindmap-web:latest \
|
||||
web_ui
|
||||
"$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()
|
||||
|
|
@ -1,33 +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-api}
|
||||
WEB_NAME=${WEB_NAME:-mindmap-web}
|
||||
API_NAME=${API_NAME:-mineru-276-api}
|
||||
WEB_NAME=${WEB_NAME:-mindmap-276-web}
|
||||
WEB_PORT=${WEB_PORT:-9898}
|
||||
MINERU_API_URL=${MINERU_API_URL:-http://${API_NAME}:8000}
|
||||
MINERU_GPU_MEMORY_UTILIZATION=${MINERU_GPU_MEMORY_UTILIZATION:-0.5}
|
||||
API_PORT=${API_PORT:-8100}
|
||||
MINERU_MODEL_DIR=${MINERU_MODEL_DIR:-/data/unis/mineru-models}
|
||||
MINERU_PYTHONPATH=${MINERU_PYTHONPATH:-/app:/usr/local/corex-4.4.0/lib64/python3/dist-packages}
|
||||
|
||||
sudo docker network create "$NETWORK" >/dev/null 2>&1 || true
|
||||
sudo docker rm -f "$API_NAME" "$WEB_NAME" >/dev/null 2>&1 || true
|
||||
sudo mkdir -p "$MINERU_MODEL_DIR"/pipeline "$MINERU_MODEL_DIR"/vlm
|
||||
sudo chmod -R 777 "$MINERU_MODEL_DIR"
|
||||
|
||||
sudo docker run -d --name "$API_NAME" --network "$NETWORK" \
|
||||
--privileged --ipc=host --shm-size=32g \
|
||||
-v "${MINERU_MODEL_DIR}:/models" \
|
||||
-e MINERU_MODEL_SOURCE="${MINERU_MODEL_SOURCE:-local}" \
|
||||
-e MINERU_MODEL_DIR=/models \
|
||||
-e MINERU_PIPELINE_MODEL_DIR=/models/pipeline \
|
||||
-e MINERU_VLM_MODEL_DIR=/models/vlm \
|
||||
-e PYTHONPATH="$MINERU_PYTHONPATH" \
|
||||
-e MINERU_GPU_MEMORY_UTILIZATION="$MINERU_GPU_MEMORY_UTILIZATION" \
|
||||
unis-mindmap-api:latest \
|
||||
mineru-api --host 0.0.0.0 --port 8000
|
||||
|
||||
sudo docker run -d --name "$WEB_NAME" --network "$NETWORK" \
|
||||
-p "${WEB_PORT}:9898" \
|
||||
-e MINERU_API_URL="$MINERU_API_URL" \
|
||||
unis-mindmap-web:latest
|
||||
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.*
|
||||
|
|
@ -5,7 +5,7 @@ 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 install
|
||||
RUN npm config set registry https://registry.npmmirror.com && npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue