refactor: pin MinerU 2.7.4 and retire standalone workbench
parent
8b501924f7
commit
71e4cb4254
|
|
@ -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/>.
|
||||
|
||||
23
README.md
23
README.md
|
|
@ -1,2 +1,23 @@
|
|||
# Unis MinerU 解析服务
|
||||
|
||||
markitdown
|
||||
本仓库维护官方 `mineru-2.7.4-released` 解析源码及部署配置;`mineru/` 与官方发布包一致。
|
||||
|
||||
思维导图工作台、用户授权、模型整理、文件格式分流和版本适配已迁至 MaxKB。旧 web_ui 不再部署。官方说明见 [README.mineru-upstream.md](README.mineru-upstream.md),基线哈希见 [2.7.4-baseline.json](docs/mineru-migration/2.7.4-baseline.json)。旧业务实现可从 Git 提交 `8b50192` 回看。
|
||||
|
||||
## 启动
|
||||
|
||||
在经过验证的独立虚拟环境安装本项目,准备原版 pipeline / VLM 模型及 mineru.json,设置 `MINERU_TOOLS_CONFIG_JSON` 和 `MINERU_MODEL_SOURCE=local`,运行:
|
||||
|
||||
```bash
|
||||
python scripts/run_parser.py --host 127.0.0.1 --port 8100
|
||||
```
|
||||
|
||||
仅启动解析服务。接口为 `/file_parse`,不包含旧 `/api`、`/v1/tasks`、智能整理或工作台静态页面。服务应仅供可信内网调用,业务鉴权在 MaxKB 完成。
|
||||
|
||||
`MINERU_GPU_MEMORY_UTILIZATION` 通过启动参数传给上游引擎;默认限制单个解析请求并发。模型文件不自动下载,也不在启动时执行数据库迁移。
|
||||
|
||||
## 镜像
|
||||
|
||||
CoreX 使用 `docker/china/Dockerfile.corex`;CUDA 使用 `docker/global/Dockerfile.cuda`。构建只安装当前源码,先固定厂商 Torch/torchvision/vLLM 版本,再解析其他依赖;冲突时停止构建。不得在厂商镜像中全量升级。
|
||||
|
||||
`scripts/build-images.sh` 只构建解析镜像;`scripts/start-mindmap.sh` 为兼容旧命令保留,实际仅增量启动 parser,不删除容器或修改业务目录权限。具体国产卡组合仍需在目标硬件验证。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,364 @@
|
|||
<div align="center" xmlns="http://www.w3.org/1999/html">
|
||||
<!-- logo -->
|
||||
<p align="center">
|
||||
<img src="https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/docs/images/MinerU-logo.png" width="300px" style="vertical-align:middle;">
|
||||
</p>
|
||||
|
||||
<!-- icon -->
|
||||
|
||||
[](https://github.com/opendatalab/MinerU)
|
||||
[](https://github.com/opendatalab/MinerU)
|
||||
[](https://github.com/opendatalab/MinerU/issues)
|
||||
[](https://github.com/opendatalab/MinerU/issues)
|
||||
[](https://pypi.org/project/mineru/)
|
||||
[](https://pypi.org/project/mineru/)
|
||||
[](https://pepy.tech/project/mineru)
|
||||
[](https://pepy.tech/project/mineru)
|
||||
[](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
[](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
[](https://colab.research.google.com/gist/myhloli/a3cb16570ab3cfeadf9d8f0ac91b4fca/mineru_demo.ipynb)
|
||||
[](https://arxiv.org/abs/2409.18839)
|
||||
[](https://arxiv.org/abs/2509.22186)
|
||||
[](https://deepwiki.com/opendatalab/MinerU)
|
||||
|
||||
|
||||
<a href="https://trendshift.io/repositories/11174" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11174" alt="opendatalab%2FMinerU | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
|
||||
<!-- language -->
|
||||
|
||||
[English](README.md) | [简体中文](README_zh-CN.md)
|
||||
|
||||
<!-- hot link -->
|
||||
|
||||
<p align="center">
|
||||
🚀<a href="https://mineru.net/?source=github">Access MinerU Now→✅ Zero-Install Web Version ✅ Full-Featured Desktop Client ✅ Instant API Access; Skip deployment headaches – get all product formats in one click. Developers, dive in!</a>
|
||||
</p>
|
||||
|
||||
<!-- join us -->
|
||||
|
||||
<p align="center">
|
||||
👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="https://mineru.net/community-portal/?aliasId=3c430f94" target="_blank">WeChat</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
# Changelog
|
||||
|
||||
- 2026/01/30 2.7.4 Release
|
||||
- Added support for domestic computing platforms IluvatarCorex and Cambricon. Currently, the officially supported domestic computing platforms include:
|
||||
- [Ascend](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Ascend/)
|
||||
- [T-Head](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/THead/)
|
||||
- [METAX](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/METAX/)
|
||||
- [Hygon](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Hygon/)
|
||||
- [Enflame](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Enflame/)
|
||||
- [MooreThreads](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/MooreThreads/)
|
||||
- [IluvatarCorex](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/IluvatarCorex/)
|
||||
- [Cambricon](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Cambricon/)
|
||||
- MinerU continues to ensure compatibility with domestic hardware platforms, supporting mainstream chip architectures. With secure and reliable technology, we empower researchers, government, and enterprises to reach new heights in document digitization!
|
||||
|
||||
- 2026/01/23 2.7.2 Release
|
||||
- Added support for domestic computing platforms Hygon, Enflame, and Moore Threads.
|
||||
- Cross-page table merging optimization, improving merge success rate and merge quality.
|
||||
|
||||
- 2026/01/06 2.7.1 Release
|
||||
- fix bug: #4300
|
||||
- Updated pdfminer.six dependency version to resolve [CVE-2025-64512](https://github.com/advisories/GHSA-wf5f-4jwr-ppcp)
|
||||
- Support automatic correction of input image exif orientation to improve OCR recognition accuracy #4283
|
||||
|
||||
- 2025/12/30 2.7.0 Release
|
||||
- Simplified installation process. No need to separately install `vlm` acceleration engine dependencies. Using `uv pip install mineru[all]` during installation will install all optional backend dependencies.
|
||||
- Added new `hybrid` backend, which combines the advantages of `pipeline` and `vlm` backends. Built on vlm, it integrates some capabilities of pipeline, adding extra extensibility on top of high accuracy:
|
||||
- Directly extracts text from text PDFs, natively supports multi-language recognition in text PDF scenarios, and greatly reduces parsing hallucinations;
|
||||
- Supports text recognition in 109 languages for scanned PDF scenarios by specifying OCR language;
|
||||
- Independent inline formula recognition switch, which can be disabled separately when inline formula recognition is not needed, improving the visual effect of parsing results.
|
||||
- Simplified engine selection logic for `vlm/hybrid` backends. Users only need to specify the backend as `*-auto-engine`, and the system will automatically select the appropriate engine for inference acceleration based on the current environment, improving usability.
|
||||
- Switched default parsing backend from `pipeline` to `hybrid-auto-engine`, improving out-of-the-box result consistency for new users and avoiding cognitive differences in parsing results.
|
||||
- Added i18n support to gradio application, supporting switching between Chinese and English languages.
|
||||
|
||||
> 📝 View the complete [Changelog](https://opendatalab.github.io/MinerU/reference/changelog/) for more historical version information
|
||||
|
||||
# MinerU
|
||||
|
||||
## Project Introduction
|
||||
|
||||
MinerU is a tool that converts PDFs into machine-readable formats (e.g., markdown, JSON), allowing for easy extraction into any format.
|
||||
MinerU was born during the pre-training process of [InternLM](https://github.com/InternLM/InternLM). We focus on solving symbol conversion issues in scientific literature and hope to contribute to technological development in the era of large models.
|
||||
Compared to well-known commercial products, MinerU is still young. If you encounter any issues or if the results are not as expected, please submit an issue on [issue](https://github.com/opendatalab/MinerU/issues) and **attach the relevant PDF**.
|
||||
|
||||
https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c
|
||||
|
||||
## Key Features
|
||||
|
||||
- Remove headers, footers, footnotes, page numbers, etc., to ensure semantic coherence.
|
||||
- Output text in human-readable order, suitable for single-column, multi-column, and complex layouts.
|
||||
- Preserve the structure of the original document, including headings, paragraphs, lists, etc.
|
||||
- Extract images, image descriptions, tables, table titles, and footnotes.
|
||||
- Automatically recognize and convert formulas in the document to LaTeX format.
|
||||
- Automatically recognize and convert tables in the document to HTML format.
|
||||
- Automatically detect scanned PDFs and garbled PDFs and enable OCR functionality.
|
||||
- OCR supports detection and recognition of 109 languages.
|
||||
- Supports multiple output formats, such as multimodal and NLP Markdown, JSON sorted by reading order, and rich intermediate formats.
|
||||
- Supports various visualization results, including layout visualization and span visualization, for efficient confirmation of output quality.
|
||||
- Supports running in a pure CPU environment, and also supports GPU(CUDA)/NPU(CANN)/MPS acceleration
|
||||
- Compatible with Windows, Linux, and Mac platforms.
|
||||
|
||||
# Quick Start
|
||||
|
||||
If you encounter any installation issues, please first consult the <a href="#faq">FAQ</a>. </br>
|
||||
If the parsing results are not as expected, refer to the <a href="#known-issues">Known Issues</a>. </br>
|
||||
|
||||
## Online Experience
|
||||
|
||||
### Official online web application
|
||||
The official online version has the same functionality as the client, with a beautiful interface and rich features, requires login to use
|
||||
|
||||
- [](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
|
||||
### Gradio-based online demo
|
||||
A WebUI developed based on Gradio, with a simple interface and only core parsing functionality, no login required
|
||||
|
||||
- [](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
- [](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
|
||||
## Local Deployment
|
||||
|
||||
|
||||
> [!WARNING]
|
||||
> **Pre-installation Notice—Hardware and Software Environment Support**
|
||||
>
|
||||
> To ensure the stability and reliability of the project, we only optimize and test for specific hardware and software environments during development. This ensures that users deploying and running the project on recommended system configurations will get the best performance with the fewest compatibility issues.
|
||||
>
|
||||
> By focusing resources on the mainline environment, our team can more efficiently resolve potential bugs and develop new features.
|
||||
>
|
||||
> In non-mainline environments, due to the diversity of hardware and software configurations, as well as third-party dependency compatibility issues, we cannot guarantee 100% project availability. Therefore, for users who wish to use this project in non-recommended environments, we suggest carefully reading the documentation and FAQ first. Most issues already have corresponding solutions in the FAQ. We also encourage community feedback to help us gradually expand support.
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th rowspan="2">Parsing Backend</th>
|
||||
<th rowspan="2">pipeline</th>
|
||||
<th colspan="2">*-auto-engine</th>
|
||||
<th colspan="2">*-http-client</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>hybrid</th>
|
||||
<th>vlm</th>
|
||||
<th>hybrid</th>
|
||||
<th>vlm</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Backend Features</th>
|
||||
<td >Good Compatibility</td>
|
||||
<td colspan="2">High Hardware Requirements</td>
|
||||
<td colspan="2">For OpenAI Compatible Servers<sup>2</sup></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Accuracy<sup>1</sup></th>
|
||||
<td style="text-align:center;">82+</td>
|
||||
<td colspan="4" style="text-align:center;">90+</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Operating System</th>
|
||||
<td colspan="5" style="text-align:center;">Linux<sup>3</sup> / Windows<sup>4</sup> / macOS<sup>5</sup></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Pure CPU Support</th>
|
||||
<td style="text-align:center;">✅</td>
|
||||
<td colspan="2" style="text-align:center;">❌</td>
|
||||
<td colspan="2" style="text-align:center;">✅</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>GPU Acceleration</th>
|
||||
<td colspan="4" style="text-align:center;">Volta and later architecture GPUs or Apple Silicon</td>
|
||||
<td rowspan="2">Not Required</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Min VRAM</th>
|
||||
<td style="text-align:center;">6GB</td>
|
||||
<td style="text-align:center;">10GB</td>
|
||||
<td style="text-align:center;">8GB</td>
|
||||
<td style="text-align:center;">3GB</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>RAM</th>
|
||||
<td colspan="3" style="text-align:center;">Min 16GB, Recommended 32GB or more</td>
|
||||
<td colspan="2" style="text-align:center;">Min 8GB</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Disk Space</th>
|
||||
<td colspan="3" style="text-align:center;">Min 20GB, SSD Recommended</td>
|
||||
<td colspan="2" style="text-align:center;">Min 2GB</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Python Version</th>
|
||||
<td colspan="5" style="text-align:center;">3.10-3.13</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<sup>1</sup> Accuracy metrics are the End-to-End Evaluation Overall scores from OmniDocBench (v1.5), based on the latest version of `MinerU`.
|
||||
<sup>2</sup> Servers compatible with OpenAI API, such as local model servers or remote model services deployed via inference frameworks like `vLLM`/`SGLang`/`LMDeploy`.
|
||||
<sup>3</sup> Linux only supports distributions from 2019 and later.
|
||||
<sup>4</sup> Since the key dependency `ray` does not support Python 3.13 on Windows, only versions 3.10~3.12 are supported.
|
||||
<sup>5</sup> macOS requires version 14.0 or later.
|
||||
|
||||
|
||||
### Install MinerU
|
||||
|
||||
#### Install MinerU using pip or uv
|
||||
```bash
|
||||
pip install --upgrade pip
|
||||
pip install uv
|
||||
uv pip install -U "mineru[all]"
|
||||
```
|
||||
|
||||
#### Install MinerU from source code
|
||||
```bash
|
||||
git clone https://github.com/opendatalab/MinerU.git
|
||||
cd MinerU
|
||||
uv pip install -e .[all]
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> `mineru[all]` includes all core features, compatible with Windows / Linux / macOS systems, suitable for most users.
|
||||
> If you need to specify the inference framework for the VLM model, or only intend to install a lightweight client on an edge device, please refer to the documentation [Extension Modules Installation Guide](https://opendatalab.github.io/MinerU/quick_start/extension_modules/).
|
||||
|
||||
---
|
||||
|
||||
#### Deploy MinerU using Docker
|
||||
MinerU provides a convenient Docker deployment method, which helps quickly set up the environment and solve some tricky environment compatibility issues.
|
||||
You can get the [Docker Deployment Instructions](https://opendatalab.github.io/MinerU/quick_start/docker_deployment/) in the documentation.
|
||||
|
||||
---
|
||||
|
||||
### Using MinerU
|
||||
|
||||
|
||||
If your device meets the GPU acceleration requirements in the table above, you can use a simple command line for document parsing:
|
||||
```bash
|
||||
mineru -p <input_path> -o <output_path>
|
||||
```
|
||||
If your device does not meet the GPU acceleration requirements, you can specify the backend as `pipeline` to run in a pure CPU environment:
|
||||
```bash
|
||||
mineru -p <input_path> -o <output_path> -b pipeline
|
||||
```
|
||||
|
||||
You can use MinerU for PDF parsing through various methods such as command line, API, and WebUI. For detailed instructions, please refer to the [Usage Guide](https://opendatalab.github.io/MinerU/usage/).
|
||||
|
||||
# TODO
|
||||
|
||||
- [x] Reading order based on the model
|
||||
- [x] Recognition of `index` and `list` in the main text
|
||||
- [x] Table recognition
|
||||
- [x] Heading Classification
|
||||
- [x] Handwritten Text Recognition
|
||||
- [x] Vertical Text Recognition
|
||||
- [x] Latin Accent Mark Recognition
|
||||
- [x] Code block recognition in the main text
|
||||
- [x] [Chemical formula recognition](docs/chemical_knowledge_introduction/introduction.pdf)(mineru.net)
|
||||
- [ ] Geometric shape recognition
|
||||
|
||||
# Known Issues
|
||||
|
||||
- Reading order is determined by the model based on the spatial distribution of readable content, and may be out of order in some areas under extremely complex layouts.
|
||||
- Limited support for vertical text.
|
||||
- Tables of contents and lists are recognized through rules, and some uncommon list formats may not be recognized.
|
||||
- Code blocks are not yet supported in the layout model.
|
||||
- Comic books, art albums, primary school textbooks, and exercises cannot be parsed well.
|
||||
- Table recognition may result in row/column recognition errors in complex tables.
|
||||
- OCR recognition may produce inaccurate characters in PDFs of lesser-known languages (e.g., diacritical marks in Latin script, easily confused characters in Arabic script).
|
||||
- Some formulas may not render correctly in Markdown.
|
||||
|
||||
# FAQ
|
||||
|
||||
- If you encounter any issues during usage, you can first check the [FAQ](https://opendatalab.github.io/MinerU/faq/) for solutions.
|
||||
- If your issue remains unresolved, you may also use [DeepWiki](https://deepwiki.com/opendatalab/MinerU) to interact with an AI assistant, which can address most common problems.
|
||||
- If you still cannot resolve the issue, you are welcome to join our community via [Discord](https://discord.gg/Tdedn9GTXq) or [WeChat](https://mineru.net/community-portal/?aliasId=3c430f94) to discuss with other users and developers.
|
||||
|
||||
# All Thanks To Our Contributors
|
||||
|
||||
<a href="https://github.com/opendatalab/MinerU/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=opendatalab/MinerU" />
|
||||
</a>
|
||||
|
||||
# License Information
|
||||
|
||||
[LICENSE.md](LICENSE.md)
|
||||
|
||||
Currently, some models in this project are trained based on YOLO. However, since YOLO follows the AGPL license, it may impose restrictions on certain use cases. In future iterations, we plan to explore and replace these with models under more permissive licenses to enhance user-friendliness and flexibility.
|
||||
|
||||
# Acknowledgments
|
||||
|
||||
- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)
|
||||
- [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
||||
- [UniMERNet](https://github.com/opendatalab/UniMERNet)
|
||||
- [RapidTable](https://github.com/RapidAI/RapidTable)
|
||||
- [TableStructureRec](https://github.com/RapidAI/TableStructureRec)
|
||||
- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)
|
||||
- [PaddleOCR2Pytorch](https://github.com/frotms/PaddleOCR2Pytorch)
|
||||
- [layoutreader](https://github.com/ppaanngggg/layoutreader)
|
||||
- [xy-cut](https://github.com/Sanster/xy-cut)
|
||||
- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)
|
||||
- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)
|
||||
- [pdftext](https://github.com/datalab-to/pdftext)
|
||||
- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
||||
- [pypdf](https://github.com/py-pdf/pypdf)
|
||||
- [magika](https://github.com/google/magika)
|
||||
- [vLLM](https://github.com/vllm-project/vllm)
|
||||
- [LMDeploy](https://github.com/InternLM/lmdeploy)
|
||||
|
||||
# Citation
|
||||
|
||||
```bibtex
|
||||
@misc{niu2025mineru25decoupledvisionlanguagemodel,
|
||||
title={MinerU2.5: A Decoupled Vision-Language Model for Efficient High-Resolution Document Parsing},
|
||||
author={Junbo Niu and Zheng Liu and Zhuangcheng Gu and Bin Wang and Linke Ouyang and Zhiyuan Zhao and Tao Chu and Tianyao He and Fan Wu and Qintong Zhang and Zhenjiang Jin and Guang Liang and Rui Zhang and Wenzheng Zhang and Yuan Qu and Zhifei Ren and Yuefeng Sun and Yuanhong Zheng and Dongsheng Ma and Zirui Tang and Boyu Niu and Ziyang Miao and Hejun Dong and Siyi Qian and Junyuan Zhang and Jingzhou Chen and Fangdong Wang and Xiaomeng Zhao and Liqun Wei and Wei Li and Shasha Wang and Ruiliang Xu and Yuanyuan Cao and Lu Chen and Qianqian Wu and Huaiyu Gu and Lindong Lu and Keming Wang and Dechen Lin and Guanlin Shen and Xuanhe Zhou and Linfeng Zhang and Yuhang Zang and Xiaoyi Dong and Jiaqi Wang and Bo Zhang and Lei Bai and Pei Chu and Weijia Li and Jiang Wu and Lijun Wu and Zhenxiang Li and Guangyu Wang and Zhongying Tu and Chao Xu and Kai Chen and Yu Qiao and Bowen Zhou and Dahua Lin and Wentao Zhang and Conghui He},
|
||||
year={2025},
|
||||
eprint={2509.22186},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CV},
|
||||
url={https://arxiv.org/abs/2509.22186},
|
||||
}
|
||||
|
||||
@misc{wang2024mineruopensourcesolutionprecise,
|
||||
title={MinerU: An Open-Source Solution for Precise Document Content Extraction},
|
||||
author={Bin Wang and Chao Xu and Xiaomeng Zhao and Linke Ouyang and Fan Wu and Zhiyuan Zhao and Rui Xu and Kaiwen Liu and Yuan Qu and Fukai Shang and Bo Zhang and Liqun Wei and Zhihao Sui and Wei Li and Botian Shi and Yu Qiao and Dahua Lin and Conghui He},
|
||||
year={2024},
|
||||
eprint={2409.18839},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CV},
|
||||
url={https://arxiv.org/abs/2409.18839},
|
||||
}
|
||||
|
||||
@article{he2024opendatalab,
|
||||
title={Opendatalab: Empowering general artificial intelligence with open datasets},
|
||||
author={He, Conghui and Li, Wei and Jin, Zhenjiang and Xu, Chao and Wang, Bin and Lin, Dahua},
|
||||
journal={arXiv preprint arXiv:2407.13773},
|
||||
year={2024}
|
||||
}
|
||||
```
|
||||
|
||||
# Star History
|
||||
|
||||
<a>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
|
||||
# Links
|
||||
- [Easy Data Preparation with latest LLMs-based Operators and Pipelines](https://github.com/OpenDCAI/DataFlow)
|
||||
- [Vis3 (OSS browser based on s3)](https://github.com/opendatalab/Vis3)
|
||||
- [LabelU (A Lightweight Multi-modal Data Annotation Tool)](https://github.com/opendatalab/labelU)
|
||||
- [LabelLLM (An Open-source LLM Dialogue Annotation Platform)](https://github.com/opendatalab/LabelLLM)
|
||||
- [PDF-Extract-Kit (A Comprehensive Toolkit for High-Quality PDF Content Extraction)](https://github.com/opendatalab/PDF-Extract-Kit)
|
||||
- [OmniDocBench (A Comprehensive Benchmark for Document Parsing and Evaluation)](https://github.com/opendatalab/OmniDocBench)
|
||||
- [Magic-HTML (Mixed web page extraction tool)](https://github.com/opendatalab/magic-html)
|
||||
- [Magic-Doc (Fast speed ppt/pptx/doc/docx/pdf extraction tool)](https://github.com/InternLM/magic-doc)
|
||||
- [Dingo: A Comprehensive AI Data Quality Evaluation Tool](https://github.com/MigoXLab/dingo)
|
||||
|
|
@ -1,108 +1,14 @@
|
|||
# ==========================================
|
||||
# 阶段 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)
|
||||
# ==========================================
|
||||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
|
||||
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 MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
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"]
|
||||
COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./
|
||||
COPY mineru ./mineru
|
||||
COPY scripts/run_parser.py ./scripts/run_parser.py
|
||||
# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch.
|
||||
RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision','vllm')))" \
|
||||
&& python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]'
|
||||
COPY docker/entrypoint.mineru-api.sh /entrypoint.sh
|
||||
ENTRYPOINT ["sh", "/entrypoint.sh"]
|
||||
CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -1,65 +1,14 @@
|
|||
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10
|
||||
|
||||
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 MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
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"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./
|
||||
COPY mineru ./mineru
|
||||
COPY scripts/run_parser.py ./scripts/run_parser.py
|
||||
# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch.
|
||||
RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision','vllm')))" \
|
||||
&& python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]'
|
||||
COPY docker/entrypoint.mineru-api.sh /entrypoint.sh
|
||||
ENTRYPOINT ["sh", "/entrypoint.sh"]
|
||||
CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -1,87 +1,16 @@
|
|||
services:
|
||||
mineru-openai-server:
|
||||
image: mineru:latest
|
||||
container_name: mineru-openai-server
|
||||
restart: always
|
||||
profiles: ["openai-server"]
|
||||
ports:
|
||||
- 30000:30000
|
||||
environment:
|
||||
MINERU_MODEL_SOURCE: local
|
||||
entrypoint: mineru-openai-server
|
||||
command:
|
||||
--host 0.0.0.0
|
||||
--port 30000
|
||||
# --data-parallel-size 2 # If using multiple GPUs, increase throughput using vllm's multi-GPU parallel mode
|
||||
# --gpu-memory-utilization 0.5 # If running on a single GPU and encountering VRAM shortage, reduce the KV cache size by this parameter, if VRAM issues persist, try lowering it further to `0.4` or below.
|
||||
ulimits:
|
||||
memlock: -1
|
||||
stack: 67108864
|
||||
ipc: host
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:30000/health || exit 1"]
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
device_ids: ["0"] # Modify for multiple GPUs: ["0", "1"]
|
||||
capabilities: [gpu]
|
||||
|
||||
mineru-api:
|
||||
image: mineru:latest
|
||||
container_name: mineru-api
|
||||
restart: always
|
||||
profiles: ["api"]
|
||||
image: unis-mineru:2.7.4
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- 8000:8000
|
||||
- "127.0.0.1:${MINERU_PORT:-8100}:8000"
|
||||
environment:
|
||||
MINERU_MODEL_SOURCE: local
|
||||
entrypoint: mineru-api
|
||||
command:
|
||||
--host 0.0.0.0
|
||||
--port 8000
|
||||
# parameters for vllm-engine
|
||||
# --data-parallel-size 2 # If using multiple GPUs, increase throughput using vllm's multi-GPU parallel mode
|
||||
# --gpu-memory-utilization 0.5 # If running on a single GPU and encountering VRAM shortage, reduce the KV cache size by this parameter, if VRAM issues persist, try lowering it further to `0.4` or below.
|
||||
ulimits:
|
||||
memlock: -1
|
||||
stack: 67108864
|
||||
ipc: host
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
device_ids: ["0"] # Modify for multiple GPUs: ["0", "1"]
|
||||
capabilities: [gpu]
|
||||
|
||||
mineru-gradio:
|
||||
image: mineru:latest
|
||||
container_name: mineru-gradio
|
||||
restart: always
|
||||
profiles: ["gradio"]
|
||||
ports:
|
||||
- 7860:7860
|
||||
environment:
|
||||
MINERU_MODEL_SOURCE: local
|
||||
entrypoint: mineru-gradio
|
||||
command:
|
||||
--server-name 0.0.0.0
|
||||
--server-port 7860
|
||||
# --enable-api false # If you want to disable the API, set this to false
|
||||
# --max-convert-pages 20 # If you want to limit the number of pages for conversion, set this to a specific number
|
||||
# parameters for vllm-engine
|
||||
# --data-parallel-size 2 # If using multiple GPUs, increase throughput using vllm's multi-GPU parallel mode
|
||||
# --gpu-memory-utilization 0.5 # If running on a single GPU and encountering VRAM shortage, reduce the KV cache size by this parameter, if VRAM issues persist, try lowering it further to `0.4` or below.
|
||||
ulimits:
|
||||
memlock: -1
|
||||
stack: 67108864
|
||||
ipc: host
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
device_ids: ["0"] # Modify for multiple GPUs: ["0", "1"]
|
||||
capabilities: [gpu]
|
||||
MINERU_MODEL_DIR: /models
|
||||
MINERU_GPU_MEMORY_UTILIZATION: ${MINERU_GPU_MEMORY_UTILIZATION:-0.5}
|
||||
volumes:
|
||||
- "${MINERU_MODEL_DIR:?Set MINERU_MODEL_DIR}:/models:ro"
|
||||
- mineru-output:/app/output
|
||||
command: ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"]
|
||||
volumes:
|
||||
mineru-output:
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ 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")"
|
||||
mkdir -p "$(dirname "$CONFIG_PATH")"
|
||||
|
||||
export CONFIG_PATH PIPELINE_MODEL_DIR VLM_MODEL_DIR
|
||||
|
||||
if [ ! -f "$CONFIG_PATH" ]; then
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import os
|
||||
|
|
@ -39,6 +40,7 @@ config = {
|
|||
}
|
||||
config_path.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
PY
|
||||
fi
|
||||
|
||||
export MINERU_TOOLS_CONFIG_JSON="$CONFIG_PATH"
|
||||
export MINERU_MODEL_SOURCE=${MINERU_MODEL_SOURCE:-local}
|
||||
|
|
|
|||
|
|
@ -1,39 +1,14 @@
|
|||
# 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
|
||||
|
||||
# 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 \"$@\"", "--"]
|
||||
FROM pytorch/pytorch:2.7.1-cuda12.6-cudnn9-runtime
|
||||
ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./
|
||||
COPY mineru ./mineru
|
||||
COPY scripts/run_parser.py ./scripts/run_parser.py
|
||||
# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch.
|
||||
RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision')))" \
|
||||
&& python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]'
|
||||
COPY docker/entrypoint.mineru-api.sh /entrypoint.sh
|
||||
ENTRYPOINT ["sh", "/entrypoint.sh"]
|
||||
CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -1,67 +1,14 @@
|
|||
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
|
||||
|
||||
ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
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"]
|
||||
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]
|
||||
COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./
|
||||
COPY mineru ./mineru
|
||||
COPY scripts/run_parser.py ./scripts/run_parser.py
|
||||
# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch.
|
||||
RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision')))" \
|
||||
&& python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]'
|
||||
COPY docker/entrypoint.mineru-api.sh /entrypoint.sh
|
||||
ENTRYPOINT ["sh", "/entrypoint.sh"]
|
||||
CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"baseline": "PyPI mineru==2.7.4",
|
||||
"url": "https://files.pythonhosted.org/packages/af/e4/60bbe4af8f4f7fa1cef4fd25e6adfb44589172830ab246a673398651f520/mineru-2.7.4-py3-none-any.whl",
|
||||
"sha256": "e802a59352e4e5ea7782a903c35053581c3539f55a0ebaa95d9afd473bc757bc",
|
||||
"files": 187
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
> 状态更新:下文为历史差异盘点,4.0.12 合并方案已被替代。当前固定官方 2.7.4,业务功能迁入 MaxKB,参见仓库 README。
|
||||
|
||||
# MinerU 2.7.1 定制盘点与 4.0.12 合并方案
|
||||
|
||||
核验日期:2026-10-22。此次完成源码与发布包对比,尚未替换旧内核、安装新依赖或切换运行服务。
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -18,6 +18,12 @@ 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"
|
||||
else:
|
||||
logger.info("CUDA not available, disabling custom_logits_processors")
|
||||
return False
|
||||
|
|
@ -71,16 +77,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)
|
||||
|
|
@ -106,4 +102,4 @@ def set_default_batch_size() -> int:
|
|||
except Exception as e:
|
||||
logger.warning(f'Error determining VRAM: {e}, using default batch_ratio: 1')
|
||||
batch_size = 1
|
||||
return batch_size
|
||||
return batch_size
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
# Copyright (c) Opendatalab. All rights reserved.
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
|
||||
from loguru import logger
|
||||
|
||||
|
|
@ -99,6 +100,37 @@ class ModelSingleton:
|
|||
import vllm
|
||||
except ImportError:
|
||||
raise ImportError("Please install vllm to use the vllm-engine backend.")
|
||||
|
||||
# musa vllm v1 引擎特殊配置
|
||||
# device = get_device()
|
||||
# if device_type.startswith("musa"):
|
||||
# import torch
|
||||
# if torch.musa.is_available():
|
||||
# compilation_config = {
|
||||
# "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
|
||||
# kwargs["compilation_config"] = compilation_config
|
||||
# kwargs["block_size"] = block_size
|
||||
|
||||
# corex vllm v1 引擎特殊配置
|
||||
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
|
||||
if device_type.lower() == "corex":
|
||||
compilation_config = {
|
||||
"cudagraph_mode": "FULL_DECODE_ONLY",
|
||||
"level": 0
|
||||
}
|
||||
kwargs["compilation_config"] = compilation_config
|
||||
|
||||
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 +142,48 @@ 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.")
|
||||
|
||||
|
||||
# musa vllm v1 引擎特殊配置
|
||||
# device = get_device()
|
||||
# if device.startswith("musa"):
|
||||
# import torch
|
||||
# if torch.musa.is_available():
|
||||
# compilation_config = CompilationConfig(
|
||||
# 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
|
||||
# kwargs["compilation_config"] = compilation_config
|
||||
# kwargs["block_size"] = block_size
|
||||
|
||||
# corex vllm v1 引擎特殊配置
|
||||
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
|
||||
if device_type.lower() == "corex":
|
||||
compilation_config = CompilationConfig(
|
||||
cudagraph_mode="FULL_DECODE_ONLY",
|
||||
level=0
|
||||
)
|
||||
kwargs["compilation_config"] = compilation_config
|
||||
|
||||
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 +192,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
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@ if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":
|
|||
|
||||
pdf_suffixes = ["pdf"]
|
||||
image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"]
|
||||
word_suffixes = ["docx", "doc"]
|
||||
|
||||
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
||||
|
||||
|
|
@ -40,109 +39,6 @@ def read_fn(path):
|
|||
return images_bytes_to_pdf_bytes(file_bytes)
|
||||
elif file_suffix in pdf_suffixes:
|
||||
return file_bytes
|
||||
elif file_suffix in word_suffixes:
|
||||
# 处理 Word 文件,转换为 PDF(保持原格式)
|
||||
from io import BytesIO
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
try:
|
||||
# 方法 1: 使用 LibreOffice 进行高质量转换(推荐)
|
||||
# 创建临时文件
|
||||
with tempfile.NamedTemporaryFile(suffix=f'.{file_suffix}', delete=False) as temp_word:
|
||||
temp_word.write(file_bytes)
|
||||
temp_word_path = temp_word.name
|
||||
|
||||
pdf_fd, pdf_path = tempfile.mkstemp(suffix='.pdf')
|
||||
os.close(pdf_fd)
|
||||
|
||||
try:
|
||||
# 使用 LibreOffice 进行转换(保持原格式,包括图片、表格等)
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
[
|
||||
'libreoffice', '--headless', '--convert-to', 'pdf',
|
||||
'--outdir', os.path.dirname(pdf_path),
|
||||
temp_word_path
|
||||
],
|
||||
capture_output=True,
|
||||
timeout=120
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
# LibreOffice 会在同目录下生成 PDF
|
||||
base_name = os.path.basename(temp_word_path).rsplit('.', 1)[0]
|
||||
generated_pdf = os.path.join(os.path.dirname(temp_word_path), f"{base_name}.pdf")
|
||||
|
||||
if os.path.exists(generated_pdf):
|
||||
with open(generated_pdf, 'rb') as f:
|
||||
pdf_bytes_result = f.read()
|
||||
os.remove(generated_pdf)
|
||||
os.remove(temp_word_path)
|
||||
return pdf_bytes_result
|
||||
|
||||
logger.warning(f"LibreOffice conversion failed: {result.stderr}")
|
||||
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError) as libreoffice_error:
|
||||
logger.warning(f"LibreOffice not available or failed: {libreoffice_error}")
|
||||
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_word_path):
|
||||
os.remove(temp_word_path)
|
||||
if os.path.exists(pdf_path):
|
||||
os.remove(pdf_path)
|
||||
|
||||
# 方法 2: 如果 LibreOffice 不可用,使用 python-docx + reportlab 作为备选
|
||||
if file_suffix == "docx":
|
||||
from docx import Document
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
# 读取 Word 文件
|
||||
doc = Document(BytesIO(file_bytes))
|
||||
|
||||
# 创建 PDF(简单文本转换,不保留复杂格式)
|
||||
output = BytesIO()
|
||||
c = canvas.Canvas(output, pagesize=letter)
|
||||
width, height = letter
|
||||
|
||||
y = height - 50
|
||||
for para in doc.paragraphs:
|
||||
text = para.text
|
||||
if text:
|
||||
# 处理长文本自动换行
|
||||
max_width = width - 100
|
||||
words = text.split(' ')
|
||||
line = ''
|
||||
for word in words:
|
||||
test_line = f"{line} {word}".strip()
|
||||
if c.stringWidth(test_line, 'Helvetica', 12) < max_width:
|
||||
line = test_line
|
||||
else:
|
||||
if y < 50:
|
||||
c.showPage()
|
||||
y = height - 50
|
||||
c.drawString(50, y, line)
|
||||
y -= 15
|
||||
line = word
|
||||
|
||||
# 写入最后一行
|
||||
if y < 50:
|
||||
c.showPage()
|
||||
y = height - 50
|
||||
c.drawString(50, y, line)
|
||||
y -= 15
|
||||
|
||||
c.save()
|
||||
output.seek(0)
|
||||
return output.read()
|
||||
|
||||
raise Exception("Word to PDF conversion failed with all methods")
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error converting Word file to PDF: {e}")
|
||||
raise Exception(f"Failed to convert Word file to PDF: {str(e)}. Please install LibreOffice for better conversion: sudo apt-get install libreoffice")
|
||||
else:
|
||||
raise Exception(f"Unknown file suffix: {file_suffix}")
|
||||
|
||||
|
|
@ -341,7 +237,6 @@ async def _async_process_vlm(
|
|||
f_dump_content_list,
|
||||
f_make_md_mode,
|
||||
server_url=None,
|
||||
progress_callback=None,
|
||||
**kwargs,
|
||||
):
|
||||
"""异步处理VLM后端逻辑"""
|
||||
|
|
@ -350,23 +245,14 @@ async def _async_process_vlm(
|
|||
if not backend.endswith("client"):
|
||||
server_url = None
|
||||
|
||||
total_files = len(pdf_bytes_list)
|
||||
for idx, pdf_bytes in enumerate(pdf_bytes_list):
|
||||
pdf_file_name = pdf_file_names[idx]
|
||||
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
|
||||
image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
|
||||
|
||||
# 更新进度
|
||||
if progress_callback:
|
||||
progress_callback((idx / total_files) * 50, f"处理文件 {idx+1}/{total_files}")
|
||||
|
||||
middle_json, infer_result = await aio_vlm_doc_analyze(
|
||||
pdf_bytes, image_writer=image_writer, backend=backend, server_url=server_url, **kwargs,
|
||||
)
|
||||
|
||||
# 更新进度
|
||||
if progress_callback:
|
||||
progress_callback(((idx + 1) / total_files) * 100, f"完成文件 {idx+1}/{total_files}")
|
||||
|
||||
pdf_info = middle_json["pdf_info"]
|
||||
|
||||
|
|
@ -489,7 +375,6 @@ async def _async_process_hybrid(
|
|||
f_dump_content_list,
|
||||
f_make_md_mode,
|
||||
server_url=None,
|
||||
progress_callback=None,
|
||||
**kwargs,
|
||||
):
|
||||
from mineru.backend.hybrid.hybrid_analyze import aio_doc_analyze as aio_hybrid_doc_analyze
|
||||
|
|
@ -497,15 +382,10 @@ async def _async_process_hybrid(
|
|||
if not backend.endswith("client"):
|
||||
server_url = None
|
||||
|
||||
total_files = len(pdf_bytes_list)
|
||||
for idx, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, h_lang_list)):
|
||||
pdf_file_name = pdf_file_names[idx]
|
||||
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")
|
||||
image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
|
||||
|
||||
# 更新进度
|
||||
if progress_callback:
|
||||
progress_callback((idx / total_files) * 50, f"处理文件 {idx+1}/{total_files}")
|
||||
|
||||
middle_json, infer_result, _vlm_ocr_enable = await aio_hybrid_doc_analyze(
|
||||
pdf_bytes,
|
||||
|
|
@ -517,10 +397,6 @@ async def _async_process_hybrid(
|
|||
server_url=server_url,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# 更新进度
|
||||
if progress_callback:
|
||||
progress_callback(((idx + 1) / total_files) * 100, f"完成文件 {idx+1}/{total_files}")
|
||||
|
||||
pdf_info = middle_json["pdf_info"]
|
||||
|
||||
|
|
@ -627,7 +503,6 @@ async def aio_do_parse(
|
|||
f_make_md_mode=MakeMode.MM_MD,
|
||||
start_page_id=0,
|
||||
end_page_id=None,
|
||||
progress_callback=None,
|
||||
**kwargs,
|
||||
):
|
||||
# 预处理PDF字节数据
|
||||
|
|
@ -654,12 +529,11 @@ async def aio_do_parse(
|
|||
os.environ['MINERU_VLM_FORMULA_ENABLE'] = str(formula_enable)
|
||||
os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
|
||||
|
||||
# 传递进度回调
|
||||
await _async_process_vlm(
|
||||
output_dir, pdf_file_names, pdf_bytes_list, backend,
|
||||
f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
|
||||
f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
|
||||
server_url, progress_callback=progress_callback, **kwargs,
|
||||
server_url, **kwargs,
|
||||
)
|
||||
elif backend.startswith("hybrid-"):
|
||||
backend = backend[7:]
|
||||
|
|
@ -673,12 +547,11 @@ async def aio_do_parse(
|
|||
os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
|
||||
os.environ['MINERU_VLM_FORMULA_ENABLE'] = "true"
|
||||
|
||||
# 传递进度回调
|
||||
await _async_process_hybrid(
|
||||
output_dir, pdf_file_names, pdf_bytes_list, p_lang_list, parse_method, formula_enable, backend,
|
||||
f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
|
||||
f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
|
||||
server_url, progress_callback=progress_callback, **kwargs,
|
||||
server_url, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -23,143 +23,26 @@ from mineru.utils.engine_utils import get_vlm_engine
|
|||
from mineru.utils.hash_utils import str_sha256
|
||||
|
||||
|
||||
# --- 新增:标准的树状思维导图生成函数 ---
|
||||
def md_to_markmap_html(md_content):
|
||||
"""
|
||||
将 Markdown 转换为标准的树状思维导图 (Markmap)
|
||||
"""
|
||||
if not md_content:
|
||||
return ""
|
||||
|
||||
# 转义 Markdown 中的反引号和符号,防止破坏 JS 字符串
|
||||
safe_md = md_content.replace('`', '\\`').replace('$', '\\$')
|
||||
|
||||
# 完整的 HTML + Markmap 渲染引擎
|
||||
full_html = f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
html, body, #mindmap {{ width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; background-color: white; }}
|
||||
</style>
|
||||
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/markmap-view"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/markmap-toolbar"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/markmap-lib"></script>
|
||||
</head>
|
||||
<body>
|
||||
<svg id="mindmap"></svg>
|
||||
<script>
|
||||
// 等待页面完全加载后再初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {{
|
||||
try {{
|
||||
const {{ Markmap, loadCSS, loadJS, Transformer }} = window.markmap;
|
||||
const transformer = new Transformer();
|
||||
const {{ root, features }} = transformer.transform(`{safe_md}`);
|
||||
const {{ styles, scripts }} = transformer.getAssets();
|
||||
|
||||
if (styles) loadCSS(styles);
|
||||
if (scripts) loadJS(scripts);
|
||||
|
||||
// 增加延迟确保资源加载完成
|
||||
setTimeout(() => {{
|
||||
const mm = Markmap.create('#mindmap', {{
|
||||
autoFit: true,
|
||||
fitRatio: 0.9,
|
||||
initialExpandLevel: -1
|
||||
}}, root);
|
||||
|
||||
// 添加错误处理
|
||||
if (mm) {{
|
||||
console.log("Markmap created successfully");
|
||||
}} else {{
|
||||
console.error("Failed to create Markmap");
|
||||
}}
|
||||
}}, 500); // 延迟500毫秒以确保资源加载
|
||||
}} catch (error) {{
|
||||
console.error('Error initializing markmap:', error);
|
||||
}}
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# 使用 iframe 封装,彻底解决渲染失效问题
|
||||
iframe_srcdoc = full_html.replace('"', '"')
|
||||
iframe_code = f"""
|
||||
<iframe srcdoc="{iframe_srcdoc}" style="width: 100%; height: 800px; border: 1px solid #ddd; border-radius: 8px;" sandbox="allow-scripts"></iframe>
|
||||
"""
|
||||
return iframe_code
|
||||
|
||||
|
||||
# ────────────── 新增:根据上一级标题自动补全下一级标题 ──────────────
|
||||
def auto_promote_paragraphs_to_subheading(text):
|
||||
lines = text.splitlines()
|
||||
result = []
|
||||
in_section = False
|
||||
empty_count = 0
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
if stripped.startswith('# '):
|
||||
result.append(line)
|
||||
in_section = True
|
||||
empty_count = 0
|
||||
continue
|
||||
|
||||
if stripped.startswith('#'):
|
||||
result.append(line)
|
||||
in_section = False
|
||||
empty_count = 0
|
||||
continue
|
||||
|
||||
if not stripped:
|
||||
result.append(line)
|
||||
empty_count += 1
|
||||
if empty_count >= 2:
|
||||
in_section = False
|
||||
continue
|
||||
|
||||
# 跳过图片、列表、代码等特殊行
|
||||
if (
|
||||
stripped.startswith('![') or
|
||||
stripped.startswith('>') or
|
||||
stripped.startswith('```') or
|
||||
re.match(r'^[-*+] ', stripped) or
|
||||
re.match(r'^\d+\. ', stripped)
|
||||
):
|
||||
result.append(line)
|
||||
empty_count = 0
|
||||
continue
|
||||
|
||||
empty_count = 0
|
||||
if in_section:
|
||||
result.append('## ' + stripped)
|
||||
else:
|
||||
result.append(line)
|
||||
|
||||
return '\n'.join(result)
|
||||
|
||||
|
||||
async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language, backend, url):
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
try:
|
||||
file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
|
||||
pdf_data = read_fn(doc_path)
|
||||
# 根据 backend 确定 parse_method
|
||||
if backend.startswith("vlm"):
|
||||
parse_method = "vlm"
|
||||
else:
|
||||
parse_method = 'ocr' if is_ocr else 'auto'
|
||||
|
||||
# 根据 backend 类型准备环境目录
|
||||
if backend.startswith("hybrid"):
|
||||
env_name = f"hybrid_{parse_method}"
|
||||
else:
|
||||
env_name = parse_method
|
||||
|
||||
local_image_dir, local_md_dir = prepare_env(output_dir, file_name, env_name)
|
||||
|
||||
await aio_do_parse(
|
||||
output_dir=output_dir,
|
||||
pdf_file_names=[file_name],
|
||||
|
|
@ -179,12 +62,22 @@ async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, t
|
|||
|
||||
|
||||
def compress_directory_to_zip(directory_path, output_zip_path):
|
||||
"""压缩指定目录到一个 ZIP 文件。
|
||||
|
||||
:param directory_path: 要压缩的目录路径
|
||||
:param output_zip_path: 输出的 ZIP 文件路径
|
||||
"""
|
||||
try:
|
||||
with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
|
||||
# 遍历目录中的所有文件和子目录
|
||||
for root, dirs, files in os.walk(directory_path):
|
||||
for file in files:
|
||||
# 构建完整的文件路径
|
||||
file_path = os.path.join(root, file)
|
||||
# 计算相对路径
|
||||
arcname = os.path.relpath(file_path, directory_path)
|
||||
# 添加文件到 ZIP 文件
|
||||
zipf.write(file_path, arcname)
|
||||
return 0
|
||||
except Exception as e:
|
||||
|
|
@ -198,32 +91,31 @@ def image_to_base64(image_path):
|
|||
|
||||
|
||||
def replace_image_with_base64(markdown_text, image_dir_path):
|
||||
# 匹配Markdown中的图片标签
|
||||
pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
|
||||
|
||||
# 替换图片链接
|
||||
def replace(match):
|
||||
relative_path = match.group(1)
|
||||
# 只处理以.jpg结尾的图片
|
||||
if relative_path.endswith('.jpg'):
|
||||
full_path = os.path.join(image_dir_path, relative_path)
|
||||
base64_image = image_to_base64(full_path)
|
||||
return f''
|
||||
return match.group(0)
|
||||
|
||||
else:
|
||||
# 其他格式的图片保持原样
|
||||
return match.group(0)
|
||||
# 应用替换
|
||||
return re.sub(pattern, replace, markdown_text)
|
||||
|
||||
|
||||
async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch",
|
||||
backend="pipeline", url=None):
|
||||
async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch", backend="pipeline", url=None):
|
||||
# 如果language包含(),则提取括号前的内容作为实际语言
|
||||
if '(' in language and ')' in language:
|
||||
language = language.split('(')[0].strip()
|
||||
file_path = to_pdf(file_path)
|
||||
# 打印请求参数日志
|
||||
logger.info(f"parse_pdf 请求参数: file_path={file_path}, output_dir='./output', end_page_id={end_pages - 1}, "
|
||||
f"is_ocr={is_ocr}, formula_enable={formula_enable}, table_enable={table_enable}, "
|
||||
f"language='{language}', backend='{backend}', url={url}")
|
||||
# 获取识别的md文件以及压缩包文件路径
|
||||
local_md_dir, file_name = await parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable,
|
||||
table_enable, language, backend, url)
|
||||
local_md_dir, file_name = await parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)
|
||||
archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
|
||||
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
|
||||
if zip_archive_success == 0:
|
||||
|
|
@ -233,55 +125,74 @@ async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True
|
|||
md_path = os.path.join(local_md_dir, file_name + '.md')
|
||||
with open(md_path, 'r', encoding='utf-8') as f:
|
||||
txt_content = f.read()
|
||||
|
||||
# ────────────── 自动补全:根据 # 标题补全后续段落为 ## ──────────────
|
||||
txt_content = auto_promote_paragraphs_to_subheading(txt_content)
|
||||
# ────────────────────────────────────────────────────────────────
|
||||
|
||||
md_content = replace_image_with_base64(txt_content, local_md_dir)
|
||||
|
||||
# 生成思维导图HTML - 使用新的实现
|
||||
mind_map_html = md_to_markmap_html(txt_content)
|
||||
|
||||
# 返回转换后的PDF路径
|
||||
new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
|
||||
|
||||
return md_content, txt_content, archive_zip_path, new_pdf_path, mind_map_html
|
||||
return md_content, txt_content, archive_zip_path, new_pdf_path
|
||||
|
||||
|
||||
latex_delimiters_type_all = [
|
||||
{'left': '$$', 'right': '$$', 'display': True},
|
||||
{'left': '$', 'right': '$', 'display': False},
|
||||
{'left': '\\(', 'right': '\\)', 'display': False},
|
||||
{'left': '\\[', 'right': '\\]', 'display': True},
|
||||
]
|
||||
|
||||
latex_delimiters_type_a = [
|
||||
{'left': '$$', 'right': '$$', 'display': True},
|
||||
{'left': '$', 'right': '$', 'display': False},
|
||||
]
|
||||
|
||||
latex_delimiters_type_b = [
|
||||
{'left': '\\(', 'right': '\\)', 'display': False},
|
||||
{'left': '\\[', 'right': '\\]', 'display': True},
|
||||
]
|
||||
latex_delimiters_type_all = latex_delimiters_type_a + latex_delimiters_type_b
|
||||
|
||||
other_lang = ['ch (Chinese, English, Chinese Traditional)', 'en (English)', 'korean', 'japan']
|
||||
all_lang = [*other_lang]
|
||||
header_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'resources', 'header.html')
|
||||
with open(header_path, mode='r', encoding='utf-8') as header_file:
|
||||
header = header_file.read()
|
||||
|
||||
other_lang = [
|
||||
'ch (Chinese, English, Chinese Traditional)',
|
||||
'ch_lite (Chinese, English, Chinese Traditional, Japanese)',
|
||||
'ch_server (Chinese, English, Chinese Traditional, Japanese)',
|
||||
'en (English)',
|
||||
'korean (Korean, English)',
|
||||
'japan (Chinese, English, Chinese Traditional, Japanese)',
|
||||
'chinese_cht (Chinese, English, Chinese Traditional, Japanese)',
|
||||
'ta (Tamil, English)',
|
||||
'te (Telugu, English)',
|
||||
'ka (Kannada)',
|
||||
'el (Greek, English)',
|
||||
'th (Thai, English)'
|
||||
]
|
||||
add_lang = [
|
||||
'latin (French, German, Afrikaans, Italian, Spanish, Bosnian, Portuguese, Czech, Welsh, Danish, Estonian, Irish, Croatian, Uzbek, Hungarian, Serbian (Latin), Indonesian, Occitan, Icelandic, Lithuanian, Maori, Malay, Dutch, Norwegian, Polish, Slovak, Slovenian, Albanian, Swedish, Swahili, Tagalog, Turkish, Latin, Azerbaijani, Kurdish, Latvian, Maltese, Pali, Romanian, Vietnamese, Finnish, Basque, Galician, Luxembourgish, Romansh, Catalan, Quechua)',
|
||||
'arabic (Arabic, Persian, Uyghur, Urdu, Pashto, Kurdish, Sindhi, Balochi, English)',
|
||||
'east_slavic (Russian, Belarusian, Ukrainian, English)',
|
||||
'cyrillic (Russian, Belarusian, Ukrainian, Serbian (Cyrillic), Bulgarian, Mongolian, Abkhazian, Adyghe, Kabardian, Avar, Dargin, Ingush, Chechen, Lak, Lezgin, Tabasaran, Kazakh, Kyrgyz, Tajik, Macedonian, Tatar, Chuvash, Bashkir, Malian, Moldovan, Udmurt, Komi, Ossetian, Buryat, Kalmyk, Tuvan, Sakha, Karakalpak, English)',
|
||||
'devanagari (Hindi, Marathi, Nepali, Bihari, Maithili, Angika, Bhojpuri, Magahi, Santali, Newari, Konkani, Sanskrit, Haryanvi, English)'
|
||||
]
|
||||
all_lang = [*other_lang, *add_lang]
|
||||
|
||||
|
||||
def safe_stem(file_path):
|
||||
stem = Path(file_path).stem
|
||||
# 只保留字母、数字、下划线和点,其他字符替换为下划线
|
||||
return re.sub(r'[^\w.]', '_', stem)
|
||||
|
||||
|
||||
def to_pdf(file_path):
|
||||
if file_path is None: return None
|
||||
|
||||
if file_path is None:
|
||||
return None
|
||||
|
||||
pdf_bytes = read_fn(file_path)
|
||||
|
||||
# unique_filename = f'{uuid.uuid4()}.pdf'
|
||||
unique_filename = f'{safe_stem(file_path)}.pdf'
|
||||
|
||||
# 构建完整的文件路径
|
||||
tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
|
||||
|
||||
# 将字节数据写入文件
|
||||
with open(tmp_file_path, 'wb') as tmp_pdf_file:
|
||||
tmp_pdf_file.write(pdf_bytes)
|
||||
|
||||
return tmp_file_path
|
||||
|
||||
|
||||
|
|
@ -339,35 +250,13 @@ def to_pdf(file_path):
|
|||
default='all',
|
||||
)
|
||||
def main(ctx,
|
||||
example_enable,
|
||||
http_client_enable,
|
||||
api_enable, max_convert_pages,
|
||||
server_name, server_port, latex_delimiters_type, **kwargs
|
||||
):
|
||||
# 检测系统语言环境,默认为中文
|
||||
import locale
|
||||
import os
|
||||
example_enable,
|
||||
http_client_enable,
|
||||
api_enable, max_convert_pages,
|
||||
server_name, server_port, latex_delimiters_type, **kwargs
|
||||
):
|
||||
|
||||
def detect_language():
|
||||
# 检查环境变量
|
||||
lang = os.getenv('LANG', '')
|
||||
if 'zh' in lang.lower() or 'chinese' in lang.lower():
|
||||
return 'zh'
|
||||
|
||||
# 检查系统默认locale
|
||||
try:
|
||||
default_locale = locale.getdefaultlocale()[0]
|
||||
if default_locale and 'zh' in default_locale.lower():
|
||||
return 'zh'
|
||||
except:
|
||||
pass
|
||||
|
||||
# 默认返回中文
|
||||
return 'zh'
|
||||
|
||||
detected_lang = detect_language()
|
||||
|
||||
# 创建 i18n 实例,支持中英文,默认为中文
|
||||
# 创建 i18n 实例,支持中英文
|
||||
i18n = gr.I18n(
|
||||
en={
|
||||
"upload_file": "Please upload a PDF or image",
|
||||
|
|
@ -375,7 +264,7 @@ def main(ctx,
|
|||
"backend": "Backend",
|
||||
"server_url": "Server URL",
|
||||
"server_url_info": "OpenAI-compatible server URL for http-client backend.",
|
||||
"recognition_options": "Recognition Options",
|
||||
"recognition_options": "**Recognition Options:**",
|
||||
"table_enable": "Enable table recognition",
|
||||
"table_info": "If disabled, tables will be shown as images.",
|
||||
"formula_label_vlm": "Enable display formula recognition",
|
||||
|
|
@ -395,7 +284,6 @@ def main(ctx,
|
|||
"convert_result": "Convert result",
|
||||
"md_rendering": "Markdown rendering",
|
||||
"md_text": "Markdown text",
|
||||
"mind_map": "Mind Map", # 新增
|
||||
"backend_info_vlm": "High-precision parsing via VLM, supports Chinese and English documents only.",
|
||||
"backend_info_pipeline": "Traditional Multi-model pipeline parsing, supports multiple languages, hallucination-free.",
|
||||
"backend_info_hybrid": "High-precision hybrid parsing, supports multiple languages.",
|
||||
|
|
@ -407,7 +295,7 @@ def main(ctx,
|
|||
"backend": "解析后端",
|
||||
"server_url": "服务器地址",
|
||||
"server_url_info": "http-client 后端的 OpenAI 兼容服务器地址。",
|
||||
"recognition_options": "识别选项",
|
||||
"recognition_options": "**识别选项:**",
|
||||
"table_enable": "启用表格识别",
|
||||
"table_info": "禁用后,表格将显示为图片。",
|
||||
"formula_label_vlm": "启用行间公式识别",
|
||||
|
|
@ -427,7 +315,6 @@ def main(ctx,
|
|||
"convert_result": "转换结果",
|
||||
"md_rendering": "Markdown 渲染",
|
||||
"md_text": "Markdown 文本",
|
||||
"mind_map": "思维导图", # 新增
|
||||
"backend_info_vlm": "多模态大模型高精度解析,仅支持中英文文档。",
|
||||
"backend_info_pipeline": "传统多模型管道解析,支持多语言,无幻觉。",
|
||||
"backend_info_hybrid": "高精度混合解析,支持多语言。",
|
||||
|
|
@ -481,6 +368,7 @@ def main(ctx,
|
|||
|
||||
return client_options_update, ocr_options_update, formula_label_update, backend_info_update
|
||||
|
||||
|
||||
kwargs.update(arg_parse(ctx))
|
||||
|
||||
if latex_delimiters_type == 'a':
|
||||
|
|
@ -511,10 +399,8 @@ def main(ctx,
|
|||
logger.exception(e)
|
||||
|
||||
suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes]
|
||||
with gr.Blocks(title="多模态思维导图助手",
|
||||
fill_height=True) as demo:
|
||||
# gr.HTML(header)
|
||||
gr.HTML("<h1 style='text-align: center;'>多模态思维导图助手</h1>")
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(header)
|
||||
with gr.Row():
|
||||
with gr.Column(variant='panel', scale=5):
|
||||
with gr.Row():
|
||||
|
|
@ -526,21 +412,16 @@ def main(ctx,
|
|||
preferred_option = "hybrid-auto-engine"
|
||||
if http_client_enable:
|
||||
drop_list.extend(["vlm-http-client", "hybrid-http-client"])
|
||||
backend = gr.Dropdown(drop_list, label=i18n("backend"), value=preferred_option,
|
||||
info=get_backend_info(preferred_option))
|
||||
backend = gr.Dropdown(drop_list, label=i18n("backend"), value=preferred_option, info=get_backend_info(preferred_option))
|
||||
with gr.Row(visible=False) as client_options:
|
||||
url = gr.Textbox(label=i18n("server_url"), value='http://localhost:30000',
|
||||
placeholder='http://localhost:30000', info=i18n("server_url_info"))
|
||||
url = gr.Textbox(label=i18n("server_url"), value='http://localhost:30000', placeholder='http://localhost:30000', info=i18n("server_url_info"))
|
||||
with gr.Row(equal_height=True):
|
||||
with gr.Column():
|
||||
gr.Markdown(i18n("recognition_options"))
|
||||
table_enable = gr.Checkbox(label=i18n("table_enable"), value=True, info=i18n("table_info"))
|
||||
formula_enable = gr.Checkbox(label=get_formula_label(preferred_option), value=True,
|
||||
info=get_formula_info(preferred_option))
|
||||
formula_enable = gr.Checkbox(label=get_formula_label(preferred_option), value=True, info=get_formula_info(preferred_option))
|
||||
with gr.Column(visible=False) as ocr_options:
|
||||
language = gr.Dropdown(all_lang, label=i18n("ocr_language"),
|
||||
value='ch (Chinese, English, Chinese Traditional)',
|
||||
info=i18n("ocr_language_info"))
|
||||
language = gr.Dropdown(all_lang, label=i18n("ocr_language"), value='ch (Chinese, English, Chinese Traditional)', info=i18n("ocr_language_info"))
|
||||
is_ocr = gr.Checkbox(label=i18n("force_ocr"), value=False, info=i18n("force_ocr_info"))
|
||||
with gr.Row():
|
||||
change_bu = gr.Button(i18n("convert"))
|
||||
|
|
@ -563,46 +444,50 @@ def main(ctx,
|
|||
md = gr.Markdown(
|
||||
label=i18n("md_rendering"),
|
||||
height=1200,
|
||||
show_copy_button=True,
|
||||
# buttons=["copy"], # gradio 6 以上版本使用
|
||||
show_copy_button=True, # gradio 6 以下版本使用
|
||||
latex_delimiters=latex_delimiters,
|
||||
line_breaks=True
|
||||
)
|
||||
with gr.Tab(i18n("md_text")):
|
||||
md_text = gr.TextArea(
|
||||
lines=45,
|
||||
show_copy_button=True,
|
||||
# buttons=["copy"], # gradio 6 以上版本使用
|
||||
show_copy_button=True, # gradio 6 以下版本使用
|
||||
label=i18n("md_text")
|
||||
)
|
||||
with gr.Tab(i18n("mind_map")): # 新增的思维导图tab
|
||||
mind_map = gr.HTML(label=i18n("mind_map")) # 使用HTML组件来渲染markmap
|
||||
|
||||
# 添加事件处理
|
||||
backend.change(
|
||||
fn=update_interface,
|
||||
inputs=[backend],
|
||||
outputs=[client_options, ocr_options, formula_enable, backend],
|
||||
api_name=False
|
||||
# api_visibility="private" # gradio 6 以上版本使用
|
||||
api_name=False # gradio 6 以下版本使用
|
||||
)
|
||||
# 添加demo.load事件,在页面加载时触发一次界面更新
|
||||
demo.load(
|
||||
fn=update_interface,
|
||||
inputs=[backend],
|
||||
outputs=[client_options, ocr_options, formula_enable, backend],
|
||||
api_name=False
|
||||
# api_visibility="private" # gradio 6 以上版本使用
|
||||
api_name=False # gradio 6 以下版本使用
|
||||
)
|
||||
clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr, mind_map])
|
||||
clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr])
|
||||
|
||||
input_file.change(
|
||||
fn=to_pdf,
|
||||
inputs=input_file,
|
||||
outputs=pdf_show,
|
||||
api_name="to_pdf" if api_enable else False
|
||||
api_name="to_pdf" if api_enable else False, # gradio 6 以下版本使用
|
||||
# api_visibility="public" if api_enable else "private" # gradio 6 以上版本使用
|
||||
)
|
||||
change_bu.click(
|
||||
fn=to_markdown,
|
||||
inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
|
||||
outputs=[md, md_text, output_file, pdf_show, mind_map], # 添加mind_map输出
|
||||
api_name="to_markdown" if api_enable else False
|
||||
outputs=[md, md_text, output_file, pdf_show],
|
||||
api_name="to_markdown" if api_enable else False, # gradio 6 以下版本使用
|
||||
# api_visibility="public" if api_enable else "private" # gradio 6 以上版本使用
|
||||
)
|
||||
|
||||
footer_links = ["gradio", "settings"]
|
||||
|
|
@ -611,12 +496,11 @@ def main(ctx,
|
|||
demo.launch(
|
||||
server_name=server_name,
|
||||
server_port=server_port,
|
||||
show_api=api_enable,
|
||||
i18n=i18n,
|
||||
# title = "多模态思维导图助手",
|
||||
# favicon_path = "logo.png"
|
||||
# footer_links=footer_links, # gradio 6 以上版本使用
|
||||
show_api=api_enable, # gradio 6 以下版本使用
|
||||
i18n=i18n
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
main()
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
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
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,28 +0,0 @@
|
|||
<!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%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
#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>
|
||||
</html>
|
||||
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
File diff suppressed because one or more lines are too long
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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])
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import os
|
|||
import sys
|
||||
|
||||
from mineru.backend.vlm.utils import set_default_gpu_memory_utilization, enable_custom_logits_processors
|
||||
from mineru.utils.config_reader import get_device
|
||||
from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
|
||||
|
||||
from vllm.entrypoints.cli.main import main as vllm_main
|
||||
|
|
@ -13,6 +14,8 @@ def main():
|
|||
has_port_arg = False
|
||||
has_gpu_memory_utilization_arg = False
|
||||
has_logits_processors_arg = False
|
||||
has_block_size_arg = False
|
||||
has_compilation_config = False
|
||||
model_path = None
|
||||
model_arg_indices = []
|
||||
|
||||
|
|
@ -24,6 +27,10 @@ def main():
|
|||
has_gpu_memory_utilization_arg = True
|
||||
if arg == "--logits-processors" or arg.startswith("--logits-processors="):
|
||||
has_logits_processors_arg = True
|
||||
if arg == "--block-size" or arg.startswith("--block-size="):
|
||||
has_block_size_arg = True
|
||||
if arg == "--compilation-config" or arg.startswith("--compilation-config="):
|
||||
has_compilation_config = True
|
||||
if arg == "--model":
|
||||
if i + 1 < len(args):
|
||||
model_path = args[i + 1]
|
||||
|
|
@ -50,6 +57,22 @@ def main():
|
|||
if (not has_logits_processors_arg) and custom_logits_processors:
|
||||
args.extend(["--logits-processors", "mineru_vl_utils:MinerULogitsProcessor"])
|
||||
|
||||
# musa vllm v1 引擎特殊配置
|
||||
# device = get_device()
|
||||
# if device.startswith("musa"):
|
||||
# import torch
|
||||
# if torch.musa.is_available():
|
||||
# if not has_block_size_arg:
|
||||
# args.extend(["--block-size", "32"])
|
||||
# if not has_compilation_config:
|
||||
# args.extend(["--compilation-config", '{"cudagraph_capture_sizes": [1,2,3,4,5,6,7,8,10,12,14,16,18,20,24,28,30], "simple_cuda_graph": true}'])
|
||||
|
||||
# corex vllm v1 引擎特殊配置
|
||||
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
|
||||
if device_type.lower() == "corex":
|
||||
if not has_compilation_config:
|
||||
args.extend(["--compilation-config", '{"cudagraph_mode": "FULL_DECODE_ONLY", "level": 0}'])
|
||||
|
||||
# 重构参数,将模型路径作为位置参数
|
||||
sys.argv = [sys.argv[0]] + ["serve", model_path] + args
|
||||
|
||||
|
|
|
|||
|
|
@ -186,6 +186,22 @@ 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
|
||||
|
||||
if model_name == 'layoutreader':
|
||||
# 检测modelscope的缓存目录是否存在
|
||||
|
|
|
|||
|
|
@ -86,7 +86,19 @@ 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:
|
||||
pass
|
||||
return "cpu"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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,15 @@ 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()
|
||||
gc.collect()
|
||||
|
||||
|
||||
|
|
@ -458,5 +467,14 @@ 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
|
||||
|
||||
return total_memory
|
||||
|
|
|
|||
|
|
@ -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.4"
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ name = "mineru"
|
|||
dynamic = ["version"]
|
||||
license = { text = "AGPL-3.0" }
|
||||
description = "A practical tool for converting PDF to Markdown"
|
||||
readme = "README.md"
|
||||
readme = "README.mineru-upstream.md"
|
||||
requires-python = ">=3.10,<3.14"
|
||||
keywords = ["magic-pdf", "mineru", "MinerU", "convert", "pdf", "markdown"]
|
||||
classifiers = [
|
||||
|
|
|
|||
|
|
@ -1,34 +1,9 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
VERSION=${VERSION:-$(date +%Y%m%d%H%M%S)}
|
||||
API_FLAVOR=${API_FLAVOR:-corex}
|
||||
ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd)
|
||||
|
||||
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
|
||||
;;
|
||||
case "${API_FLAVOR:-corex}" in
|
||||
corex) FILE=docker/china/Dockerfile.corex ;;
|
||||
cuda) FILE=docker/global/Dockerfile.cuda ;;
|
||||
*) echo "API_FLAVOR must be corex or cuda" >&2; exit 2 ;;
|
||||
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
|
||||
exec docker build -f "$ROOT_DIR/$FILE" -t "unis-mineru:${VERSION:-2.7.4}" "$ROOT_DIR"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
"""Start the pinned upstream parser; application features live in MaxKB."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def main():
|
||||
os.environ.setdefault('MINERU_MODEL_SOURCE', 'local')
|
||||
os.environ.setdefault('MINERU_API_MAX_CONCURRENT_REQUESTS', '1')
|
||||
from mineru.version import __version__
|
||||
from mineru import __file__ as module_path
|
||||
if __version__ != '2.7.4' or not Path(module_path).resolve().is_relative_to(ROOT / 'mineru'):
|
||||
raise RuntimeError('解析服务版本或源码路径不匹配')
|
||||
if not any(arg.startswith('--mineru-api-max-concurrent-requests') for arg in sys.argv):
|
||||
sys.argv += ['--mineru-api-max-concurrent-requests', os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS']]
|
||||
memory = os.getenv('MINERU_GPU_MEMORY_UTILIZATION')
|
||||
if memory:
|
||||
if not 0 < float(memory) < 1:
|
||||
raise ValueError('MINERU_GPU_MEMORY_UTILIZATION must be between 0 and 1')
|
||||
if not any(arg.startswith('--gpu-memory-utilization') for arg in sys.argv):
|
||||
sys.argv += ['--gpu-memory-utilization', str(float(memory))]
|
||||
from mineru.cli.fast_api import main as serve
|
||||
serve()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -1,33 +1,5 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
NETWORK=${NETWORK:-unis-ai}
|
||||
API_NAME=${API_NAME:-mineru-api}
|
||||
WEB_NAME=${WEB_NAME:-mindmap-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}
|
||||
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
|
||||
# Compatibility entrypoint: starts only the parser, never the retired workbench.
|
||||
ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd)
|
||||
exec docker compose -f "$ROOT_DIR/docker/compose.yaml" up -d --no-deps mineru-api
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
# 构建阶段
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 使用国内镜像源加速
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
|
||||
# 复制 package.json 和 package-lock.json
|
||||
COPY package*.json ./
|
||||
|
||||
# 安装依赖(使用 npm 淘宝镜像)
|
||||
RUN npm config set registry https://registry.npmmirror.com && \
|
||||
npm install
|
||||
|
||||
# 复制源代码
|
||||
COPY . .
|
||||
|
||||
# 构建前端
|
||||
RUN npm run build
|
||||
|
||||
# 运行阶段
|
||||
FROM nginx:alpine
|
||||
|
||||
# 复制构建结果到 Nginx 静态目录
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
|
||||
# 复制 Nginx 配置
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 9898
|
||||
|
||||
# 启动 Nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
# Portable Web UI image for UnisMindMap.
|
||||
# Runtime API upstream is configured by MINERU_API_URL, defaulting to Docker DNS name mineru-api.
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
COPY package*.json ./
|
||||
RUN npm config set registry https://registry.npmmirror.com && npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
ENV MINERU_API_URL=http://mineru-api:8000
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
|
||||
EXPOSE 9898
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
169
web_ui/README.md
169
web_ui/README.md
|
|
@ -1,169 +0,0 @@
|
|||
# MinerU Vue.js Web UI
|
||||
|
||||
基于 Vue 3 + TypeScript + Element Plus 的现代化 Web 界面,用于替代原有的 Gradio 界面。
|
||||
|
||||
## 🌟 特性
|
||||
|
||||
- ✨ 响应式设计,支持移动端
|
||||
- 🌍 国际化支持(中英文)
|
||||
- 📁 文件拖拽上传
|
||||
- ⚙️ 丰富的配置选项
|
||||
- 📊 Markdown 渲染和源码查看
|
||||
- 🧠 思维导图可视化(开发中)
|
||||
- 🔗 与 FastAPI 后端无缝集成
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Node.js >= 16.0.0
|
||||
- npm >= 8.0.0
|
||||
|
||||
### 安装依赖
|
||||
|
||||
```bash
|
||||
cd web_ui
|
||||
npm install
|
||||
```
|
||||
|
||||
### 启动开发服务器
|
||||
|
||||
```bash
|
||||
# 方式1:使用 npm
|
||||
npm run dev
|
||||
|
||||
# 方式2:使用启动脚本
|
||||
./start.sh
|
||||
```
|
||||
|
||||
### 构建生产版本
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
## 🏗️ 项目结构
|
||||
|
||||
```
|
||||
web_ui/
|
||||
├── src/
|
||||
│ ├── components/ # 可复用组件
|
||||
│ │ ├── FileUploader.vue # 文件上传组件
|
||||
│ │ ├── ConfigPanel.vue # 配置面板组件
|
||||
│ │ ├── ResultPanel.vue # 结果展示组件
|
||||
│ │ ├── MarkdownRenderer.vue # Markdown 渲染器
|
||||
│ │ └── MindMapRenderer.vue # 思维导图渲染器
|
||||
│ ├── views/ # 页面视图
|
||||
│ │ └── DocumentProcessor.vue # 主处理器页面
|
||||
│ ├── composables/ # Vue 组合式函数
|
||||
│ │ └── useDocumentProcessor.ts # 文档处理逻辑
|
||||
│ ├── locales/ # 国际化文件
|
||||
│ │ ├── zh.ts # 中文翻译
|
||||
│ │ ├── en.ts # 英文翻译
|
||||
│ │ └── index.ts # 导出文件
|
||||
│ ├── api/ # API 接口
|
||||
│ │ └── document.ts # 文档处理 API
|
||||
│ ├── utils/ # 工具函数
|
||||
│ │ └── request.ts # HTTP 请求封装
|
||||
│ ├── App.vue # 根组件
|
||||
│ └── main.ts # 入口文件
|
||||
├── public/ # 静态资源
|
||||
├── index.html # HTML 模板
|
||||
├── vite.config.ts # Vite 配置
|
||||
├── tsconfig.json # TypeScript 配置
|
||||
├── package.json # 项目依赖
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 🔧 技术栈
|
||||
|
||||
- **Vue 3** - 渐进式 JavaScript 框架
|
||||
- **TypeScript** - JavaScript 的超集,提供类型安全
|
||||
- **Element Plus** - Vue 3 组件库
|
||||
- **Vite** - 新一代构建工具
|
||||
- **Axios** - HTTP 客户端
|
||||
- **Vue I18n** - 国际化解决方案
|
||||
- **Markdown-it** - Markdown 解析器
|
||||
|
||||
## 🔄 与原 Gradio 界面的区别
|
||||
|
||||
| 特性 | 原 Gradio | Vue.js 版本 |
|
||||
|------|-----------|-------------|
|
||||
| 用户体验 | 基础交互 | 现代化 UI 设计 |
|
||||
| 响应式 | 有限支持 | 完全响应式 |
|
||||
| 国际化 | 有限支持 | 完善的多语言支持 |
|
||||
| 组件化 | 不支持 | 高度组件化 |
|
||||
| 扩展性 | 较差 | 易于扩展和维护 |
|
||||
| 移动端适配 | 不支持 | 响应式设计 |
|
||||
|
||||
## 📋 功能对比
|
||||
|
||||
### ✅ 已实现功能
|
||||
- [x] 文件上传(PDF/图片)
|
||||
- [x] 参数配置面板
|
||||
- [x] 后端选择(pipeline/VLM/hybrid)
|
||||
- [x] OCR 语言选择
|
||||
- [x] 表格和公式识别选项
|
||||
- [x] Markdown 渲染展示
|
||||
- [x] Markdown 源码查看
|
||||
- [x] 结果下载
|
||||
- [x] 中英文国际化
|
||||
- [x] 错误处理和提示
|
||||
|
||||
### ⏳ 待完善功能
|
||||
- [ ] 交互式思维导图
|
||||
- [ ] 批量处理支持
|
||||
- [ ] 处理进度显示
|
||||
- [ ] 历史记录管理
|
||||
- [ ] 用户偏好设置保存
|
||||
- [ ] 更多主题样式
|
||||
|
||||
## 🛠️ 开发指南
|
||||
|
||||
### 添加新组件
|
||||
|
||||
1. 在 `src/components/` 目录下创建新的 `.vue` 文件
|
||||
2. 使用 Composition API 编写组件逻辑
|
||||
3. 在需要的地方导入和使用组件
|
||||
|
||||
### 添加国际化文本
|
||||
|
||||
1. 在 `src/locales/zh.ts` 和 `src/locales/en.ts` 中添加对应的翻译
|
||||
2. 在组件中使用 `$t('key')` 来引用翻译文本
|
||||
|
||||
### API 接口扩展
|
||||
|
||||
1. 在 `src/api/` 目录下创建新的 API 文件
|
||||
2. 使用 `request.ts` 封装的 axios 实例
|
||||
3. 在 `composables` 中调用 API
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### 1. 启动时报错 "Port 3000 is in use"
|
||||
这是正常的,Vite 会自动寻找可用端口。通常会在 3001、3002 等端口启动。
|
||||
|
||||
### 2. 无法连接到后端 API
|
||||
确保 FastAPI 服务已在 8000 端口启动:
|
||||
```bash
|
||||
mineru-api --host localhost --port 8000
|
||||
```
|
||||
|
||||
### 3. 构建失败
|
||||
尝试清理缓存并重新安装依赖:
|
||||
```bash
|
||||
rm -rf node_modules package-lock.json
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
本项目遵循 AGPL-3.0 许可证。
|
||||
|
||||
## 🤝 贡献
|
||||
|
||||
欢迎提交 Issue 和 Pull Request!
|
||||
|
||||
---
|
||||
|
||||
**注意**:此 Vue.js 版本目前仍在开发中,部分功能可能不如原 Gradio 版本稳定。建议在生产环境中继续使用原版 Gradio 界面。
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
<!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%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
cat > /etc/nginx/conf.d/default.conf << 'EOF'
|
||||
server {
|
||||
listen 9898;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log;
|
||||
|
||||
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# 【新增】直接代理 /file_parse 请求(无前缀)
|
||||
location = /file_parse {
|
||||
proxy_pass http://localhost:8000/file_parse;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# 【保留】也支持带 /api 前缀的请求
|
||||
location /api/ {
|
||||
proxy_pass http://localhost:8000/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
server {
|
||||
listen 9898;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log;
|
||||
|
||||
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# 【新增】直接代理 /file_parse 请求(无前缀)
|
||||
location = /file_parse {
|
||||
proxy_pass http://localhost:8000/file_parse;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# 【保留】也支持带 /api 前缀的请求
|
||||
location /api/ {
|
||||
proxy_pass http://localhost:8000/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
server {
|
||||
listen 9898;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log;
|
||||
|
||||
location ~* ^/(assets|mindmap/assets)/.*\.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
|
||||
rewrite ^/mindmap/(.*)$ /$1 break;
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /mindmap {
|
||||
return 301 /mindmap/;
|
||||
}
|
||||
|
||||
location = /mindmap/api/health {
|
||||
proxy_pass ${MINERU_API_URL}/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /api/health {
|
||||
proxy_pass ${MINERU_API_URL}/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location ^~ /mindmap/api/ {
|
||||
rewrite ^/mindmap/api/(.*)$ /api/$1 break;
|
||||
proxy_pass ${MINERU_API_URL};
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location = /file_parse {
|
||||
proxy_pass ${MINERU_API_URL}/file_parse;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass ${MINERU_API_URL}/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
proxy_connect_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location ^~ /mindmap/ {
|
||||
rewrite ^/mindmap/(.*)$ /$1 break;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,31 +0,0 @@
|
|||
{
|
||||
"name": "mineru-web-ui",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.6.0",
|
||||
"build": "^0.1.4",
|
||||
"d3": "^7.9.0",
|
||||
"element-plus": "^2.4.0",
|
||||
"handlebars": "^4.7.9",
|
||||
"markdown-it": "^14.0.0",
|
||||
"markmap-lib": "^0.18.12",
|
||||
"markmap-toolbar": "^0.18.12",
|
||||
"markmap-view": "^0.18.12",
|
||||
"vue": "^3.4.0",
|
||||
"vue-i18n": "^9.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"@vitejs/plugin-vue": "^5.0.0",
|
||||
"typescript": "^5.2.0",
|
||||
"vite": "^5.0.0",
|
||||
"vue-tsc": "^1.8.0"
|
||||
}
|
||||
}
|
||||
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
File diff suppressed because one or more lines are too long
|
|
@ -1,40 +0,0 @@
|
|||
<template>
|
||||
<div id="app">
|
||||
<div class="container">
|
||||
<DocumentProcessor />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DocumentProcessor from './views/DocumentProcessor.vue'
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* 全局样式 */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: #4E5969;
|
||||
background-color: #F2F3F5;
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
import { hubCall } from './hub'
|
||||
import { uuid } from '@/utils/uuid'
|
||||
export interface ParseParams {
|
||||
files: File[]
|
||||
parser_resource_id: string
|
||||
output_dir: string
|
||||
lang_list: string
|
||||
backend: string
|
||||
parse_method: string
|
||||
formula_enable: boolean
|
||||
table_enable: boolean
|
||||
server_url?: string
|
||||
start_page_id: number
|
||||
end_page_id: number
|
||||
return_md: boolean
|
||||
return_middle_json: boolean
|
||||
response_format_zip: boolean
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
backend: string
|
||||
version: string
|
||||
results: Record<string, {
|
||||
md_content?: string
|
||||
middle_json?: string
|
||||
model_output?: string
|
||||
content_list?: string
|
||||
images?: Record<string, string>
|
||||
}>
|
||||
}
|
||||
|
||||
export interface ParseProgress {
|
||||
progress: number | null
|
||||
stage: string
|
||||
status: 'pending' | 'processing' | 'completed' | 'failed'
|
||||
error: string | null
|
||||
file_names: string
|
||||
}
|
||||
|
||||
export interface MindmapOrganizeProgress extends ParseProgress {
|
||||
result_md?: string | null
|
||||
}
|
||||
|
||||
|
||||
const ids = new Map<string, string>()
|
||||
const states: Record<string, ParseProgress['status']> = { PENDING: 'pending', RUNNING: 'processing', SUCCESS: 'completed', FAILED: 'failed' }
|
||||
async function progress(taskId: string): Promise<MindmapOrganizeProgress> {
|
||||
const id = ids.get(taskId)
|
||||
if (!id) return { progress: null, status: 'pending', stage: '准备中', error: null, file_names: '' }
|
||||
const task = await hubCall('tasks', 'get', undefined, id)
|
||||
return { progress: task.status === 'SUCCESS' ? 100 : task.progress?.percent ?? null, status: states[task.status], stage: task.progress?.stage || (task.status === 'PENDING' ? '等待处理' : task.status === 'RUNNING' ? '处理中' : task.status === 'SUCCESS' ? '完成' : '失败'), error: task.error, file_names: task.name, result_md: task.result?.markdown }
|
||||
}
|
||||
export const documentApi = {
|
||||
async parseDocument(params: ParseParams, taskId: string = uuid()): Promise<ParseResult> {
|
||||
if (!params.parser_resource_id) throw new Error('请选择解析服务')
|
||||
const results: ParseResult['results'] = {}
|
||||
for (const file of params.files) {
|
||||
const task = await hubCall('tasks', 'post', { name: file.name.slice(0, 128), nodes: [{ type: 'parse', resource_id: params.parser_resource_id }, { type: 'render' }] }, undefined, file)
|
||||
ids.set(taskId, task.id)
|
||||
const until = Date.now() + 30 * 60 * 1000
|
||||
let completed = false
|
||||
while (Date.now() < until) {
|
||||
const current = await hubCall('tasks', 'get', undefined, task.id)
|
||||
if (current.status === 'FAILED') throw new Error(current.error || '解析失败')
|
||||
if (current.status === 'SUCCESS') { results[file.name] = { md_content: current.result.markdown, middle_json: JSON.stringify(current.result.source) }; completed = true; break }
|
||||
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||
}
|
||||
if (!completed) throw new Error('任务仍在处理中,请到管理页查看')
|
||||
}
|
||||
return { backend: 'shared', version: '1', results }
|
||||
},
|
||||
async createParseTask(_taskId: string): Promise<ParseProgress> { return { progress: null, stage: '准备中', status: 'pending', error: null, file_names: '' } },
|
||||
getParseProgress: progress,
|
||||
async createMindmapTask(taskId: string, markdown: string, _mode = 'smart', prompt?: string, config?: { model_id: string; temperature: number }): Promise<MindmapOrganizeProgress> {
|
||||
if (!config?.model_id) throw new Error('请选择整理模型')
|
||||
const task = await hubCall('tasks', 'post', { name: '智能整理', markdown, nodes: [{ type: 'organize', model_id: config.model_id, prompt, temperature: config.temperature }, { type: 'render' }] })
|
||||
ids.set(taskId, task.id)
|
||||
return progress(taskId)
|
||||
},
|
||||
getMindmapProgress: progress
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
// The parent owns authentication. No token or provider secret is sent to this frame.
|
||||
import { uuid } from '@/utils/uuid'
|
||||
const pending = new Map<string, { resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>()
|
||||
const parentOrigin = (() => { try { return new URL(document.referrer).origin } catch { return '' } })()
|
||||
window.addEventListener('message', event => {
|
||||
if (event.source !== window.parent || event.origin !== parentOrigin || event.data?.type !== 'ai-hub-response') return
|
||||
const call = pending.get(event.data.id)
|
||||
if (!call) return
|
||||
clearTimeout(call.timer); pending.delete(event.data.id)
|
||||
if (event.data.error) call.reject(new Error(event.data.error)); else call.resolve(event.data.data)
|
||||
})
|
||||
export async function hubCall(kind: string, method = 'get', data?: any, recordId?: string, file?: File): Promise<any> {
|
||||
if (window.parent === window || !parentOrigin) throw new Error('请从管理平台打开思维导图')
|
||||
const id = uuid()
|
||||
const upload = file ? { name: file.name, content: await file.arrayBuffer() } : undefined
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error('请求超时')) }, 45000)
|
||||
pending.set(id, { resolve, reject, timer })
|
||||
window.parent.postMessage({ type: 'ai-hub-request', id, kind, method, data, recordId, file: upload }, parentOrigin)
|
||||
})
|
||||
}
|
||||
export function onOpenArtifact(callback: (artifact: any) => void) {
|
||||
const handler = (event: MessageEvent) => {
|
||||
if (event.source === window.parent && event.origin === parentOrigin && event.data?.type === 'ai-hub-open') callback(event.data.artifact)
|
||||
}
|
||||
window.addEventListener('message', handler)
|
||||
return () => window.removeEventListener('message', handler)
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
<template>
|
||||
<div class="config-panel">
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="解析服务"><el-select v-model="draft.parserResourceId" placeholder="请选择"><el-option v-for="p in resources.parsers" :key="p.id" :label="p.name" :value="p.id"/></el-select></el-form-item>
|
||||
<el-form-item label="整理模型"><el-select v-model="draft.mindmapModelId" clearable placeholder="请选择"><el-option v-for="m in models" :key="m.id" :label="m.name" :value="m.id"/></el-select></el-form-item>
|
||||
<el-form-item label="温度"><el-input-number v-model="draft.mindmapLlmTemperature" :min="0" :max="2" :step="0.1"/></el-form-item>
|
||||
<el-form-item label="整理提示词"><el-input v-model="draft.mindmapPrompt" type="textarea" :rows="6" /></el-form-item>
|
||||
<el-form-item label="导出长边"><el-select v-model="draft.exportResolution"><el-option label="1080P" :value="1080"/><el-option label="2K" :value="2560"/><el-option label="4K" :value="3840"/></el-select></el-form-item>
|
||||
<div v-if="error" class="error">{{ error }}</div>
|
||||
<div class="actions"><el-button @click="load">刷新资源</el-button><el-button type="primary" @click="confirm">确认</el-button></div>
|
||||
</el-form>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import type { DocumentConfig } from '@/composables/useDocumentProcessor'
|
||||
import { hubCall } from '@/api/hub'
|
||||
const props = defineProps<{ modelValue: DocumentConfig; backendOptions: any[]; languageOptions: any[] }>()
|
||||
const emit = defineEmits(['update:modelValue', 'backendChange', 'close'])
|
||||
const draft = reactive({ ...props.modelValue })
|
||||
const resources = ref<any>({ parsers: [], models: [] }), error = ref('')
|
||||
const models = computed(() => resources.value.models.filter((m: any) => m.model_type === 'LLM'))
|
||||
watch(() => props.modelValue, value => Object.assign(draft, value), { deep: true })
|
||||
async function load() {
|
||||
try {
|
||||
resources.value = await hubCall('resources'); error.value = ''
|
||||
if (!draft.parserResourceId && resources.value.parsers?.length) draft.parserResourceId = resources.value.parsers[0].id
|
||||
if (!draft.mindmapModelId && models.value.length) draft.mindmapModelId = models.value[0].id
|
||||
if (draft.parserResourceId || draft.mindmapModelId) emit('update:modelValue', { ...draft })
|
||||
} catch (e: any) { error.value = e.message }
|
||||
}
|
||||
function confirm() { emit('update:modelValue', { ...draft }); emit('close') }
|
||||
onMounted(load)
|
||||
</script>
|
||||
<style scoped>.config-panel { padding: 12px; } .el-select { width: 100%; } .actions { display: flex; justify-content: flex-end; gap: 8px; } .error { color: var(--el-color-danger); margin: 8px 0; }</style>
|
||||
|
|
@ -1,246 +0,0 @@
|
|||
<template>
|
||||
<div class="file-uploader">
|
||||
<div
|
||||
class="upload-container"
|
||||
:class="{ 'drag-over': isDragging }"
|
||||
@drop="handleDrop"
|
||||
@dragover.prevent="isDragging = true"
|
||||
@dragleave="isDragging = false"
|
||||
@click="triggerUpload"
|
||||
>
|
||||
<div class="upload-content">
|
||||
<el-icon class="upload-icon"><UploadFilled /></el-icon>
|
||||
<div class="upload-text">
|
||||
<div class="main-text">点击或拖拽文件到此处上传</div>
|
||||
<div class="sub-text">支持 PDF、PNG、JPG、JPEG 格式,最大 100MB</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 隐藏的上传控件 -->
|
||||
<el-upload
|
||||
ref="uploadRef"
|
||||
:auto-upload="false"
|
||||
:show-file-list="false"
|
||||
:on-change="handleFileChange"
|
||||
:before-upload="beforeUpload"
|
||||
multiple
|
||||
accept=".pdf,.png,.jpg,.jpeg"
|
||||
class="hidden-upload"
|
||||
>
|
||||
<el-button type="primary">上传文件</el-button>
|
||||
</el-upload>
|
||||
|
||||
<!-- 已上传文件预览 -->
|
||||
<div v-if="files.length > 0" class="file-preview">
|
||||
<h3 class="preview-title">已上传文件</h3>
|
||||
<div class="file-card" v-for="(file, index) in files" :key="index">
|
||||
<div class="file-info">
|
||||
<el-icon class="file-icon"><Document /></el-icon>
|
||||
<span class="file-name">{{ file.name }}</span>
|
||||
<span class="file-size">({{ formatFileSize(file.size) }})</span>
|
||||
<el-button
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
circle
|
||||
size="small"
|
||||
@click.stop="removeFile(index)"
|
||||
class="remove-button"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { UploadFilled, Document, Delete, Picture } from '@element-plus/icons-vue'
|
||||
import type { UploadFile, UploadInstance } from 'element-plus'
|
||||
|
||||
interface Props {
|
||||
modelValue: File[]
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
(e: 'update:modelValue', value: File[]): void
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const files = ref<File[]>(props.modelValue)
|
||||
const uploadRef = ref<UploadInstance>()
|
||||
const isDragging = ref(false)
|
||||
|
||||
// 监听外部值变化
|
||||
watch(() => props.modelValue, (newVal) => {
|
||||
files.value = newVal
|
||||
})
|
||||
|
||||
// 监听内部值变化并通知父组件
|
||||
watch(files, (newVal) => {
|
||||
emit('update:modelValue', newVal)
|
||||
}, { deep: true })
|
||||
|
||||
const triggerUpload = () => {
|
||||
uploadRef.value?.handleClick()
|
||||
}
|
||||
|
||||
const handleFileChange = (uploadFile: UploadFile) => {
|
||||
if (uploadFile.raw) {
|
||||
files.value.push(uploadFile.raw)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDrop = (event: DragEvent) => {
|
||||
event.preventDefault()
|
||||
isDragging.value = false
|
||||
|
||||
if (event.dataTransfer?.files) {
|
||||
const droppedFiles = Array.from(event.dataTransfer.files)
|
||||
droppedFiles.forEach(file => {
|
||||
if (file.type.match(/(pdf|png|jpe?g)/i)) {
|
||||
files.value.push(file)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const beforeUpload = (file: File): boolean => {
|
||||
// 阻止自动上传
|
||||
return false
|
||||
}
|
||||
|
||||
const removeFile = (index: number) => {
|
||||
files.value.splice(index, 1)
|
||||
}
|
||||
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.file-uploader {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.upload-container {
|
||||
border: 2px dashed #C9CDD4;
|
||||
border-radius: 8px;
|
||||
background-color: #FFFFFF;
|
||||
padding: 60px 24px;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
margin-bottom: 24px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.upload-container:hover {
|
||||
border-color: #165DFF;
|
||||
background-color: #E8F3FF;
|
||||
}
|
||||
|
||||
.upload-container.drag-over {
|
||||
border-color: #165DFF;
|
||||
background-color: #E8F3FF;
|
||||
}
|
||||
|
||||
.upload-container.drag-over .upload-icon {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.upload-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
font-size: 24px;
|
||||
color: #165DFF;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.main-text {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: #1D2129;
|
||||
}
|
||||
|
||||
.sub-text {
|
||||
font-size: 12px;
|
||||
color: #4E5969;
|
||||
}
|
||||
|
||||
.hidden-upload {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-preview {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.preview-title {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
color: #1D2129;
|
||||
margin: 0 0 16px 0;
|
||||
}
|
||||
|
||||
.file-card {
|
||||
background-color: #F2F3F5;
|
||||
border-radius: 6px;
|
||||
padding: 16px;
|
||||
margin-bottom: 12px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.file-card:hover {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
color: #165DFF;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
flex: 1;
|
||||
font-weight: 400;
|
||||
color: #4E5969;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
color: #4E5969;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.remove-button {
|
||||
opacity: 0.7;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.remove-button:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,700 +0,0 @@
|
|||
<template>
|
||||
<div class="markdown-renderer" @click="openImage">
|
||||
<el-image-viewer v-if="imageViewer" :url-list="[imageViewer]" @close="imageViewer = ''" />
|
||||
<template v-if="content">
|
||||
<div class="content-toolbar render-actions">
|
||||
<div class="render-actions-left">
|
||||
<el-segmented
|
||||
v-if="mode === 'markdown'"
|
||||
v-model="activeFlavor"
|
||||
:options="flavorOptions"
|
||||
size="small"
|
||||
/>
|
||||
<el-segmented
|
||||
v-else-if="mode === 'richtext'"
|
||||
v-model="activeRichtextFormat"
|
||||
:options="richtextOptions"
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
<div class="render-actions-right">
|
||||
<el-button type="primary" size="small" class="action-button primary" @click="handleDownload()">
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="render-content">
|
||||
<el-button v-if="imageError" link type="warning" @click="retryImages">{{ imageError }}</el-button>
|
||||
<div v-if="mode === 'markdown'" class="render-shell">
|
||||
<div ref="markdownRef" class="markdown-content rendered-html" v-html="renderedContent"></div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="mode === 'html'" class="render-shell">
|
||||
<div ref="htmlRef" class="markdown-content rendered-html" v-html="renderedContent"></div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="mode === 'pdf'" class="render-shell">
|
||||
<div class="pdf-stage">
|
||||
<div ref="pdfRef" class="pdf-preview-pages">
|
||||
<div
|
||||
v-for="(page, index) in pdfPages"
|
||||
:key="`pdf-page-${index}`"
|
||||
class="pdf-page"
|
||||
>
|
||||
<div class="markdown-content pdf-content" v-html="page"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref="pdfMeasureRef"
|
||||
class="pdf-measure markdown-content pdf-content"
|
||||
v-html="renderedContent"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div v-else class="render-shell">
|
||||
<div ref="richtextRef" class="markdown-content rendered-html richtext-content" v-html="renderedContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-else class="empty-state">
|
||||
<el-empty :description="$t('results.noResults')" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import type { PropType } from 'vue'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { loadHtml2Pdf } from '@/utils/wordToPdf'
|
||||
import { useImageAssets, hasImageAssets, exportMarkdownBundle, embedImages } from '@/utils/imageAssets'
|
||||
|
||||
type RenderMode = 'markdown' | 'html' | 'pdf' | 'richtext'
|
||||
type FlavorMode = 'commonmark' | 'gfm'
|
||||
type RichtextFormat = 'word' | 'rtf'
|
||||
|
||||
const props = defineProps({
|
||||
content: {
|
||||
type: String as PropType<string>,
|
||||
default: ''
|
||||
},
|
||||
mode: {
|
||||
type: String as PropType<RenderMode>,
|
||||
default: 'markdown'
|
||||
},
|
||||
flavor: {
|
||||
type: String as PropType<FlavorMode>,
|
||||
default: 'gfm'
|
||||
}
|
||||
})
|
||||
|
||||
const activeFlavor = ref<FlavorMode>(props.flavor)
|
||||
const activeRichtextFormat = ref<RichtextFormat>('word')
|
||||
const markdownRef = ref<HTMLElement | null>(null)
|
||||
const htmlRef = ref<HTMLElement | null>(null)
|
||||
const pdfRef = ref<HTMLElement | null>(null)
|
||||
const pdfMeasureRef = ref<HTMLElement | null>(null)
|
||||
const richtextRef = ref<HTMLElement | null>(null)
|
||||
const pdfPages = ref<string[]>([])
|
||||
const imageViewer = ref('')
|
||||
function openImage(event: MouseEvent) {
|
||||
if (event.target instanceof HTMLImageElement && event.target.src) imageViewer.value = event.target.src
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.flavor,
|
||||
(value) => {
|
||||
activeFlavor.value = value
|
||||
}
|
||||
)
|
||||
|
||||
const flavorOptions = [
|
||||
{ label: 'CommonMark', value: 'commonmark' },
|
||||
{ label: 'GFM', value: 'gfm' }
|
||||
]
|
||||
|
||||
const richtextOptions = [
|
||||
{ label: 'Word', value: 'word' },
|
||||
{ label: 'RTF', value: 'rtf' }
|
||||
]
|
||||
|
||||
function applyMathSupport(md: MarkdownIt) {
|
||||
md.use(function (md) {
|
||||
md.inline.ruler.after('escape', 'math_inline', function (state, silent) {
|
||||
const start = state.pos
|
||||
if (state.src.charCodeAt(start) !== 0x24) return false
|
||||
if (state.src.charCodeAt(start + 1) !== 0x24) return false
|
||||
|
||||
let pos = start + 2
|
||||
let found = false
|
||||
while (pos < state.posMax) {
|
||||
if (state.src.charCodeAt(pos) === 0x24 && state.src.charCodeAt(pos + 1) === 0x24) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
pos++
|
||||
}
|
||||
if (!found) return false
|
||||
|
||||
if (!silent) {
|
||||
const token = state.push('math_inline', 'span', 0)
|
||||
token.content = state.src.slice(start + 2, pos)
|
||||
token.markup = '$$'
|
||||
}
|
||||
|
||||
state.pos = pos + 2
|
||||
return true
|
||||
})
|
||||
|
||||
md.inline.ruler.after('escape', 'math_inline_single', function (state, silent) {
|
||||
const start = state.pos
|
||||
if (state.src.charCodeAt(start) !== 0x24) return false
|
||||
if (state.src.charCodeAt(start + 1) === 0x24) return false
|
||||
|
||||
let pos = start + 1
|
||||
let found = false
|
||||
while (pos < state.posMax) {
|
||||
if (state.src.charCodeAt(pos) === 0x24) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
pos++
|
||||
}
|
||||
if (!found) return false
|
||||
|
||||
if (!silent) {
|
||||
const token = state.push('math_inline_single', 'span', 0)
|
||||
token.content = state.src.slice(start + 1, pos)
|
||||
token.markup = '$'
|
||||
}
|
||||
|
||||
state.pos = pos + 1
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
md.renderer.rules.math_inline = function(tokens, idx) {
|
||||
return `<span class="math-inline">$$${tokens[idx].content}$$</span>`
|
||||
}
|
||||
|
||||
md.renderer.rules.math_inline_single = function(tokens, idx) {
|
||||
return `<span class="math-inline">$${tokens[idx].content}$</span>`
|
||||
}
|
||||
}
|
||||
|
||||
function createMarkdownRenderer(flavor: FlavorMode) {
|
||||
const md = flavor === 'commonmark'
|
||||
? new MarkdownIt('commonmark', {
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
breaks: false
|
||||
})
|
||||
: new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
breaks: true
|
||||
})
|
||||
|
||||
applyMathSupport(md)
|
||||
return md
|
||||
}
|
||||
|
||||
const { content: previewContent, error: imageError, retry: retryImages } = useImageAssets(() => props.content)
|
||||
const renderedContent = computed(() => {
|
||||
if (!previewContent.value) return ''
|
||||
const flavor = props.mode === 'markdown' ? activeFlavor.value : 'gfm'
|
||||
const renderer = createMarkdownRenderer(flavor)
|
||||
return renderer.render(previewContent.value)
|
||||
})
|
||||
|
||||
async function recalculatePdfPages() {
|
||||
if (props.mode !== 'pdf') {
|
||||
pdfPages.value = []
|
||||
return
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
|
||||
const measureEl = pdfMeasureRef.value
|
||||
if (!measureEl) {
|
||||
pdfPages.value = renderedContent.value ? [renderedContent.value] : []
|
||||
return
|
||||
}
|
||||
|
||||
await Promise.all(Array.from(measureEl.querySelectorAll('img')).map(image => image.decode().catch(() => undefined)))
|
||||
|
||||
const children = Array.from(measureEl.children) as HTMLElement[]
|
||||
if (children.length === 0) {
|
||||
pdfPages.value = renderedContent.value ? [renderedContent.value] : []
|
||||
return
|
||||
}
|
||||
|
||||
const maxPageHeight = 980
|
||||
const pages: string[] = []
|
||||
let currentPageHtml = ''
|
||||
let currentHeight = 0
|
||||
|
||||
children.forEach((child) => {
|
||||
const childHeight = child.offsetHeight || child.scrollHeight || 0
|
||||
const childHtml = child.outerHTML
|
||||
|
||||
if (currentPageHtml && currentHeight + childHeight > maxPageHeight) {
|
||||
pages.push(currentPageHtml)
|
||||
currentPageHtml = childHtml
|
||||
currentHeight = childHeight
|
||||
return
|
||||
}
|
||||
|
||||
currentPageHtml += childHtml
|
||||
currentHeight += childHeight
|
||||
})
|
||||
|
||||
if (currentPageHtml) {
|
||||
pages.push(currentPageHtml)
|
||||
}
|
||||
|
||||
pdfPages.value = pages.length > 0 ? pages : [renderedContent.value]
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.mode, renderedContent.value],
|
||||
() => {
|
||||
void recalculatePdfPages()
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void recalculatePdfPages()
|
||||
})
|
||||
|
||||
const baseFileName = computed(() => `markdown_render_${new Date().getTime()}`)
|
||||
|
||||
function downloadBlob(blob: Blob, fileName: string) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = fileName
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function createFullHtmlDocument(innerHtml: string, title: string) {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>${title}</title>
|
||||
<style>
|
||||
body { font-family: "Microsoft YaHei", Arial, sans-serif; color: #1f2937; padding: 32px; line-height: 1.75; }
|
||||
h1, h2, h3, h4, h5, h6 { color: #111827; }
|
||||
pre { background: #f5f7fa; padding: 16px; border-radius: 8px; overflow: auto; }
|
||||
code { background: #f5f7fa; padding: 2px 4px; border-radius: 4px; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
th, td { border: 1px solid #dcdfe6; padding: 8px 12px; text-align: left; }
|
||||
blockquote { border-left: 4px solid #dcdfe6; margin: 1em 0; padding-left: 1em; color: #606266; }
|
||||
img { max-width: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>${innerHtml}</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
function htmlToPlainText(html: string) {
|
||||
const temp = document.createElement('div')
|
||||
temp.innerHTML = html
|
||||
return temp.innerText || temp.textContent || ''
|
||||
}
|
||||
|
||||
function escapeRtf(text: string) {
|
||||
return text
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/\{/g, '\\{')
|
||||
.replace(/\}/g, '\\}')
|
||||
.replace(/\n/g, '\\par\n')
|
||||
}
|
||||
|
||||
async function exportHtml(innerHtml: string, fileName: string) {
|
||||
const html = createFullHtmlDocument(await embedImages(innerHtml), fileName)
|
||||
downloadBlob(new Blob([html], { type: 'text/html;charset=utf-8' }), fileName)
|
||||
}
|
||||
|
||||
async function exportMarkdown(markdown: string, fileName: string) {
|
||||
if (hasImageAssets(markdown)) {
|
||||
downloadBlob(await exportMarkdownBundle(markdown), fileName.replace(/\.md$/, '.zip'))
|
||||
return
|
||||
}
|
||||
downloadBlob(new Blob([markdown], { type: 'text/markdown;charset=utf-8' }), fileName)
|
||||
}
|
||||
|
||||
async function exportPdf(element: HTMLElement | null, fileName: string) {
|
||||
if (!element) {
|
||||
ElMessage.error('当前没有可导出的 PDF 内容')
|
||||
return
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
await loadHtml2Pdf()
|
||||
|
||||
const pdfBlob = await window.html2pdf()
|
||||
.set({
|
||||
margin: 10,
|
||||
filename: fileName,
|
||||
image: { type: 'jpeg', quality: 0.98 },
|
||||
html2canvas: { scale: 2, useCORS: true },
|
||||
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
|
||||
})
|
||||
.from(element)
|
||||
.outputPdf('blob')
|
||||
|
||||
downloadBlob(pdfBlob, fileName)
|
||||
}
|
||||
|
||||
async function exportDoc(innerHtml: string, fileName: string) {
|
||||
const docHtml = createFullHtmlDocument(await embedImages(innerHtml), fileName)
|
||||
downloadBlob(new Blob(['\ufeff', docHtml], { type: 'application/msword' }), fileName)
|
||||
}
|
||||
|
||||
async function exportRtf(innerHtml: string, fileName: string) {
|
||||
const plainText = htmlToPlainText(innerHtml)
|
||||
const rtf = `{\\rtf1\\ansi\\deff0 {\\fonttbl{\\f0 Calibri;}}\n\\fs24 ${escapeRtf(plainText)}}`
|
||||
downloadBlob(new Blob([rtf], { type: 'application/rtf' }), fileName)
|
||||
}
|
||||
|
||||
async function handleDownload() {
|
||||
try {
|
||||
if (props.mode === 'markdown') {
|
||||
const suffix = activeFlavor.value === 'commonmark' ? '_commonmark' : '_gfm'
|
||||
await exportMarkdown(props.content, `${baseFileName.value}${suffix}.md`)
|
||||
return
|
||||
}
|
||||
if (props.mode === 'html') {
|
||||
await exportHtml(renderedContent.value, `${baseFileName.value}.html`)
|
||||
return
|
||||
}
|
||||
if (props.mode === 'pdf') {
|
||||
await exportPdf(pdfRef.value, `${baseFileName.value}.pdf`)
|
||||
return
|
||||
}
|
||||
if (activeRichtextFormat.value === 'word') {
|
||||
await exportDoc(renderedContent.value, `${baseFileName.value}.doc`)
|
||||
return
|
||||
}
|
||||
await exportRtf(renderedContent.value, `${baseFileName.value}.rtf`)
|
||||
} catch { ElMessage.error('下载失败,请重试') }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.markdown-renderer {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 4px;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.content-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.render-actions {
|
||||
padding: 0 0 12px;
|
||||
background-color: #FFFFFF;
|
||||
}
|
||||
|
||||
.render-actions-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 32px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.render-actions-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
border-radius: 6px;
|
||||
transition: all 0.3s ease;
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.action-button.primary {
|
||||
background-color: #165dff;
|
||||
border-color: #165dff;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.action-button.primary:hover {
|
||||
background-color: #0e42d2;
|
||||
border-color: #0e42d2;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
|
||||
}
|
||||
|
||||
.render-shell {
|
||||
min-height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.render-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.render-header {
|
||||
padding: 14px 16px;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(135deg, #f7faff 0%, #eef4ff 100%);
|
||||
border: 1px solid #d7e4ff;
|
||||
}
|
||||
|
||||
.render-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.render-desc {
|
||||
margin-top: 4px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #5b6472;
|
||||
}
|
||||
|
||||
.markdown-content {
|
||||
padding: 20px;
|
||||
background: white;
|
||||
border-radius: 4px;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.rendered-html {
|
||||
border: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.pdf-stage {
|
||||
padding: 20px;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
background: #F8F9FA;
|
||||
}
|
||||
|
||||
.pdf-preview-pages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.pdf-page {
|
||||
width: min(100%, 840px);
|
||||
min-height: 1160px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border: 1px solid #d9dee8;
|
||||
box-shadow: 0 18px 45px rgba(15, 23, 42, 0.12);
|
||||
padding: 28px 36px 36px;
|
||||
}
|
||||
|
||||
.pdf-content {
|
||||
padding: 0;
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.pdf-measure {
|
||||
position: absolute;
|
||||
left: -99999px;
|
||||
top: 0;
|
||||
width: 768px;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.richtext-stage {
|
||||
padding: 12px;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
background: #F8F9FA;
|
||||
}
|
||||
|
||||
.richtext-document {
|
||||
min-height: 100%;
|
||||
background: white;
|
||||
border: 1px solid #dde3ea;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.richtext-content {
|
||||
padding: 32px 40px 48px;
|
||||
}
|
||||
|
||||
.markdown-content :deep(h1) {
|
||||
font-size: 2em;
|
||||
margin: 0.67em 0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-content :deep(h2) {
|
||||
font-size: 1.5em;
|
||||
margin: 0.83em 0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-content :deep(h3) {
|
||||
font-size: 1.17em;
|
||||
margin: 1em 0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-content :deep(p) {
|
||||
margin: 1em 0;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.markdown-content :deep(code) {
|
||||
background-color: #f5f7fa;
|
||||
padding: 2px 4px;
|
||||
border-radius: 3px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
}
|
||||
|
||||
.markdown-content :deep(pre) {
|
||||
background-color: #f5f7fa;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.markdown-content :deep(pre code) {
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdown-content :deep(blockquote) {
|
||||
margin: 1em 0;
|
||||
padding: 0 1em;
|
||||
border-left: 4px solid #dcdfe6;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.markdown-content :deep(ul), .markdown-content :deep(ol) {
|
||||
margin: 1em 0;
|
||||
padding-left: 2em;
|
||||
}
|
||||
|
||||
.markdown-content :deep(li) {
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
|
||||
.markdown-content :deep(table) {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.markdown-content :deep(th), .markdown-content :deep(td) {
|
||||
border: 1px solid #dcdfe6;
|
||||
padding: 8px 12px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.markdown-content :deep(th) {
|
||||
background-color: #f5f7fa;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-content :deep(img) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.math-inline {
|
||||
font-family: 'Cambria Math', 'STIX Two Math', serif;
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.render-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.render-actions-left {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.render-actions-right {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.pdf-page {
|
||||
padding: 24px 20px 32px;
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.richtext-content {
|
||||
padding: 24px 18px 32px;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,747 +0,0 @@
|
|||
<template>
|
||||
<div class="mindmap-container">
|
||||
<el-image-viewer v-if="imageViewer" :url-list="[imageViewer]" @close="imageViewer = ''" />
|
||||
<div class="content-toolbar mindmap-actions">
|
||||
<div class="mindmap-actions-left">
|
||||
<span class="content-toolbar-meta">{{ nodeSummary }}</span>
|
||||
</div>
|
||||
<div class="mindmap-actions-right">
|
||||
<el-dropdown @command="handleDownload">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
class="action-button primary"
|
||||
:disabled="!content"
|
||||
>
|
||||
<template #icon>
|
||||
<el-icon><Download /></el-icon>
|
||||
</template>
|
||||
下载
|
||||
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||
</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="svg">SVG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="png">PNG 格式</el-dropdown-item>
|
||||
<el-dropdown-item command="jpeg">JPEG 格式</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button
|
||||
type="default"
|
||||
size="small"
|
||||
@click="resetView"
|
||||
class="action-button secondary"
|
||||
>
|
||||
<template #icon>
|
||||
<el-icon><Refresh /></el-icon>
|
||||
</template>
|
||||
重置视图
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mindmap-content" @click="handleNodeClick">
|
||||
<el-button v-if="imageError" link type="warning" @click.stop="retryImages">{{ imageError }}</el-button>
|
||||
<div class="empty-state" v-if="!content">
|
||||
<el-icon class="empty-icon"><Document /></el-icon>
|
||||
<p class="empty-text">暂无思维导图内容</p>
|
||||
<p class="empty-subtext">请先上传并转换文档</p>
|
||||
</div>
|
||||
<div class="mindmap-loading" v-if="content && isRendering">
|
||||
<el-icon class="loading-icon"><Loading /></el-icon>
|
||||
<span>正在生成导图...</span>
|
||||
</div>
|
||||
<svg ref="svgRef" class="markmap-svg" v-show="content"></svg>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
|
||||
import { Download, Refresh, Document, ArrowDown, Loading } from '@element-plus/icons-vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
|
||||
// 导入 markmap 相关包
|
||||
import { Transformer } from 'markmap-lib'
|
||||
import { Markmap, loadCSS, loadJS } from 'markmap-view'
|
||||
import * as markmapView from 'markmap-view'
|
||||
import { useImageAssets, embedImages } from '@/utils/imageAssets'
|
||||
import { captureFolds, restoreFolds, type FoldState } from '@/utils/mindmapState'
|
||||
|
||||
const props = defineProps({
|
||||
content: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
exportResolution: {
|
||||
type: Number,
|
||||
default: 0
|
||||
},
|
||||
documentKey: {
|
||||
type: String,
|
||||
default: 'document'
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'node-edit', payload: { oldText: string; newText: string }): void
|
||||
}>()
|
||||
|
||||
const svgRef = ref<SVGElement | null>(null)
|
||||
let mmInstance: any = null
|
||||
let renderTimer: number | undefined
|
||||
let activeDocumentKey = ''
|
||||
let renderQueue = Promise.resolve()
|
||||
let needsInitialFit = true
|
||||
let viewportObserver: ResizeObserver | undefined
|
||||
const viewStates = new Map<string, { folds: FoldState; camera: any }>()
|
||||
function rememberView() {
|
||||
if (!activeDocumentKey || !mmInstance?.state?.data) return
|
||||
viewStates.set(activeDocumentKey, { folds: captureFolds(mmInstance.state.data), camera: needsInitialFit ? undefined : mmInstance.svg.property('__zoom') })
|
||||
if (viewStates.size > 10) viewStates.delete(viewStates.keys().next().value!)
|
||||
}
|
||||
const transformer = new Transformer()
|
||||
const scale = ref(1)
|
||||
const isRendering = ref(false)
|
||||
const totalNodeCount = ref(0)
|
||||
const hiddenNodeCount = ref(0)
|
||||
|
||||
type MarkmapNode = {
|
||||
content?: string
|
||||
children?: MarkmapNode[]
|
||||
payload?: {
|
||||
fold?: number
|
||||
}
|
||||
}
|
||||
|
||||
const nodeSummary = computed(() => {
|
||||
if (!props.content) return '暂无节点'
|
||||
return hiddenNodeCount.value > 0
|
||||
? `已生成 ${totalNodeCount.value} 个节点,隐藏 ${hiddenNodeCount.value} 个节点`
|
||||
: `已生成 ${totalNodeCount.value} 个节点`
|
||||
})
|
||||
|
||||
const updateNodeStats = () => {
|
||||
const root = mmInstance?.state?.data as MarkmapNode | undefined
|
||||
if (!root || !props.content) {
|
||||
totalNodeCount.value = 0
|
||||
hiddenNodeCount.value = 0
|
||||
return
|
||||
}
|
||||
|
||||
const countSubtree = (node: MarkmapNode): number => {
|
||||
const children = node.children || []
|
||||
return 1 + children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
}
|
||||
|
||||
const walkVisible = (node: MarkmapNode): { total: number; hidden: number } => {
|
||||
const children = node.children || []
|
||||
const total = 1 + children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
|
||||
if (node.payload?.fold && children.length > 0) {
|
||||
return {
|
||||
total,
|
||||
hidden: children.reduce((sum, child) => sum + countSubtree(child), 0)
|
||||
}
|
||||
}
|
||||
|
||||
const childStats = children.reduce(
|
||||
(stats, child) => {
|
||||
const childStat = walkVisible(child)
|
||||
return {
|
||||
total: stats.total + childStat.total,
|
||||
hidden: stats.hidden + childStat.hidden
|
||||
}
|
||||
},
|
||||
{ total: 1, hidden: 0 }
|
||||
)
|
||||
return childStats
|
||||
}
|
||||
|
||||
const stats = walkVisible(root)
|
||||
totalNodeCount.value = Math.max(0, stats.total - 1)
|
||||
hiddenNodeCount.value = Math.max(0, stats.hidden)
|
||||
}
|
||||
|
||||
const { content: imageContent, error: imageError, retry: retryImages } = useImageAssets(() => props.content)
|
||||
const imageViewer = ref('')
|
||||
const initMarkmap = async () => {
|
||||
if (!svgRef.value) return
|
||||
if (props.content && !imageContent.value) return
|
||||
|
||||
if (!props.content) {
|
||||
svgRef.value.innerHTML = ''
|
||||
if (mmInstance && typeof mmInstance.destroy === 'function') {
|
||||
mmInstance.destroy()
|
||||
}
|
||||
mmInstance = null
|
||||
return
|
||||
}
|
||||
|
||||
isRendering.value = true
|
||||
|
||||
try {
|
||||
rememberView()
|
||||
const documentKey = props.documentKey
|
||||
const saved = viewStates.get(documentKey)
|
||||
const { root, features } = transformer.transform(imageContent.value)
|
||||
restoreFolds(root, saved?.folds)
|
||||
const { styles, scripts } = transformer.getUsedAssets(features)
|
||||
|
||||
if (styles) loadCSS(styles)
|
||||
if (scripts) await loadJS(scripts, { getMarkmap: () => markmapView })
|
||||
|
||||
await nextTick()
|
||||
|
||||
const initialExpandLevel = -1
|
||||
|
||||
if (mmInstance) {
|
||||
if (typeof mmInstance.setData === 'function') {
|
||||
await mmInstance.setData(root, { initialExpandLevel, autoFit: false })
|
||||
} else {
|
||||
mmInstance = Markmap.create(svgRef.value, {
|
||||
autoFit: false,
|
||||
fitRatio: 0.9,
|
||||
initialExpandLevel
|
||||
}, root)
|
||||
}
|
||||
} else {
|
||||
mmInstance = Markmap.create(svgRef.value, {
|
||||
autoFit: false,
|
||||
fitRatio: 0.9,
|
||||
initialExpandLevel
|
||||
}, root)
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
svgRef.value?.querySelectorAll('text').forEach((text) => {
|
||||
text.setAttribute('data-editable-node', 'true')
|
||||
})
|
||||
updateNodeStats()
|
||||
await Promise.all(Array.from(svgRef.value?.querySelectorAll('img') || []).map(image => image.decode().catch(() => undefined)))
|
||||
activeDocumentKey = documentKey
|
||||
needsInitialFit = !saved?.camera
|
||||
if (saved?.camera) mmInstance.svg.call(mmInstance.zoom.transform, saved.camera)
|
||||
else if (svgRef.value.getBoundingClientRect().width > 0) { needsInitialFit = false; await mmInstance.fit() }
|
||||
} catch (error) {
|
||||
console.error('Error initializing markmap:', error)
|
||||
mmInstance = null
|
||||
} finally {
|
||||
isRendering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 监听内容变化自动重绘
|
||||
watch([imageContent, () => props.documentKey], () => {
|
||||
window.clearTimeout(renderTimer)
|
||||
renderTimer = window.setTimeout(() => {
|
||||
renderQueue = renderQueue.catch(() => undefined).then(initMarkmap)
|
||||
}, 160)
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
renderQueue = renderQueue.then(initMarkmap)
|
||||
viewportObserver = new ResizeObserver(() => {
|
||||
if (needsInitialFit && mmInstance?.state?.data && svgRef.value && svgRef.value.getBoundingClientRect().width > 0) {
|
||||
needsInitialFit = false
|
||||
void mmInstance.fit()
|
||||
}
|
||||
})
|
||||
if (svgRef.value) viewportObserver.observe(svgRef.value)
|
||||
// 窗口缩放时自动调整导图大小
|
||||
window.addEventListener('resize', handleResize)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
viewportObserver?.disconnect()
|
||||
window.clearTimeout(renderTimer)
|
||||
window.removeEventListener('resize', handleResize)
|
||||
if (mmInstance && typeof mmInstance.destroy === 'function') {
|
||||
mmInstance.destroy()
|
||||
} else if (mmInstance) {
|
||||
console.error('mmInstance does not have destroy method:', mmInstance)
|
||||
}
|
||||
})
|
||||
|
||||
const handleResize = () => {
|
||||
mmInstance?.fit()
|
||||
}
|
||||
|
||||
function downloadBlob(blob: Blob, fileName: string) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = fileName
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
type ExportFormat = 'svg' | 'png' | 'jpeg'
|
||||
|
||||
interface ExportBox {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
function getViewportSize(svg: SVGElement) {
|
||||
const rect = svg.getBoundingClientRect()
|
||||
return {
|
||||
width: Math.ceil(Math.max(rect.width, 320)),
|
||||
height: Math.ceil(Math.max(rect.height, 240))
|
||||
}
|
||||
}
|
||||
|
||||
function cleanExportSvg(svg: SVGElement) {
|
||||
if (!svg.getAttribute('xmlns')) {
|
||||
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
|
||||
}
|
||||
svg.querySelectorAll('[style*="cursor"]').forEach((node) => node.removeAttribute('style'))
|
||||
}
|
||||
|
||||
function getBoxFromSvgRect(rect: DOMRect): ExportBox {
|
||||
return {
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height
|
||||
}
|
||||
}
|
||||
|
||||
function transformBox(box: ExportBox, matrix: DOMMatrix): ExportBox {
|
||||
const points = [
|
||||
new DOMPoint(box.x, box.y).matrixTransform(matrix),
|
||||
new DOMPoint(box.x + box.width, box.y).matrixTransform(matrix),
|
||||
new DOMPoint(box.x, box.y + box.height).matrixTransform(matrix),
|
||||
new DOMPoint(box.x + box.width, box.y + box.height).matrixTransform(matrix)
|
||||
]
|
||||
const xs = points.map((point) => point.x)
|
||||
const ys = points.map((point) => point.y)
|
||||
const minX = Math.min(...xs)
|
||||
const minY = Math.min(...ys)
|
||||
const maxX = Math.max(...xs)
|
||||
const maxY = Math.max(...ys)
|
||||
return {
|
||||
x: minX,
|
||||
y: minY,
|
||||
width: maxX - minX,
|
||||
height: maxY - minY
|
||||
}
|
||||
}
|
||||
|
||||
function getIntersection(a: ExportBox, b: ExportBox): ExportBox | null {
|
||||
const x = Math.max(a.x, b.x)
|
||||
const y = Math.max(a.y, b.y)
|
||||
const right = Math.min(a.x + a.width, b.x + b.width)
|
||||
const bottom = Math.min(a.y + a.height, b.y + b.height)
|
||||
if (right <= x || bottom <= y) return null
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: right - x,
|
||||
height: bottom - y
|
||||
}
|
||||
}
|
||||
|
||||
function padBox(box: ExportBox, padding: number, boundary?: ExportBox): ExportBox {
|
||||
const padded = {
|
||||
x: box.x - padding,
|
||||
y: box.y - padding,
|
||||
width: box.width + padding * 2,
|
||||
height: box.height + padding * 2
|
||||
}
|
||||
|
||||
if (!boundary) return padded
|
||||
const clipped = getIntersection(padded, boundary)
|
||||
return clipped || box
|
||||
}
|
||||
|
||||
function normalizeBox(box: ExportBox): ExportBox {
|
||||
const x = Math.min(box.x, box.x + box.width)
|
||||
const y = Math.min(box.y, box.y + box.height)
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: Math.abs(box.width),
|
||||
height: Math.abs(box.height)
|
||||
}
|
||||
}
|
||||
|
||||
function isCompleteInViewport(contentBox: ExportBox, viewportBox: ExportBox) {
|
||||
const tolerance = 4
|
||||
return (
|
||||
contentBox.x >= viewportBox.x - tolerance &&
|
||||
contentBox.y >= viewportBox.y - tolerance &&
|
||||
contentBox.x + contentBox.width <= viewportBox.x + viewportBox.width + tolerance &&
|
||||
contentBox.y + contentBox.height <= viewportBox.y + viewportBox.height + tolerance
|
||||
)
|
||||
}
|
||||
|
||||
function createFullExportSvg() {
|
||||
const svg = svgRef.value
|
||||
if (!svg) return null
|
||||
|
||||
const svgCopy = svg.cloneNode(true) as SVGElement
|
||||
cleanExportSvg(svgCopy)
|
||||
|
||||
const contentGroup = svg.querySelector('g')
|
||||
const bbox = contentGroup
|
||||
? (contentGroup as SVGGElement).getBBox()
|
||||
: svg.getBBox()
|
||||
|
||||
const padding = 48
|
||||
const width = Math.ceil(Math.max(bbox.width + padding * 2, 320))
|
||||
const height = Math.ceil(Math.max(bbox.height + padding * 2, 240))
|
||||
const viewBox = `${Math.floor(bbox.x - padding)} ${Math.floor(bbox.y - padding)} ${width} ${height}`
|
||||
|
||||
const viewportGroupCopy = svgCopy.querySelector('g')
|
||||
viewportGroupCopy?.removeAttribute('transform')
|
||||
svgCopy.setAttribute('viewBox', viewBox)
|
||||
svgCopy.setAttribute('width', String(width))
|
||||
svgCopy.setAttribute('height', String(height))
|
||||
|
||||
return {
|
||||
data: new XMLSerializer().serializeToString(svgCopy),
|
||||
width,
|
||||
height
|
||||
}
|
||||
}
|
||||
|
||||
function createVisibleExportSvg() {
|
||||
const svg = svgRef.value
|
||||
if (!svg) return null
|
||||
|
||||
const contentGroup = svg.querySelector('g') as SVGGElement | null
|
||||
if (!contentGroup) return createFullExportSvg()
|
||||
|
||||
const viewport = getViewportSize(svg)
|
||||
const viewportBox = { x: 0, y: 0, width: viewport.width, height: viewport.height }
|
||||
const ctm = contentGroup.getCTM()
|
||||
if (!ctm) return createFullExportSvg()
|
||||
|
||||
const contentBox = transformBox(getBoxFromSvgRect(contentGroup.getBBox()), ctm)
|
||||
if (isCompleteInViewport(contentBox, viewportBox)) {
|
||||
return createFullExportSvg()
|
||||
}
|
||||
|
||||
const svgCopy = svg.cloneNode(true) as SVGElement
|
||||
cleanExportSvg(svgCopy)
|
||||
|
||||
const screenVisibleBox = padBox(getIntersection(contentBox, viewportBox) || viewportBox, 24, viewportBox)
|
||||
const localVisibleBox = normalizeBox(transformBox(screenVisibleBox, ctm.inverse()))
|
||||
const localContentBox = getBoxFromSvgRect(contentGroup.getBBox())
|
||||
const clippedLocalBox = getIntersection(localVisibleBox, localContentBox) || localVisibleBox
|
||||
const visibleBox = padBox(clippedLocalBox, 24)
|
||||
const width = Math.ceil(Math.max(visibleBox.width, 320))
|
||||
const height = Math.ceil(Math.max(visibleBox.height, 240))
|
||||
const viewBox = `${Math.floor(visibleBox.x)} ${Math.floor(visibleBox.y)} ${width} ${height}`
|
||||
|
||||
const viewportGroupCopy = svgCopy.querySelector('g')
|
||||
viewportGroupCopy?.removeAttribute('transform')
|
||||
svgCopy.setAttribute('width', String(width))
|
||||
svgCopy.setAttribute('height', String(height))
|
||||
svgCopy.setAttribute('viewBox', viewBox)
|
||||
|
||||
return {
|
||||
data: new XMLSerializer().serializeToString(svgCopy),
|
||||
width,
|
||||
height
|
||||
}
|
||||
}
|
||||
|
||||
// 下载思维导图
|
||||
const downloadMindMap = async (format: ExportFormat = 'svg') => {
|
||||
const exportSvg = createVisibleExportSvg()
|
||||
if (!exportSvg) return
|
||||
exportSvg.data = await embedImages(exportSvg.data)
|
||||
|
||||
const time = new Date().getTime()
|
||||
if (format === 'svg') {
|
||||
downloadBlob(new Blob([exportSvg.data], { type: 'image/svg+xml;charset=utf-8' }), `mindmap_${time}.svg`)
|
||||
return
|
||||
}
|
||||
|
||||
const baseScale = 3
|
||||
const maxResolution = Number(props.exportResolution) || 0
|
||||
const longEdge = Math.max(exportSvg.width, exportSvg.height)
|
||||
const scaleFactor = maxResolution > 0
|
||||
? Math.min(baseScale, Math.max(0.1, maxResolution / longEdge))
|
||||
: baseScale
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
canvas.width = Math.ceil(exportSvg.width * scaleFactor)
|
||||
canvas.height = Math.ceil(exportSvg.height * scaleFactor)
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||
ctx.scale(scaleFactor, scaleFactor)
|
||||
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
ctx.drawImage(img, 0, 0)
|
||||
const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png'
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) return
|
||||
downloadBlob(blob, `mindmap_${time}.${format === 'jpeg' ? 'jpg' : 'png'}`)
|
||||
}, mimeType, 0.96)
|
||||
}
|
||||
img.onerror = () => ElMessage.error('导出图片失败')
|
||||
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(exportSvg.data)
|
||||
}
|
||||
|
||||
// 处理下载命令
|
||||
const handleDownload = (command: string) => {
|
||||
if (!props.content) {
|
||||
ElMessage.warning('暂无思维导图内容可下载')
|
||||
return
|
||||
}
|
||||
if (command === 'svg' || command === 'png' || command === 'jpeg') {
|
||||
downloadMindMap(command)
|
||||
}
|
||||
}
|
||||
|
||||
// 重置视图
|
||||
const resetView = () => {
|
||||
mmInstance?.fit()
|
||||
scale.value = 1
|
||||
window.setTimeout(updateNodeStats, 0)
|
||||
}
|
||||
|
||||
// 放大
|
||||
const zoomIn = () => {
|
||||
if (scale.value < 2) {
|
||||
scale.value += 0.1
|
||||
applyZoom()
|
||||
}
|
||||
}
|
||||
|
||||
// 缩小
|
||||
const zoomOut = () => {
|
||||
if (scale.value > 0.5) {
|
||||
scale.value -= 0.1
|
||||
applyZoom()
|
||||
}
|
||||
}
|
||||
|
||||
// 应用缩放
|
||||
const applyZoom = () => {
|
||||
if (mmInstance && typeof mmInstance.setScale === 'function') {
|
||||
mmInstance.setScale(scale.value)
|
||||
}
|
||||
}
|
||||
|
||||
const handleNodeClick = async (event: MouseEvent) => {
|
||||
if (event.target instanceof HTMLImageElement && event.target.src) { imageViewer.value = event.target.src; return }
|
||||
window.setTimeout(updateNodeStats, 0)
|
||||
const textNode = (event.target as Element | null)?.closest?.('text')
|
||||
const oldText = textNode?.textContent?.trim()
|
||||
const rootText = (props.content.split('\n')[0] || '').replace(/^#\s+/, '').replace(/\\(.)/g, '$1')
|
||||
if (!oldText || !props.content || oldText === rootText) return
|
||||
|
||||
try {
|
||||
const { value } = await ElMessageBox.prompt('编辑节点文本', '编辑思维导图节点', {
|
||||
inputValue: oldText,
|
||||
confirmButtonText: '确认',
|
||||
cancelButtonText: '取消',
|
||||
inputValidator: (value) => Boolean(value.trim()) || '节点文本不能为空'
|
||||
})
|
||||
const newText = String(value).trim()
|
||||
if (newText && newText !== oldText) {
|
||||
emit('node-edit', { oldText, newText })
|
||||
}
|
||||
} catch {
|
||||
// 用户取消编辑
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mindmap-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: transparent;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.content-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mindmap-actions {
|
||||
padding: 0 0 12px;
|
||||
}
|
||||
|
||||
.mindmap-actions-left,
|
||||
.mindmap-actions-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mindmap-actions-left {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.mindmap-actions-right {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.content-toolbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #343A40;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 12px;
|
||||
color: #86909C;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
border-radius: 6px;
|
||||
transition: all 0.3s ease;
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.action-button.primary {
|
||||
background-color: #165DFF;
|
||||
border-color: #165DFF;
|
||||
color: #FFFFFF;
|
||||
}
|
||||
|
||||
.action-button.primary:hover {
|
||||
background-color: #0E42D2;
|
||||
border-color: #0E42D2;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
|
||||
}
|
||||
|
||||
.action-button.secondary {
|
||||
background-color: #FFFFFF;
|
||||
border-color: #C9CDD4;
|
||||
color: #4E5969;
|
||||
}
|
||||
|
||||
.action-button.secondary:hover {
|
||||
border-color: #165DFF;
|
||||
color: #165DFF;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.mindmap-content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
background-color: #F9FAFC;
|
||||
cursor: grab;
|
||||
min-height: 0;
|
||||
border: 1px solid #E9ECEF;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.mindmap-content:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.mindmap-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: #4E5969;
|
||||
background: rgba(249, 250, 252, 0.82);
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.loading-icon {
|
||||
color: #165DFF;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 48px;
|
||||
color: #C9CDD4;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
color: #4E5969;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.empty-subtext {
|
||||
font-size: 14px;
|
||||
color: #86909C;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.markmap-svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.markmap-svg :deep(text[data-editable-node="true"]) {
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.mindmap-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.mindmap-actions-left,
|
||||
.mindmap-actions-right {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.content-toolbar-meta {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
padding: 0 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.mindmap-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,198 +0,0 @@
|
|||
<template>
|
||||
<div class="result-panel">
|
||||
<div class="panel-header" v-if="result">
|
||||
<el-button
|
||||
type="primary"
|
||||
:icon="Download"
|
||||
@click="downloadResult"
|
||||
size="small"
|
||||
class="download-button"
|
||||
>
|
||||
{{ $t('results.download') }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="isProcessing" class="loading-container">
|
||||
<el-spinner :size="64" />
|
||||
<p class="loading-text">处理中...</p>
|
||||
</div>
|
||||
|
||||
<!-- 结果内容 -->
|
||||
<el-tabs v-else v-model="activeTab" class="result-tabs">
|
||||
<el-tab-pane :label="$t('results.tabs.markdown')" name="markdown">
|
||||
<MarkdownRenderer :content="result?.markdown || ''" />
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane :label="$t('results.tabs.source')" name="source">
|
||||
<el-input
|
||||
:model-value="result?.source"
|
||||
type="textarea"
|
||||
:rows="20"
|
||||
readonly
|
||||
class="source-textarea"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane :label="$t('results.tabs.mindmap')" name="mindmap">
|
||||
<MindMapRenderer :content="result?.mindmap || ''" />
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
import type { ProcessResult } from '@/composables/useDocumentProcessor'
|
||||
import MarkdownRenderer from './MarkdownRenderer.vue'
|
||||
import MindMapRenderer from './MindMapRenderer.vue'
|
||||
|
||||
interface Props {
|
||||
result: ProcessResult | null
|
||||
isProcessing: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const activeTab = ref('markdown')
|
||||
|
||||
const downloadResult = () => {
|
||||
if (!props.result?.markdown) return
|
||||
|
||||
const blob = new Blob([props.result.markdown], { type: 'text/markdown' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `result_${new Date().getTime()}.md`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.result-panel {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.download-button {
|
||||
border-radius: 6px;
|
||||
transition: all 0.3s ease;
|
||||
background-color: #165DFF;
|
||||
border-color: #165DFF;
|
||||
}
|
||||
|
||||
.download-button:hover {
|
||||
background-color: #0E42D2;
|
||||
border-color: #0E42D2;
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.result-tabs {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__content) {
|
||||
height: calc(100% - 48px);
|
||||
padding-top: 16px;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tab-pane) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* 极简Tab样式 */
|
||||
.result-tabs :deep(.el-tabs__nav) {
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__item) {
|
||||
height: 48px;
|
||||
line-height: 48px;
|
||||
padding: 0 24px;
|
||||
margin-right: 24px;
|
||||
color: #4E5969;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
position: relative;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__item:hover) {
|
||||
color: #165DFF;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__item.is-active) {
|
||||
color: #165DFF;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__item.is-active::after) {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 2px;
|
||||
background-color: #165DFF;
|
||||
border-radius: 1px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.result-tabs :deep(.el-tabs__active-bar) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.source-textarea {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.source-textarea :deep(.el-textarea__wrapper) {
|
||||
border: 1px solid #C9CDD4;
|
||||
border-radius: 8px;
|
||||
box-shadow: none;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.source-textarea :deep(.el-textarea__wrapper:hover) {
|
||||
border-color: #165DFF;
|
||||
}
|
||||
|
||||
.source-textarea :deep(.el-textarea__inner) {
|
||||
height: 100%;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: #4E5969;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
/* 加载状态 */
|
||||
.loading-container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.loading-text {
|
||||
margin-top: 16px;
|
||||
font-size: 16px;
|
||||
color: #4E5969;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,411 +0,0 @@
|
|||
import { ref, reactive, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
import { documentApi, type ParseParams } from '@/api/document'
|
||||
import { convertWordToPdf, isWordFile } from '@/utils/wordToPdf'
|
||||
import { buildMindmapMarkdown, documentTitleFromName } from '@/utils/mindmapMarkdown'
|
||||
|
||||
// 根据上一级标题自动补全下一级标题
|
||||
export function autoPromoteParagraphsToSubheading(text: string): string {
|
||||
return buildMindmapMarkdown(text)
|
||||
}
|
||||
|
||||
export interface DocumentConfig {
|
||||
maxPages: number
|
||||
backend: string
|
||||
serverUrl: string
|
||||
exportResolution: number
|
||||
mindmapPrompt: string
|
||||
parserResourceId: string
|
||||
mindmapModelId: string
|
||||
mindmapLlmTimeout: number
|
||||
mindmapLlmTemperature: number
|
||||
mindmapLlmMaxContextTokens: number
|
||||
mindmapLlmMaxOutputTokens: number
|
||||
mindmapLlmSafetyTokens: number
|
||||
tableEnable: boolean
|
||||
formulaEnable: boolean
|
||||
language: string
|
||||
forceOcr: boolean
|
||||
}
|
||||
|
||||
export interface ProcessResult {
|
||||
markdown: string
|
||||
source: string
|
||||
mindmap: string
|
||||
downloadUrl?: string
|
||||
}
|
||||
|
||||
export const DOCUMENT_CONFIG_STORAGE_KEY = 'mineru.documentProcessor.config.v4'
|
||||
|
||||
export const DEFAULT_MINDMAP_PROMPT = `你是文档结构整理助手。请基于用户提供的 Markdown 生成适合思维导图展示的 Markdown。
|
||||
|
||||
要求:
|
||||
1. 保留原文标题结构,不要重写或打乱主要标题层级。
|
||||
2. 将标题下的段落内容总结为要点,合并相近段落,避免逐段照抄。
|
||||
3. 保留原文语言:英文内容输出英文,中文内容输出中文,多语言内容按原文语言分别保留。
|
||||
4. 不要编造原文没有的信息。
|
||||
5. 保留关键数字、公式、专有名词、步骤和结论。
|
||||
6. 最大层级不超过 4 层。
|
||||
7. 每个父节点下最多 8 个子节点。
|
||||
8. 节点标题尽量简短,正文说明使用短句列表。
|
||||
9. 只输出 Markdown,不要输出解释、代码块围栏或额外说明。`
|
||||
|
||||
export const DEFAULT_DOCUMENT_CONFIG: DocumentConfig = {
|
||||
maxPages: 1000,
|
||||
backend: 'hybrid-auto-engine',
|
||||
serverUrl: 'http://localhost:30000',
|
||||
exportResolution: 7680,
|
||||
mindmapPrompt: DEFAULT_MINDMAP_PROMPT,
|
||||
parserResourceId: '',
|
||||
mindmapModelId: '',
|
||||
mindmapLlmTimeout: 180,
|
||||
mindmapLlmTemperature: 0.2,
|
||||
mindmapLlmMaxContextTokens: 32768,
|
||||
mindmapLlmMaxOutputTokens: 4096,
|
||||
mindmapLlmSafetyTokens: 1024,
|
||||
tableEnable: true,
|
||||
formulaEnable: true,
|
||||
language: 'ch',
|
||||
forceOcr: false
|
||||
}
|
||||
|
||||
function loadCachedConfig(): Partial<DocumentConfig> {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(DOCUMENT_CONFIG_STORAGE_KEY)
|
||||
const cached = raw ? JSON.parse(raw) : {}
|
||||
const safe = Object.fromEntries(Object.keys(DEFAULT_DOCUMENT_CONFIG).filter(key => key in cached).map(key => [key, cached[key]]))
|
||||
window.localStorage.setItem(DOCUMENT_CONFIG_STORAGE_KEY, JSON.stringify(safe))
|
||||
return safe
|
||||
} catch {
|
||||
try { window.localStorage.removeItem(DOCUMENT_CONFIG_STORAGE_KEY) } catch { /* Storage unavailable. */ }
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function useDocumentProcessor() {
|
||||
// 文件相关
|
||||
const uploadedFiles: Ref<File[]> = ref([])
|
||||
const uploadedDisplayFiles: Ref<File[]> = ref([])
|
||||
const isUploading = ref(false)
|
||||
|
||||
// 配置相关
|
||||
const config = reactive<DocumentConfig>({
|
||||
...DEFAULT_DOCUMENT_CONFIG,
|
||||
...loadCachedConfig()
|
||||
})
|
||||
|
||||
watch(
|
||||
config,
|
||||
(value) => {
|
||||
try {
|
||||
window.localStorage.setItem(DOCUMENT_CONFIG_STORAGE_KEY, JSON.stringify(value))
|
||||
} catch {
|
||||
// 浏览器禁用本地存储时不影响当前页面使用。
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
// 结果相关
|
||||
const results = ref<ProcessResult | null>(null)
|
||||
const isProcessing = ref(false)
|
||||
const processingStage = ref('')
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// 后端选项
|
||||
const backendOptions = [
|
||||
{ value: 'pipeline', label: '传统管道解析' },
|
||||
{ value: 'vlm-auto-engine', label: 'VLM本地引擎' },
|
||||
{ value: 'hybrid-auto-engine', label: '混合本地引擎' },
|
||||
{ value: 'vlm-http-client', label: 'VLM远程客户端' },
|
||||
{ value: 'hybrid-http-client', label: '混合远程客户端' }
|
||||
]
|
||||
|
||||
// 语言选项
|
||||
const languageOptions = [
|
||||
{ value: 'ch', label: '中文(简体)' },
|
||||
{ value: 'en', label: '英语' },
|
||||
{ value: 'korean', label: '韩语' },
|
||||
{ value: 'japan', label: '日语' },
|
||||
{ value: 'chinese_cht', label: '中文(繁体)' },
|
||||
{ value: 'ta', label: '泰米尔语' },
|
||||
{ value: 'te', label: '泰卢固语' },
|
||||
{ value: 'ka', label: '卡纳达语' },
|
||||
{ value: 'th', label: '泰语' },
|
||||
{ value: 'el', label: '希腊语' },
|
||||
{ value: 'latin', label: '拉丁语系' },
|
||||
{ value: 'arabic', label: '阿拉伯语系' },
|
||||
{ value: 'east_slavic', label: '东斯拉夫语系' },
|
||||
{ value: 'cyrillic', label: '西里尔语系' },
|
||||
{ value: 'devanagari', label: '梵文字母语系' }
|
||||
]
|
||||
|
||||
// 文件上传处理
|
||||
const handleFileUpload = async (files: FileList | null) => {
|
||||
console.log('handleFileUpload called with files:', files)
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const validFiles: File[] = []
|
||||
const displayFiles: File[] = []
|
||||
const file = files[0]
|
||||
uploadedFiles.value = []
|
||||
uploadedDisplayFiles.value = []
|
||||
results.value = null
|
||||
error.value = null
|
||||
if (files.length > 1) {
|
||||
error.value = '一次只能选择一个文件,已使用第一个文件'
|
||||
}
|
||||
|
||||
const fileType = file.type
|
||||
const fileName = file.name.toLowerCase()
|
||||
|
||||
console.log('Processing file:', fileName, 'type:', fileType)
|
||||
|
||||
// 验证文件类型 - 支持 Markdown、PDF、Word 和后端可转换为 PDF 的图片格式
|
||||
const supportedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff', '.gif', '.jp2']
|
||||
const isImage = fileType.startsWith('image/') && supportedImageExtensions.some((ext) => fileName.endsWith(ext))
|
||||
const isPdf = fileType === 'application/pdf'
|
||||
const isWord = fileName.endsWith('.docx') || fileName.endsWith('.doc') || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
const isMarkdown = fileName.endsWith('.md') || fileType === 'text/markdown'
|
||||
|
||||
console.log('File type checks - isImage:', isImage, 'isPdf:', isPdf, 'isWord:', isWord, 'isMarkdown:', isMarkdown)
|
||||
|
||||
if (!isImage && !isPdf && !isWord && !isMarkdown) {
|
||||
error.value = '不支持的文件类型,请选择 MD、PDF、Word、JPG、PNG、WEBP、BMP、TIFF、GIF 或 JP2 文件'
|
||||
console.log('Unsupported file type:', fileName, fileType)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证文件大小 (100MB)
|
||||
if (file.size > 100 * 1024 * 1024) {
|
||||
error.value = '文件大小超出限制'
|
||||
console.log('File too large:', fileName, file.size)
|
||||
return
|
||||
}
|
||||
|
||||
if (isMarkdown) {
|
||||
try {
|
||||
isUploading.value = true
|
||||
const markdown = await file.text()
|
||||
validFiles.push(file)
|
||||
displayFiles.push(file)
|
||||
results.value = {
|
||||
markdown,
|
||||
source: markdown,
|
||||
mindmap: buildMindmapMarkdown(markdown, documentTitleFromName(file.name))
|
||||
}
|
||||
error.value = null
|
||||
console.log('Markdown file loaded directly:', fileName, markdown.length)
|
||||
} catch (err) {
|
||||
error.value = 'Markdown 文件读取失败: ' + (err as Error).message
|
||||
console.error('Markdown read failed:', (err as Error).message)
|
||||
return
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
} else if (isWord) {
|
||||
try {
|
||||
isUploading.value = true
|
||||
error.value = '正在将 Word 文档转换为 PDF...'
|
||||
console.log('Converting Word to PDF:', fileName)
|
||||
const pdfFile = await convertWordToPdf(file)
|
||||
console.log('Conversion successful, PDF file:', pdfFile.name, pdfFile.size)
|
||||
validFiles.push(pdfFile)
|
||||
displayFiles.push(file)
|
||||
error.value = null
|
||||
} catch (err) {
|
||||
error.value = 'Word 转换为 PDF 失败: ' + (err as Error).message
|
||||
console.error('Conversion failed:', (err as Error).message)
|
||||
return
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
} else {
|
||||
validFiles.push(file)
|
||||
displayFiles.push(file)
|
||||
console.log('Adding file directly:', fileName)
|
||||
}
|
||||
|
||||
uploadedFiles.value = validFiles
|
||||
uploadedDisplayFiles.value = displayFiles
|
||||
console.log('Final uploaded files:', validFiles.map(f => f.name))
|
||||
}
|
||||
|
||||
// 清除所有数据
|
||||
const clearAll = () => {
|
||||
uploadedFiles.value = []
|
||||
uploadedDisplayFiles.value = []
|
||||
results.value = null
|
||||
error.value = null
|
||||
processingStage.value = ''
|
||||
}
|
||||
|
||||
// 演示模式:上传文件后由用户手动粘贴 Markdown 源码
|
||||
const initializeManualResult = () => {
|
||||
results.value = {
|
||||
markdown: '',
|
||||
source: '',
|
||||
mindmap: ''
|
||||
}
|
||||
error.value = null
|
||||
}
|
||||
|
||||
// 进度相关
|
||||
const progressPercent = ref<number | null>(null)
|
||||
const progressStage = ref('')
|
||||
const progressElapsedLabel = ref('')
|
||||
let progressStartedAt = 0
|
||||
let progressTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
// 启动进度轮询
|
||||
const startProgressPolling = (taskId: string) => {
|
||||
stopProgressPolling()
|
||||
progressPercent.value = null
|
||||
progressStartedAt = Date.now()
|
||||
progressElapsedLabel.value = '已用时 0 秒'
|
||||
progressStage.value = '准备中'
|
||||
progressTimer = setInterval(async () => {
|
||||
const elapsed = Math.floor((Date.now() - progressStartedAt) / 1000)
|
||||
progressElapsedLabel.value = elapsed < 60 ? `已用时 ${elapsed} 秒` : `已用时 ${Math.floor(elapsed / 60)} 分 ${elapsed % 60} 秒`
|
||||
try {
|
||||
const data = await documentApi.getParseProgress(taskId)
|
||||
progressPercent.value = data.progress
|
||||
progressStage.value = data.stage
|
||||
if (data.status === 'completed' || data.status === 'failed') {
|
||||
stopProgressPolling()
|
||||
}
|
||||
} catch {
|
||||
// 忽略轮询失败
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
// 停止进度轮询
|
||||
const stopProgressPolling = () => {
|
||||
if (progressTimer) {
|
||||
clearInterval(progressTimer)
|
||||
progressTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
// 处理文档转换
|
||||
const processDocument = async () => {
|
||||
if (uploadedFiles.value.length === 0) {
|
||||
error.value = '请先上传文件'
|
||||
return
|
||||
}
|
||||
|
||||
const firstFileName = uploadedFiles.value[0]?.name.toLowerCase() || ''
|
||||
if (firstFileName.endsWith('.md')) {
|
||||
if (!results.value) {
|
||||
error.value = 'Markdown 文件内容为空,请重新上传'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
isProcessing.value = true
|
||||
error.value = null
|
||||
processingStage.value = '准备提交解析任务'
|
||||
|
||||
// 生成任务ID
|
||||
const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
|
||||
try {
|
||||
await documentApi.createParseTask(taskId)
|
||||
startProgressPolling(taskId)
|
||||
processingStage.value = '提交文档到解析服务'
|
||||
const params: ParseParams = {
|
||||
files: uploadedFiles.value,
|
||||
parser_resource_id: config.parserResourceId,
|
||||
output_dir: './output',
|
||||
lang_list: config.language,
|
||||
backend: config.backend,
|
||||
parse_method: config.forceOcr ? 'ocr' : 'auto',
|
||||
formula_enable: config.formulaEnable,
|
||||
table_enable: config.tableEnable,
|
||||
start_page_id: 0,
|
||||
end_page_id: config.maxPages - 1,
|
||||
return_md: true,
|
||||
return_middle_json: false,
|
||||
response_format_zip: false
|
||||
}
|
||||
|
||||
if (config.backend.includes('http-client') && config.serverUrl) {
|
||||
params.server_url = config.serverUrl
|
||||
}
|
||||
|
||||
processingStage.value = '服务端正在解析文档'
|
||||
const response = await documentApi.parseDocument(params, taskId)
|
||||
|
||||
if (response.results) {
|
||||
processingStage.value = '生成 Markdown 和思维导图'
|
||||
const resultData = Object.values(response.results)[0]
|
||||
const mdContent = resultData.md_content || ''
|
||||
const mindmapContent = buildMindmapMarkdown(mdContent, documentTitleFromName(uploadedDisplayFiles.value[0]?.name || ''))
|
||||
results.value = {
|
||||
markdown: mdContent,
|
||||
source: mdContent,
|
||||
mindmap: mindmapContent
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err: any) {
|
||||
error.value = err.message || '转换失败'
|
||||
} finally {
|
||||
stopProgressPolling()
|
||||
processingStage.value = ''
|
||||
isProcessing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 根据后端类型获取公式标签
|
||||
const getFormulaLabel = (backend: string) => {
|
||||
if (backend.startsWith('vlm')) {
|
||||
return '启用行间公式识别'
|
||||
} else if (backend === 'pipeline') {
|
||||
return '启用公式识别'
|
||||
} else if (backend.startsWith('hybrid')) {
|
||||
return '启用行内公式识别'
|
||||
}
|
||||
return '启用公式识别'
|
||||
}
|
||||
|
||||
// 根据后端类型获取公式说明
|
||||
const getFormulaInfo = (backend: string) => {
|
||||
if (backend.startsWith('vlm')) {
|
||||
return '禁用后,行间公式将显示为图片。'
|
||||
} else if (backend === 'pipeline') {
|
||||
return '禁用后,行间公式将显示为图片,行内公式将不会被检测或解析。'
|
||||
} else if (backend.startsWith('hybrid')) {
|
||||
return '禁用后,行内公式将不会被检测或解析。'
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
return {
|
||||
// 数据
|
||||
uploadedFiles,
|
||||
uploadedDisplayFiles,
|
||||
config,
|
||||
results,
|
||||
isUploading,
|
||||
isProcessing,
|
||||
processingStage,
|
||||
progressPercent,
|
||||
progressStage,
|
||||
progressElapsedLabel,
|
||||
error,
|
||||
|
||||
// 选项
|
||||
backendOptions,
|
||||
languageOptions,
|
||||
|
||||
// 方法
|
||||
handleFileUpload,
|
||||
initializeManualResult,
|
||||
clearAll,
|
||||
processDocument,
|
||||
getFormulaLabel,
|
||||
getFormulaInfo
|
||||
}
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
export default {
|
||||
app: {
|
||||
title: 'Multimodal Mind Map Assistant'
|
||||
},
|
||||
common: {
|
||||
upload: 'Upload',
|
||||
clear: 'Clear',
|
||||
convert: 'Convert',
|
||||
cancel: 'Cancel',
|
||||
confirm: 'Confirm',
|
||||
loading: 'Loading...',
|
||||
success: 'Success',
|
||||
error: 'Error',
|
||||
warning: 'Warning'
|
||||
},
|
||||
upload: {
|
||||
title: 'Please upload PDF or image',
|
||||
placeholder: 'Click to upload or drag files here',
|
||||
supportedTypes: 'Supported file types: PDF, PNG, JPG, JPEG',
|
||||
maxSize: 'Maximum file size: 100MB'
|
||||
},
|
||||
config: {
|
||||
title: 'Configuration Options',
|
||||
maxPages: 'Max convert pages',
|
||||
backend: 'Backend',
|
||||
serverUrl: 'Server URL',
|
||||
serverUrlInfo: 'OpenAI-compatible server URL for http-client backend.',
|
||||
recognitionOptions: 'Recognition Options',
|
||||
tableEnable: 'Enable table recognition',
|
||||
tableInfo: 'If disabled, tables will be shown as images.',
|
||||
formulaLabelVlm: 'Enable display formula recognition',
|
||||
formulaLabelPipeline: 'Enable formula recognition',
|
||||
formulaLabelHybrid: 'Enable inline formula recognition',
|
||||
formulaInfoVlm: 'If disabled, display formulas will be shown as images.',
|
||||
formulaInfoPipeline: 'If disabled, display formulas will be shown as images, and inline formulas will not be detected or parsed.',
|
||||
formulaInfoHybrid: 'If disabled, inline formulas will not be detected or parsed.',
|
||||
ocrLanguage: 'OCR Language',
|
||||
ocrLanguageInfo: 'Select the OCR language for image-based PDFs and images.',
|
||||
forceOcr: 'Force enable OCR',
|
||||
forceOcrInfo: 'Enable only if the result is extremely poor. Requires correct OCR language.',
|
||||
backendInfoVlm: 'High-precision parsing via VLM, supports Chinese and English documents only.',
|
||||
backendInfoPipeline: 'Traditional Multi-model pipeline parsing, supports multiple languages, hallucination-free.',
|
||||
backendInfoHybrid: 'High-precision hybrid parsing, supports multiple languages.',
|
||||
backendInfoDefault: 'Select the backend engine for document parsing.'
|
||||
},
|
||||
results: {
|
||||
title: 'Convert Result',
|
||||
tabs: {
|
||||
markdown: 'Markdown Rendering',
|
||||
source: 'Markdown Source',
|
||||
mindmap: 'Mind Map'
|
||||
},
|
||||
download: 'Download Result',
|
||||
noResults: 'No conversion results yet'
|
||||
},
|
||||
languages: {
|
||||
ch: 'Chinese (Simplified)',
|
||||
en: 'English',
|
||||
korean: 'Korean',
|
||||
japan: 'Japanese',
|
||||
chinese_cht: 'Chinese (Traditional)',
|
||||
ta: 'Tamil',
|
||||
te: 'Telugu',
|
||||
ka: 'Kannada',
|
||||
th: 'Thai',
|
||||
el: 'Greek',
|
||||
latin: 'Latin Languages',
|
||||
arabic: 'Arabic Languages',
|
||||
east_slavic: 'East Slavic Languages',
|
||||
cyrillic: 'Cyrillic Languages',
|
||||
devanagari: 'Devanagari Languages'
|
||||
},
|
||||
backends: {
|
||||
pipeline: 'Traditional Pipeline Parsing',
|
||||
'vlm-auto-engine': 'VLM Local Engine',
|
||||
'hybrid-auto-engine': 'Hybrid Local Engine',
|
||||
'vlm-http-client': 'VLM Remote Client',
|
||||
'hybrid-http-client': 'Hybrid Remote Client'
|
||||
},
|
||||
errors: {
|
||||
uploadFailed: 'File upload failed',
|
||||
conversionFailed: 'Conversion failed',
|
||||
invalidFileType: 'Unsupported file type',
|
||||
fileSizeExceeded: 'File size exceeded limit',
|
||||
networkError: 'Network connection error'
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
export { default as zh } from './zh'
|
||||
export { default as en } from './en'
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
export default {
|
||||
app: {
|
||||
title: '多模态思维导图助手'
|
||||
},
|
||||
common: {
|
||||
upload: '上传',
|
||||
clear: '清除',
|
||||
convert: '转换',
|
||||
cancel: '取消',
|
||||
confirm: '确定',
|
||||
loading: '加载中...',
|
||||
success: '成功',
|
||||
error: '错误',
|
||||
warning: '警告'
|
||||
},
|
||||
upload: {
|
||||
title: '请上传 PDF 或图片',
|
||||
placeholder: '点击上传或将文件拖拽到此处',
|
||||
supportedTypes: '支持的文件类型: PDF, PNG, JPG, JPEG',
|
||||
maxSize: '最大文件大小: 100MB'
|
||||
},
|
||||
config: {
|
||||
title: '配置选项',
|
||||
maxPages: '最大转换页数',
|
||||
backend: '解析后端',
|
||||
serverUrl: '服务器地址',
|
||||
serverUrlInfo: 'http-client 后端的 OpenAI 兼容服务器地址。',
|
||||
recognitionOptions: '识别选项',
|
||||
tableEnable: '启用表格识别',
|
||||
tableInfo: '禁用后,表格将显示为图片。',
|
||||
formulaLabelVlm: '启用行间公式识别',
|
||||
formulaLabelPipeline: '启用公式识别',
|
||||
formulaLabelHybrid: '启用行内公式识别',
|
||||
formulaInfoVlm: '禁用后,行间公式将显示为图片。',
|
||||
formulaInfoPipeline: '禁用后,行间公式将显示为图片,行内公式将不会被检测或解析。',
|
||||
formulaInfoHybrid: '禁用后,行内公式将不会被检测或解析。',
|
||||
ocrLanguage: 'OCR 语言',
|
||||
ocrLanguageInfo: '为扫描版 PDF 和图片选择 OCR 语言。',
|
||||
forceOcr: '强制启用 OCR',
|
||||
forceOcrInfo: '仅在识别效果极差时启用,需选择正确的 OCR 语言。',
|
||||
backendInfoVlm: '多模态大模型高精度解析,仅支持中英文文档。',
|
||||
backendInfoPipeline: '传统多模型管道解析,支持多语言,无幻觉。',
|
||||
backendInfoHybrid: '高精度混合解析,支持多语言。',
|
||||
backendInfoDefault: '选择文档解析的后端引擎。'
|
||||
},
|
||||
results: {
|
||||
title: '转换结果',
|
||||
tabs: {
|
||||
markdown: 'Markdown 渲染',
|
||||
source: 'Markdown 源码',
|
||||
mindmap: '思维导图'
|
||||
},
|
||||
download: '下载结果',
|
||||
noResults: '暂无转换结果'
|
||||
},
|
||||
languages: {
|
||||
ch: '中文(简体)',
|
||||
en: '英语',
|
||||
korean: '韩语',
|
||||
japan: '日语',
|
||||
chinese_cht: '中文(繁体)',
|
||||
ta: '泰米尔语',
|
||||
te: '泰卢固语',
|
||||
ka: '卡纳达语',
|
||||
th: '泰语',
|
||||
el: '希腊语',
|
||||
latin: '拉丁语系',
|
||||
arabic: '阿拉伯语系',
|
||||
east_slavic: '东斯拉夫语系',
|
||||
cyrillic: '西里尔语系',
|
||||
devanagari: '梵文字母语系'
|
||||
},
|
||||
backends: {
|
||||
pipeline: '传统管道解析',
|
||||
'vlm-auto-engine': 'VLM本地引擎',
|
||||
'hybrid-auto-engine': '混合本地引擎',
|
||||
'vlm-http-client': 'VLM远程客户端',
|
||||
'hybrid-http-client': '混合远程客户端'
|
||||
},
|
||||
errors: {
|
||||
uploadFailed: '文件上传失败',
|
||||
conversionFailed: '转换失败',
|
||||
invalidFileType: '不支持的文件类型',
|
||||
fileSizeExceeded: '文件大小超出限制',
|
||||
networkError: '网络连接错误'
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import App from './App.vue'
|
||||
import { zh, en } from './locales'
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: navigator.language.includes('zh') ? 'zh' : 'en',
|
||||
fallbackLocale: 'en',
|
||||
messages: {
|
||||
zh,
|
||||
en
|
||||
}
|
||||
})
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(ElementPlus)
|
||||
app.use(i18n)
|
||||
app.mount('#app')
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
import { onBeforeUnmount, ref, watch, type Ref } from 'vue'
|
||||
import { hubCall } from '@/api/hub'
|
||||
|
||||
const pattern = () => /\/admin\/api\/workspace\/[^/\s"<>]+\/ai_hub\/assets\/([a-f0-9-]{36})\/content/g
|
||||
const cache = new Map<string, Blob>()
|
||||
const pending = new Map<string, Promise<Blob>>()
|
||||
let cachedBytes = 0
|
||||
|
||||
async function imageBlob(url: string, id: string) {
|
||||
if (cache.has(url)) return cache.get(url)!
|
||||
if (pending.has(url)) return pending.get(url)!
|
||||
const request = hubCall('assets', 'get', undefined, id).then(result => {
|
||||
if (!(result.content instanceof ArrayBuffer) || !/^image\/(png|jpeg|gif|webp|bmp)$/.test(result.mime)) throw new Error('图片加载失败')
|
||||
const blob = new Blob([result.content], { type: result.mime })
|
||||
while (cache.size && cachedBytes + blob.size > 64 * 1024 * 1024) {
|
||||
const oldest = cache.keys().next().value!
|
||||
cachedBytes -= cache.get(oldest)!.size
|
||||
cache.delete(oldest)
|
||||
}
|
||||
cache.set(url, blob); cachedBytes += blob.size
|
||||
return blob
|
||||
}).finally(() => pending.delete(url))
|
||||
pending.set(url, request)
|
||||
return request
|
||||
}
|
||||
|
||||
export function hasImageAssets(content: string) { return pattern().test(content) }
|
||||
|
||||
async function replaceAssets(content: string, convert: (blob: Blob) => Promise<string> | string) {
|
||||
const replacements = new Map<string, string>()
|
||||
for (const match of content.matchAll(pattern())) {
|
||||
if (!replacements.has(match[0])) replacements.set(match[0], await convert(await imageBlob(match[0], match[1])))
|
||||
}
|
||||
return content.replace(pattern(), url => replacements.get(url)!)
|
||||
}
|
||||
|
||||
export function useImageAssets(source: () => string): { content: Ref<string>; error: Ref<string>; retry: () => void } {
|
||||
const content = ref(''), error = ref(''), revision = ref(0)
|
||||
let generation = 0, urls: string[] = []
|
||||
watch([source, revision], async ([value]) => {
|
||||
const current = ++generation, nextUrls: string[] = []
|
||||
error.value = ''
|
||||
try {
|
||||
const resolved = await replaceAssets(String(value), blob => {
|
||||
const url = URL.createObjectURL(blob); nextUrls.push(url); return url
|
||||
})
|
||||
if (current === generation) {
|
||||
const previous = urls; urls = nextUrls; content.value = resolved
|
||||
// Give both Vue and markmap time to detach the previous DOM.
|
||||
window.setTimeout(() => previous.forEach(url => URL.revokeObjectURL(url)), 1000)
|
||||
} else nextUrls.forEach(url => URL.revokeObjectURL(url))
|
||||
} catch {
|
||||
nextUrls.forEach(url => URL.revokeObjectURL(url))
|
||||
if (current === generation) {
|
||||
content.value = String(value).replace(pattern(), '')
|
||||
error.value = '图片加载失败,点击重试'
|
||||
}
|
||||
}
|
||||
}, { immediate: true })
|
||||
onBeforeUnmount(() => { generation++; urls.forEach(url => URL.revokeObjectURL(url)) })
|
||||
return { content, error, retry: () => revision.value++ }
|
||||
}
|
||||
|
||||
export function blobDataUrl(blob: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result))
|
||||
reader.onerror = () => reject(new Error('图片读取失败'))
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
// Standalone HTML and SVG must not contain browser-session Blob URLs.
|
||||
export async function embedImages(html: string) {
|
||||
const document = new DOMParser().parseFromString(html, 'text/html')
|
||||
for (const image of Array.from(document.querySelectorAll('img'))) {
|
||||
if (image.src.startsWith('blob:')) image.setAttribute('src', await blobDataUrl(await (await fetch(image.src)).blob()))
|
||||
}
|
||||
return document.body.innerHTML
|
||||
}
|
||||
|
||||
export async function exportMarkdownBundle(markdown: string) {
|
||||
const result = await hubCall('exports', 'post', { markdown })
|
||||
if (!(result.content instanceof ArrayBuffer) || result.mime !== 'application/zip') throw new Error('导出失败')
|
||||
return new Blob([result.content], { type: result.mime })
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
import MarkdownIt from 'markdown-it'
|
||||
import type Token from 'markdown-it/lib/token.mjs'
|
||||
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
breaks: true
|
||||
})
|
||||
|
||||
type AstNode = {
|
||||
type: string
|
||||
tag?: string
|
||||
nesting?: number
|
||||
level?: number
|
||||
content?: string
|
||||
markup?: string
|
||||
info?: string
|
||||
block?: boolean
|
||||
hidden?: boolean
|
||||
map?: number[] | null
|
||||
attrs?: Record<string, string>
|
||||
children?: AstNode[]
|
||||
}
|
||||
|
||||
function tokenToAstNode(token: Token): AstNode {
|
||||
return {
|
||||
type: token.type,
|
||||
tag: token.tag || undefined,
|
||||
nesting: token.nesting,
|
||||
level: token.level,
|
||||
content: token.content || undefined,
|
||||
markup: token.markup || undefined,
|
||||
info: token.info || undefined,
|
||||
block: token.block,
|
||||
hidden: token.hidden,
|
||||
map: token.map || null,
|
||||
attrs: token.attrs ? Object.fromEntries(token.attrs) : undefined,
|
||||
children: token.children?.map(tokenToAstNode)
|
||||
}
|
||||
}
|
||||
|
||||
export function markdownToAstString(markdown: string): string {
|
||||
if (!markdown.trim()) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const tokens = md.parse(markdown, {})
|
||||
const ast = {
|
||||
type: 'root',
|
||||
children: tokens.map(tokenToAstNode)
|
||||
}
|
||||
|
||||
return JSON.stringify(ast, null, 2)
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
export interface ReplacementRule {
|
||||
id: string
|
||||
search: string
|
||||
replace: string
|
||||
}
|
||||
|
||||
export interface MarkdownTemplateRenderResult {
|
||||
markdown: string
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export function createEmptyReplacementRule(): ReplacementRule {
|
||||
return {
|
||||
id: `${Date.now()}_${Math.random().toString(16).slice(2)}`,
|
||||
search: '',
|
||||
replace: ''
|
||||
}
|
||||
}
|
||||
|
||||
export function renderMarkdownTemplate(template: string, rules: ReplacementRule[]): MarkdownTemplateRenderResult {
|
||||
if (!template.trim()) {
|
||||
return {
|
||||
markdown: '',
|
||||
error: null
|
||||
}
|
||||
}
|
||||
|
||||
const activeRules = rules.filter((rule) => rule.search.trim())
|
||||
|
||||
try {
|
||||
const markdown = activeRules.reduce((current, rule) => {
|
||||
return current.split(rule.search).join(rule.replace)
|
||||
}, template)
|
||||
|
||||
return {
|
||||
markdown,
|
||||
error: null
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
markdown: template,
|
||||
error: `替换规则执行失败:${(error as Error).message}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
import MarkdownIt from 'markdown-it'
|
||||
import type Token from 'markdown-it/lib/token.mjs'
|
||||
|
||||
const ROOT_TITLE = '文档思维导图'
|
||||
const MAX_HEADING_LEVEL = 6
|
||||
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
breaks: true
|
||||
})
|
||||
|
||||
function normalizeNodeText(text: string) {
|
||||
return text
|
||||
.replace(/\r?\n/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function clampHeadingLevel(level: number) {
|
||||
return Math.min(Math.max(level, 1), MAX_HEADING_LEVEL)
|
||||
}
|
||||
|
||||
function pushHeading(result: string[], level: number, text: string) {
|
||||
const normalized = normalizeNodeText(text)
|
||||
if (!normalized) return
|
||||
result.push(`${'#'.repeat(clampHeadingLevel(level))} ${normalized}`)
|
||||
}
|
||||
|
||||
function getHeadingLevel(token: Token) {
|
||||
const tagLevel = Number(token.tag.replace(/^h/i, ''))
|
||||
return Number.isFinite(tagLevel) && tagLevel > 0 ? tagLevel : 1
|
||||
}
|
||||
|
||||
function getNextInlineContent(tokens: Token[], index: number) {
|
||||
const next = tokens[index + 1]
|
||||
return next?.type === 'inline' ? next.content : ''
|
||||
}
|
||||
|
||||
function getFenceContent(token: Token) {
|
||||
const info = normalizeNodeText(token.info || '')
|
||||
const content = token.content.trim()
|
||||
if (!content) return info ? `代码块 ${info}` : '代码块'
|
||||
return info ? `代码块 ${info}: ${content}` : `代码块: ${content}`
|
||||
}
|
||||
|
||||
function collectTableRows(tokens: Token[], startIndex: number) {
|
||||
const rows: string[][] = []
|
||||
let currentRow: string[] | null = null
|
||||
let endIndex = startIndex
|
||||
|
||||
for (let i = startIndex + 1; i < tokens.length; i += 1) {
|
||||
const token = tokens[i]
|
||||
endIndex = i
|
||||
|
||||
if (token.type === 'table_close') break
|
||||
if (token.type === 'tr_open') {
|
||||
currentRow = []
|
||||
continue
|
||||
}
|
||||
if (token.type === 'tr_close') {
|
||||
if (currentRow && currentRow.some((cell) => cell.trim())) {
|
||||
rows.push(currentRow)
|
||||
}
|
||||
currentRow = null
|
||||
continue
|
||||
}
|
||||
if ((token.type === 'th_open' || token.type === 'td_open') && currentRow) {
|
||||
currentRow.push(getNextInlineContent(tokens, i))
|
||||
}
|
||||
}
|
||||
|
||||
return { rows, endIndex }
|
||||
}
|
||||
|
||||
export function documentTitleFromName(name: string) {
|
||||
return name.replace(/\.[^.\\/]+$/, '').trim() || ROOT_TITLE
|
||||
}
|
||||
|
||||
export function buildMindmapMarkdown(markdown: string, title = ROOT_TITLE) {
|
||||
if (!markdown.trim()) return ''
|
||||
|
||||
const tokens = md.parse(markdown, {})
|
||||
const rootTitle = normalizeNodeText(title).replace(/([\\`*{}\[\]()#+.!_<>])/g, '\\$1')
|
||||
const result: string[] = [`# ${rootTitle || ROOT_TITLE}`]
|
||||
let currentHeadingLevel = 1
|
||||
let listDepth = 0
|
||||
|
||||
for (let i = 0; i < tokens.length; i += 1) {
|
||||
const token = tokens[i]
|
||||
|
||||
if (token.type === 'heading_open') {
|
||||
currentHeadingLevel = clampHeadingLevel(getHeadingLevel(token) + 1)
|
||||
pushHeading(result, currentHeadingLevel, getNextInlineContent(tokens, i) || '未命名章节')
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'bullet_list_open' || token.type === 'ordered_list_open') {
|
||||
listDepth += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'bullet_list_close' || token.type === 'ordered_list_close') {
|
||||
listDepth = Math.max(0, listDepth - 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'paragraph_open') {
|
||||
const level = currentHeadingLevel + Math.max(listDepth, 1)
|
||||
pushHeading(result, level, getNextInlineContent(tokens, i))
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'fence' || token.type === 'code_block') {
|
||||
pushHeading(result, currentHeadingLevel + 1, getFenceContent(token))
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'html_block') {
|
||||
pushHeading(result, currentHeadingLevel + 1, token.content)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'blockquote_open') {
|
||||
pushHeading(result, currentHeadingLevel + 1, '引用')
|
||||
currentHeadingLevel = clampHeadingLevel(currentHeadingLevel + 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'blockquote_close') {
|
||||
currentHeadingLevel = Math.max(1, currentHeadingLevel - 1)
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'hr') {
|
||||
pushHeading(result, currentHeadingLevel + 1, '---')
|
||||
continue
|
||||
}
|
||||
|
||||
if (token.type === 'table_open') {
|
||||
const tableLevel = currentHeadingLevel + 1
|
||||
const { rows, endIndex } = collectTableRows(tokens, i)
|
||||
pushHeading(result, tableLevel, '表格')
|
||||
rows.forEach((row) => {
|
||||
pushHeading(result, tableLevel + 1, row.map(normalizeNodeText).join(' | '))
|
||||
})
|
||||
i = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n')
|
||||
}
|
||||
|
||||
export function replaceFirstMindmapText(markdown: string, oldText: string, newText: string) {
|
||||
const normalizedOld = oldText.replace(/^(引用|表格|代码块)(\s|:|:)?/, '').trim()
|
||||
if (!normalizedOld || !newText.trim()) return markdown
|
||||
|
||||
const escaped = normalizedOld.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const directMatch = new RegExp(escaped)
|
||||
if (directMatch.test(markdown)) {
|
||||
return markdown.replace(directMatch, newText.trim())
|
||||
}
|
||||
|
||||
const lines = markdown.split(/\r?\n/)
|
||||
const targetLineIndex = lines.findIndex((line) => normalizeNodeText(line).includes(normalizedOld))
|
||||
if (targetLineIndex >= 0) {
|
||||
lines[targetLineIndex] = lines[targetLineIndex].replace(normalizedOld, newText.trim())
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
return markdown
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
export interface MindmapNode {
|
||||
content?: string
|
||||
children?: MindmapNode[]
|
||||
payload?: { fold?: number; [key: string]: unknown }
|
||||
}
|
||||
|
||||
export interface FoldState { paths: Map<string, number>; unique: Map<string, number> }
|
||||
|
||||
function identity(node: MindmapNode) {
|
||||
// Browser Blob URLs change on every preview render; image identity must not.
|
||||
return (node.content || '').replace(/src="blob:[^"]*"/g, 'src=""').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function visit(root: MindmapNode, fn: (node: MindmapNode, path: string, text: string) => void) {
|
||||
const walk = (node: MindmapNode, path: string) => {
|
||||
fn(node, path, identity(node))
|
||||
const occurrences = new Map<string, number>()
|
||||
for (const child of node.children || []) {
|
||||
const text = identity(child), ordinal = occurrences.get(text) || 0
|
||||
occurrences.set(text, ordinal + 1)
|
||||
walk(child, `${path}/${JSON.stringify([text, ordinal])}`)
|
||||
}
|
||||
}
|
||||
walk(root, 'root')
|
||||
}
|
||||
|
||||
export function captureFolds(root: MindmapNode): FoldState {
|
||||
const paths = new Map<string, number>(), unique = new Map<string, number>(), repeated = new Set<string>()
|
||||
visit(root, (node, path, text) => {
|
||||
const fold = node.payload?.fold || 0
|
||||
paths.set(path, fold)
|
||||
if (unique.has(text)) repeated.add(text)
|
||||
else unique.set(text, fold)
|
||||
})
|
||||
repeated.forEach(text => unique.delete(text))
|
||||
return { paths, unique }
|
||||
}
|
||||
|
||||
export function restoreFolds(root: MindmapNode, saved?: FoldState) {
|
||||
const counts = new Map<string, number>()
|
||||
visit(root, (_node, _path, text) => counts.set(text, (counts.get(text) || 0) + 1))
|
||||
visit(root, (node, path, text) => {
|
||||
const fold = saved?.paths.get(path) ?? (counts.get(text) === 1 ? saved?.unique.get(text) : undefined) ?? 0
|
||||
node.payload = { ...node.payload, fold: node.children?.length ? fold : 0 }
|
||||
})
|
||||
}
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const getApiBaseURL = () => {
|
||||
const pathname = window.location.pathname
|
||||
const basePath = pathname === '/mindmap' || pathname.startsWith('/mindmap/') ? '/mindmap' : ''
|
||||
return `${basePath}/api`
|
||||
}
|
||||
|
||||
// ?? axios ??
|
||||
const request = axios.create({
|
||||
baseURL: getApiBaseURL(),
|
||||
timeout: 300000, // 5????
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
// ?????
|
||||
request.interceptors.request.use(
|
||||
(config) => {
|
||||
// ?????????token?
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// ?????
|
||||
request.interceptors.response.use(
|
||||
(response) => {
|
||||
return response.data
|
||||
},
|
||||
(error) => {
|
||||
// ??????
|
||||
if (error.response) {
|
||||
const serverMessage = error.response.data?.error || error.response.data?.detail
|
||||
if (serverMessage) {
|
||||
error.message = serverMessage
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
switch (error.response.status) {
|
||||
case 400:
|
||||
error.message = '??????'
|
||||
break
|
||||
case 401:
|
||||
error.message = '?????????'
|
||||
break
|
||||
case 403:
|
||||
error.message = '????'
|
||||
break
|
||||
case 404:
|
||||
error.message = '???????'
|
||||
break
|
||||
case 500:
|
||||
error.message = '???????'
|
||||
break
|
||||
case 502:
|
||||
error.message = '????'
|
||||
break
|
||||
case 503:
|
||||
error.message = '?????'
|
||||
break
|
||||
case 504:
|
||||
error.message = '????'
|
||||
break
|
||||
default:
|
||||
error.message = `????${error.response.status}`
|
||||
}
|
||||
} else {
|
||||
error.message = '??????'
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default request
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
// crypto.randomUUID 仅在安全上下文(HTTPS/localhost)可用;管理平台可能以 HTTP 访问,需要降级。
|
||||
export function uuid(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
||||
const buf = new Uint8Array(16)
|
||||
crypto.getRandomValues(buf)
|
||||
buf[6] = (buf[6] & 0x0f) | 0x40
|
||||
buf[8] = (buf[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(buf, b => b.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
/**
|
||||
* Word 转 PDF 工具
|
||||
* 使用 mammoth 将 Word 文档转换为 HTML,然后使用 html2pdf.js 转换为 PDF
|
||||
*/
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
mammoth: {
|
||||
convertToHtml: (arrayBuffer: ArrayBuffer) => Promise<{ value: string }>;
|
||||
convertToHtmlOptions: (options: object) => object;
|
||||
};
|
||||
html2pdf: {
|
||||
(): {
|
||||
set: (options: object) => ReturnType<typeof html2pdf>;
|
||||
from: (element: HTMLElement | string) => ReturnType<typeof html2pdf>;
|
||||
save: () => Promise<string>;
|
||||
outputPdf: (type: string) => Promise<Blob>;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态加载 mammoth 库
|
||||
*/
|
||||
async function loadMammoth(): Promise<void> {
|
||||
if (typeof window.mammoth === 'undefined') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/mammoth@1.6.0/mammoth.browser.min.js';
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error('Failed to load mammoth library'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态加载 html2pdf 库
|
||||
*/
|
||||
export async function loadHtml2Pdf(): Promise<void> {
|
||||
if (typeof window.html2pdf === 'undefined') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/html2pdf.js@0.10.1/dist/html2pdf.bundle.min.js';
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error('Failed to load html2pdf library'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Word 文档转换为 PDF
|
||||
* @param file Word 文件
|
||||
* @param onProgress 进度回调
|
||||
* @returns PDF 文件
|
||||
*/
|
||||
export async function convertWordToPdf(
|
||||
file: File,
|
||||
onProgress?: (progress: number) => void
|
||||
): Promise<File> {
|
||||
console.log('convertWordToPdf called with file:', file.name, file.size)
|
||||
onProgress?.(10);
|
||||
|
||||
// 加载必要的库
|
||||
console.log('Loading mammoth library...')
|
||||
await loadMammoth();
|
||||
console.log('Mammoth library loaded')
|
||||
onProgress?.(20);
|
||||
|
||||
console.log('Loading html2pdf library...')
|
||||
await loadHtml2Pdf();
|
||||
console.log('html2pdf library loaded')
|
||||
onProgress?.(30);
|
||||
|
||||
// 读取 Word 文件
|
||||
console.log('Reading Word file...')
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
console.log('Word file read successfully')
|
||||
onProgress?.(50);
|
||||
|
||||
// 转换为 HTML
|
||||
console.log('Converting Word to HTML...')
|
||||
const result = await window.mammoth.convertToHtml({ arrayBuffer });
|
||||
console.log('Word to HTML conversion successful, HTML length:', result.value.length)
|
||||
const html = result.value;
|
||||
onProgress?.(70);
|
||||
|
||||
// 创建临时容器
|
||||
console.log('Creating temporary container...')
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = `
|
||||
<div style="font-family: 'Microsoft YaHei', Arial, sans-serif; padding: 20px;">
|
||||
${html}
|
||||
</div>
|
||||
`;
|
||||
container.style.width = '595px'; // A4 width in pixels at 72 DPI
|
||||
document.body.appendChild(container);
|
||||
console.log('Temporary container created')
|
||||
|
||||
onProgress?.(80);
|
||||
|
||||
// 生成 PDF
|
||||
console.log('Generating PDF...')
|
||||
const pdfOptions = {
|
||||
margin: 10,
|
||||
filename: file.name.replace(/\.(docx?|doc)$/i, '.pdf'),
|
||||
image: { type: 'jpeg', quality: 0.98 },
|
||||
html2canvas: { scale: 2, useCORS: true },
|
||||
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
|
||||
};
|
||||
|
||||
const pdfBlob = await window.html2pdf()
|
||||
.set(pdfOptions)
|
||||
.from(container)
|
||||
.outputPdf('blob');
|
||||
console.log('PDF generated successfully, blob size:', pdfBlob.size)
|
||||
|
||||
onProgress?.(95);
|
||||
|
||||
// 清理
|
||||
document.body.removeChild(container);
|
||||
console.log('Temporary container removed')
|
||||
|
||||
// 转换为 File 对象
|
||||
const pdfFile = new File([pdfBlob], pdfOptions.filename, {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
console.log('PDF file created:', pdfFile.name, pdfFile.size)
|
||||
|
||||
onProgress?.(100);
|
||||
|
||||
return pdfFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否为 Word 文档
|
||||
*/
|
||||
export function isWordFile(file: File): boolean {
|
||||
const fileName = file.name.toLowerCase();
|
||||
return fileName.endsWith('.docx') || fileName.endsWith('.doc');
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,15 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# MinerU Vue.js Web UI 启动脚本
|
||||
|
||||
echo "🚀 启动 MinerU Vue.js Web UI..."
|
||||
|
||||
# 检查是否已安装依赖
|
||||
if [ ! -d "node_modules" ]; then
|
||||
echo "📦 安装依赖..."
|
||||
npm install
|
||||
fi
|
||||
|
||||
# 启动开发服务器
|
||||
echo "🌐 启动前端开发服务器..."
|
||||
npm run dev -- --host
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler"
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { resolve } from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src')
|
||||
}
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.VITE_API_PROXY || 'http://127.0.0.1:8000',
|
||||
changeOrigin: true
|
||||
},
|
||||
'/mindmap/api': {
|
||||
target: process.env.VITE_API_PROXY || 'http://127.0.0.1:8000',
|
||||
changeOrigin: true,
|
||||
rewrite: path => path.replace(/^\/mindmap\/api/, '/api')
|
||||
}
|
||||
}
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
assetsDir: 'assets',
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
vendor: ['vue', 'element-plus'],
|
||||
markdown: ['markdown-it']
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Loading…
Reference in New Issue