Compare commits

..

No commits in common. "develop-refact" and "master" have entirely different histories.

79 changed files with 9403 additions and 2528 deletions

View File

@ -1,30 +0,0 @@
.git
.idea
venv
__pycache__
*.pyc
*.pyo
*.log
*.tar
*.tar.gz
*.zip
output
outputs
tmp
.cache
node_modules
web_ui/node_modules
web_ui/dist
mineru/cli/static/web
test_files
tests
.venv
.venv-*
venv-*
*.egg-info
.env
.env.*
*.env
config
models
logs

2
.gitattributes vendored
View File

@ -3,5 +3,3 @@
*.html linguist-documentation *.html linguist-documentation
*.css linguist-vendored *.css linguist-vendored
*.scss linguist-vendored *.scss linguist-vendored
*.sh text eol=lf
mineru/** text eol=lf

View File

@ -1,662 +0,0 @@
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/>.

View File

@ -1,33 +1,2 @@
# Unis MinerU 解析服务
当前基线为官方 **MinerU 2.7.1**。`mineru/` 的全部 187 个文件与登记的官方 wheel 一致,没有项目内核定制;本轮暂不加入六级标题补丁,保持官方最多四级的标题输出。 markitdown
思维导图工作台、用户授权、模型整理、文件格式分流和版本适配已迁至 MaxKB。旧 web_ui 不再部署。官方说明见 [README.mineru-upstream.md](README.mineru-upstream.md),来源和逐文件哈希见 [2.7.1-baseline.json](docs/mineru-migration/2.7.1-baseline.json)。旧业务实现可从 Git 提交 `8b50192` 回看。
## 启动
在经过验证的独立虚拟环境安装本项目,准备原版 pipeline / VLM 模型及 mineru.json,设置 `MINERU_TOOLS_CONFIG_JSON` 和 `MINERU_MODEL_SOURCE=local`,运行:
```bash
python scripts/check_parser_baseline.py --runtime
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`。两者恢复 `develop` 中原厂商基础镜像和依赖安装顺序,保留原字体和系统库。必要差异是将旧 `mineru[core]>=2.7.4` 改为 `mineru[core]==2.7.1`,并在构建结束检查全部官方源码及安装版本。CoreX 继续使用原 `--no-deps` 安装方式及 CoreX 4.4.0 / Torch 2.7.1 / vLLM 0.11.2 / Python 3.10 基础镜像。
`scripts/build-images.sh` 只构建解析镜像,不恢复已退役的 web_ui 构建。它保留 `unis-mindmap-api:版本`、`:corex`/`:cuda`、`:latest` 旧标签,并生成新版升级包需要的 `unis-mineru:版本-卡型` 标签和发布标记。构建时 `latest` 会更新,需保留原交付包/镜像 ID 以便回退。
```bash
API_FLAVOR=corex VERSION=refact-271-20261106-1 bash scripts/build-images.sh
# NVIDIA:API_FLAVOR=cuda
```
模型配置 entrypoint 保持原命令入口;`mineru-api` 命令转交 `scripts/run_parser.py`,在内核之外保留显存/并发参数兼容。包装器配置官方 ASGI app,并将 API 服务参数与引擎参数分开,避免把并发数等字段交给 vLLM 的 `AsyncEngineArgs`;不恢复内核参数过滤补丁。`scripts/start-mindmap.sh` 仅启动 parser,不删除容器、不递归修改业务目录权限;独立 Compose 的 NVIDIA 环境需配置 `MINERU_DOCKER_RUNTIME=nvidia`。
**回到 2.7.1 不等于 MR100 已通过验收。** 原依赖列表仍有浮动版本,基础镜像标签也不等于不可变镜像 ID;移除旧 AsyncEngineArgs 签名过滤补丁后,官方内核与厂商 vLLM 的组合仍需实卡验证。旧 CoreX 离线镜像继续保留为回退材料,见 [基线核查](docs/mineru-migration/release-baseline-20261106.md)。

View File

@ -1,348 +0,0 @@
<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 -->
[![stars](https://img.shields.io/github/stars/opendatalab/MinerU.svg)](https://github.com/opendatalab/MinerU)
[![forks](https://img.shields.io/github/forks/opendatalab/MinerU.svg)](https://github.com/opendatalab/MinerU)
[![open issues](https://img.shields.io/github/issues-raw/opendatalab/MinerU)](https://github.com/opendatalab/MinerU/issues)
[![issue resolution](https://img.shields.io/github/issues-closed-raw/opendatalab/MinerU)](https://github.com/opendatalab/MinerU/issues)
[![PyPI version](https://img.shields.io/pypi/v/mineru)](https://pypi.org/project/mineru/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mineru)](https://pypi.org/project/mineru/)
[![Downloads](https://static.pepy.tech/badge/mineru)](https://pepy.tech/project/mineru)
[![Downloads](https://static.pepy.tech/badge/mineru/month)](https://pepy.tech/project/mineru)
[![OpenDataLab](https://img.shields.io/badge/webapp_on_mineru.net-blue?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTM0IiBoZWlnaHQ9IjEzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJtMTIyLDljMCw1LTQsOS05LDlzLTktNC05LTksNC05LDktOSw5LDQsOSw5eiIgZmlsbD0idXJsKCNhKSIvPjxwYXRoIGQ9Im0xMjIsOWMwLDUtNCw5LTksOXMtOS00LTktOSw0LTksOS05LDksNCw5LDl6IiBmaWxsPSIjMDEwMTAxIi8+PHBhdGggZD0ibTkxLDE4YzAsNS00LDktOSw5cy05LTQtOS05LDQtOSw5LTksOSw0LDksOXoiIGZpbGw9InVybCgjYikiLz48cGF0aCBkPSJtOTEsMThjMCw1LTQsOS05LDlzLTktNC05LTksNC05LDktOSw5LDQsOSw5eiIgZmlsbD0iIzAxMDEwMSIvPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtMzksNjJjMCwxNiw4LDMwLDIwLDM4LDctNiwxMi0xNiwxMi0yNlY0OWMwLTQsMy03LDYtOGw0Ni0xMmM1LTEsMTEsMywxMSw4djMxYzAsMzctMzAsNjYtNjYsNjYtMzcsMC02Ni0zMC02Ni02NlY0NmMwLTQsMy03LDYtOGwyMC02YzUtMSwxMSwzLDExLDh2MjF6bS0yOSw2YzAsMTYsNiwzMCwxNyw0MCwzLDEsNSwxLDgsMSw1LDAsMTAtMSwxNS0zQzM3LDk1LDI5LDc5LDI5LDYyVjQybC0xOSw1djIweiIgZmlsbD0idXJsKCNjKSIvPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtMzksNjJjMCwxNiw4LDMwLDIwLDM4LDctNiwxMi0xNiwxMi0yNlY0OWMwLTQsMy03LDYtOGw0Ni0xMmM1LTEsMTEsMywxMSw4djMxYzAsMzctMzAsNjYtNjYsNjYtMzcsMC02Ni0zMC02Ni02NlY0NmMwLTQsMy03LDYtOGwyMC02YzUtMSwxMSwzLDExLDh2MjF6bS0yOSw2YzAsMTYsNiwzMCwxNyw0MCwzLDEsNSwxLDgsMSw1LDAsMTAtMSwxNS0zQzM3LDk1LDI5LDc5LDI5LDYyVjQybC0xOSw1djIweiIgZmlsbD0iIzAxMDEwMSIvPjxkZWZzPjxsaW5lYXJHcmFkaWVudCBpZD0iYSIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0iYiIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0iYyIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48L3N2Zz4=&labelColor=white)](https://mineru.net/OpenSourceTools/Extractor?source=github)
[![HuggingFace](https://img.shields.io/badge/Demo_on_HuggingFace-yellow.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF8AAABYCAMAAACkl9t/AAAAk1BMVEVHcEz/nQv/nQv/nQr/nQv/nQr/nQv/nQv/nQr/wRf/txT/pg7/yRr/rBD/zRz/ngv/oAz/zhz/nwv/txT/ngv/0B3+zBz/nQv/0h7/wxn/vRb/thXkuiT/rxH/pxD/ogzcqyf/nQvTlSz/czCxky7/SjifdjT/Mj3+Mj3wMj15aTnDNz+DSD9RTUBsP0FRO0Q6O0WyIxEIAAAAGHRSTlMADB8zSWF3krDDw8TJ1NbX5efv8ff9/fxKDJ9uAAAGKklEQVR42u2Z63qjOAyGC4RwCOfB2JAGqrSb2WnTw/1f3UaWcSGYNKTdf/P+mOkTrE+yJBulvfvLT2A5ruenaVHyIks33npl/6C4s/ZLAM45SOi/1FtZPyFur1OYofBX3w7d54Bxm+E8db+nDr12ttmESZ4zludJEG5S7TO72YPlKZFyE+YCYUJTBZsMiNS5Sd7NlDmKM2Eg2JQg8awbglfqgbhArjxkS7dgp2RH6hc9AMLdZYUtZN5DJr4molC8BfKrEkPKEnEVjLbgW1fLy77ZVOJagoIcLIl+IxaQZGjiX597HopF5CkaXVMDO9Pyix3AFV3kw4lQLCbHuMovz8FallbcQIJ5Ta0vks9RnolbCK84BtjKRS5uA43hYoZcOBGIG2Epbv6CvFVQ8m8loh66WNySsnN7htL58LNp+NXT8/PhXiBXPMjLSxtwp8W9f/1AngRierBkA+kk/IpUSOeKByzn8y3kAAAfh//0oXgV4roHm/kz4E2z//zRc3/lgwBzbM2mJxQEa5pqgX7d1L0htrhx7LKxOZlKbwcAWyEOWqYSI8YPtgDQVjpB5nvaHaSnBaQSD6hweDi8PosxD6/PT09YY3xQA7LTCTKfYX+QHpA0GCcqmEHvr/cyfKQTEuwgbs2kPxJEB0iNjfJcCTPyocx+A0griHSmADiC91oNGVwJ69RudYe65vJmoqfpul0lrqXadW0jFKH5BKwAeCq+Den7s+3zfRJzA61/Uj/9H/VzLKTx9jFPPdXeeP+L7WEvDLAKAIoF8bPTKT0+TM7W8ePj3Rz/Yn3kOAp2f1Kf0Weony7pn/cPydvhQYV+eFOfmOu7VB/ViPe34/EN3RFHY/yRuT8ddCtMPH/McBAT5s+vRde/gf2c/sPsjLK+m5IBQF5tO+h2tTlBGnP6693JdsvofjOPnnEHkh2TnV/X1fBl9S5zrwuwF8NFrAVJVwCAPTe8gaJlomqlp0pv4Pjn98tJ/t/fL++6unpR1YGC2n/KCoa0tTLoKiEeUPDl94nj+5/Tv3/eT5vBQ60X1S0oZr+IWRR8Ldhu7AlLjPISlJcO9vrFotky9SpzDequlwEir5beYAc0R7D9KS1DXva0jhYRDXoExPdc6yw5GShkZXe9QdO/uOvHofxjrV/TNS6iMJS+4TcSTgk9n5agJdBQbB//IfF/HpvPt3Tbi7b6I6K0R72p6ajryEJrENW2bbeVUGjfgoals4L443c7BEE4mJO2SpbRngxQrAKRudRzGQ8jVOL2qDVjjI8K1gc3TIJ5KiFZ1q+gdsARPB4NQS4AjwVSt72DSoXNyOWUrU5mQ9nRYyjp89Xo7oRI6Bga9QNT1mQ/ptaJq5T/7WcgAZywR/XlPGAUDdet3LE+qS0TI+g+aJU8MIqjo0Kx8Ly+maxLjJmjQ18rA0YCkxLQbUZP1WqdmyQGJLUm7VnQFqodmXSqmRrdVpqdzk5LvmvgtEcW8PMGdaS23EOWyDVbACZzUJPaqMbjDxpA3Qrgl0AikimGDbqmyT8P8NOYiqrldF8rX+YN7TopX4UoHuSCYY7cgX4gHwclQKl1zhx0THf+tCAUValzjI7Wg9EhptrkIcfIJjA94evOn8B2eHaVzvBrnl2ig0So6hvPaz0IGcOvTHvUIlE2+prqAxLSQxZlU2stql1NqCCLdIiIN/i1DBEHUoElM9dBravbiAnKqgpi4IBkw+utSPIoBijDXJipSVV7MpOEJUAc5Qmm3BnUN+w3hteEieYKfRZSIUcXKMVf0u5wD4EwsUNVvZOtUT7A2GkffHjByWpHqvRBYrTV72a6j8zZ6W0DTE86Hn04bmyWX3Ri9WH7ZU6Q7h+ZHo0nHUAcsQvVhXRDZHChwiyi/hnPuOsSEF6Exk3o6Y9DT1eZ+6cASXk2Y9k+6EOQMDGm6WBK10wOQJCBwren86cPPWUcRAnTVjGcU1LBgs9FURiX/e6479yZcLwCBmTxiawEwrOcleuu12t3tbLv/N4RLYIBhYexm7Fcn4OJcn0+zc+s8/VfPeddZHAGN6TT8eGczHdR/Gts1/MzDkThr23zqrVfAMFT33Nx1RJsx1k5zuWILLnG/vsH+Fv5D4NTVcp1Gzo8AAAAAElFTkSuQmCC&labelColor=white)](https://huggingface.co/spaces/opendatalab/MinerU)
[![ModelScope](https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS4xNCwxMTUuNDlsMjUuNjUsMGwwLDI1LjY1bC0yNS42NSwwbDAsLTI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTYiIGZpbGw9IiM2MjRhZmYiIGQ9Im0xNzYuMDksMTQxLjE0bC0yNS42NDk5OSwwbDAsMjIuMTlsNDcuODQsMGwwLC00Ny44NGwtMjIuMTksMGwwLDI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTciIGZpbGw9IiMzNmNmZDEiIGQ9Im0xMjQuNzksODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTgiIGZpbGw9IiMzNmNmZDEiIGQ9Im0wLDY0LjE5bDI1LjY1LDBsMCwyNS42NWwtMjUuNjUsMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzE5IiBmaWxsPSIjNjI0YWZmIiBkPSJtMTk4LjI4LDg5Ljg0bDI1LjY0OTk5LDBsMCwyNS42NDk5OWwtMjUuNjQ5OTksMGwwLC0yNS42NDk5OXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIwIiBmaWxsPSIjMzZjZmQxIiBkPSJtMTk4LjI4LDY0LjE5bDI1LjY0OTk5LDBsMCwyNS42NWwtMjUuNjQ5OTksMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIxIiBmaWxsPSIjNjI0YWZmIiBkPSJtMTUwLjQ0LDQybDAsMjIuMTlsMjUuNjQ5OTksMGwwLDI1LjY1bDIyLjE5LDBsMCwtNDcuODRsLTQ3Ljg0LDB6Ii8+CiAgPHBhdGggaWQ9InN2Z18yMiIgZmlsbD0iIzM2Y2ZkMSIgZD0ibTczLjQ5LDg5Ljg0bDI1LjY1LDBsMCwyNS42NDk5OWwtMjUuNjUsMGwwLC0yNS42NDk5OXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIzIiBmaWxsPSIjNjI0YWZmIiBkPSJtNDcuODQsNjQuMTlsMjUuNjUsMGwwLC0yMi4xOWwtNDcuODQsMGwwLDQ3Ljg0bDIyLjE5LDBsMCwtMjUuNjV6Ii8+CiAgPHBhdGggaWQ9InN2Z18yNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTQ3Ljg0LDExNS40OWwtMjIuMTksMGwwLDQ3Ljg0bDQ3Ljg0LDBsMCwtMjIuMTlsLTI1LjY1LDBsMCwtMjUuNjV6Ii8+CiA8L2c+Cjwvc3ZnPg==&labelColor=white)](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/gist/myhloli/a3cb16570ab3cfeadf9d8f0ac91b4fca/mineru_demo.ipynb)
[![arXiv](https://img.shields.io/badge/MinerU-Technical%20Report-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2409.18839)
[![arXiv](https://img.shields.io/badge/MinerU2.5-Technical%20Report-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2509.22186)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](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/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
- [![OpenDataLab](https://img.shields.io/badge/webapp_on_mineru.net-blue?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTM0IiBoZWlnaHQ9IjEzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJtMTIyLDljMCw1LTQsOS05LDlzLTktNC05LTksNC05LDktOSw5LDQsOSw5eiIgZmlsbD0idXJsKCNhKSIvPjxwYXRoIGQ9Im0xMjIsOWMwLDUtNCw5LTksOXMtOS00LTktOSw0LTksOS05LDksNCw5LDl6IiBmaWxsPSIjMDEwMTAxIi8+PHBhdGggZD0ibTkxLDE4YzAsNS00LDktOSw5cy05LTQtOS05LDQtOSw5LTksOSw0LDksOXoiIGZpbGw9InVybCgjYikiLz48cGF0aCBkPSJtOTEsMThjMCw1LTQsOS05LDlzLTktNC05LTksNC05LDktOSw5LDQsOSw5eiIgZmlsbD0iIzAxMDEwMSIvPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtMzksNjJjMCwxNiw4LDMwLDIwLDM4LDctNiwxMi0xNiwxMi0yNlY0OWMwLTQsMy03LDYtOGw0Ni0xMmM1LTEsMTEsMywxMSw4djMxYzAsMzctMzAsNjYtNjYsNjYtMzcsMC02Ni0zMC02Ni02NlY0NmMwLTQsMy03LDYtOGwyMC02YzUtMSwxMSwzLDExLDh2MjF6bS0yOSw2YzAsMTYsNiwzMCwxNyw0MCwzLDEsNSwxLDgsMSw1LDAsMTAtMSwxNS0zQzM3LDk1LDI5LDc5LDI5LDYyVjQybC0xOSw1djIweiIgZmlsbD0idXJsKCNjKSIvPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtMzksNjJjMCwxNiw4LDMwLDIwLDM4LDctNiwxMi0xNiwxMi0yNlY0OWMwLTQsMy03LDYtOGw0Ni0xMmM1LTEsMTEsMywxMSw4djMxYzAsMzctMzAsNjYtNjYsNjYtMzcsMC02Ni0zMC02Ni02NlY0NmMwLTQsMy03LDYtOGwyMC02YzUtMSwxMSwzLDExLDh2MjF6bS0yOSw2YzAsMTYsNiwzMCwxNyw0MCwzLDEsNSwxLDgsMSw1LDAsMTAtMSwxNS0zQzM3LDk1LDI5LDc5LDI5LDYyVjQybC0xOSw1djIweiIgZmlsbD0iIzAxMDEwMSIvPjxkZWZzPjxsaW5lYXJHcmFkaWVudCBpZD0iYSIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0iYiIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0iYyIgeDE9Ijg0IiB5MT0iNDEiIHgyPSI3NSIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiNmZmYiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyZTJlMmUiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48L3N2Zz4=&labelColor=white)](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
- [![ModelScope](https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS4xNCwxMTUuNDlsMjUuNjUsMGwwLDI1LjY1bC0yNS42NSwwbDAsLTI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTYiIGZpbGw9IiM2MjRhZmYiIGQ9Im0xNzYuMDksMTQxLjE0bC0yNS42NDk5OSwwbDAsMjIuMTlsNDcuODQsMGwwLC00Ny44NGwtMjIuMTksMGwwLDI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTciIGZpbGw9IiMzNmNmZDEiIGQ9Im0xMjQuNzksODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTgiIGZpbGw9IiMzNmNmZDEiIGQ9Im0wLDY0LjE5bDI1LjY1LDBsMCwyNS42NWwtMjUuNjUsMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzE5IiBmaWxsPSIjNjI0YWZmIiBkPSJtMTk4LjI4LDg5Ljg0bDI1LjY0OTk5LDBsMCwyNS42NDk5OWwtMjUuNjQ5OTksMGwwLC0yNS42NDk5OXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIwIiBmaWxsPSIjMzZjZmQxIiBkPSJtMTk4LjI4LDY0LjE5bDI1LjY0OTk5LDBsMCwyNS42NWwtMjUuNjQ5OTksMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIxIiBmaWxsPSIjNjI0YWZmIiBkPSJtMTUwLjQ0LDQybDAsMjIuMTlsMjUuNjQ5OTksMGwwLDI1LjY1bDIyLjE5LDBsMCwtNDcuODRsLTQ3Ljg0LDB6Ii8+CiAgPHBhdGggaWQ9InN2Z18yMiIgZmlsbD0iIzM2Y2ZkMSIgZD0ibTczLjQ5LDg5Ljg0bDI1LjY1LDBsMCwyNS42NDk5OWwtMjUuNjUsMGwwLC0yNS42NDk5OXoiLz4KICA8cGF0aCBpZD0ic3ZnXzIzIiBmaWxsPSIjNjI0YWZmIiBkPSJtNDcuODQsNjQuMTlsMjUuNjUsMGwwLC0yMi4xOWwtNDcuODQsMGwwLDQ3Ljg0bDIyLjE5LDBsMCwtMjUuNjV6Ii8+CiAgPHBhdGggaWQ9InN2Z18yNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTQ3Ljg0LDExNS40OWwtMjIuMTksMGwwLDQ3Ljg0bDQ3Ljg0LDBsMCwtMjIuMTlsLTI1LjY1LDBsMCwtMjUuNjV6Ii8+CiA8L2c+Cjwvc3ZnPg==&labelColor=white)](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
- [![HuggingFace](https://img.shields.io/badge/Demo_on_HuggingFace-yellow.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF8AAABYCAMAAACkl9t/AAAAk1BMVEVHcEz/nQv/nQv/nQr/nQv/nQr/nQv/nQv/nQr/wRf/txT/pg7/yRr/rBD/zRz/ngv/oAz/zhz/nwv/txT/ngv/0B3+zBz/nQv/0h7/wxn/vRb/thXkuiT/rxH/pxD/ogzcqyf/nQvTlSz/czCxky7/SjifdjT/Mj3+Mj3wMj15aTnDNz+DSD9RTUBsP0FRO0Q6O0WyIxEIAAAAGHRSTlMADB8zSWF3krDDw8TJ1NbX5efv8ff9/fxKDJ9uAAAGKklEQVR42u2Z63qjOAyGC4RwCOfB2JAGqrSb2WnTw/1f3UaWcSGYNKTdf/P+mOkTrE+yJBulvfvLT2A5ruenaVHyIks33npl/6C4s/ZLAM45SOi/1FtZPyFur1OYofBX3w7d54Bxm+E8db+nDr12ttmESZ4zludJEG5S7TO72YPlKZFyE+YCYUJTBZsMiNS5Sd7NlDmKM2Eg2JQg8awbglfqgbhArjxkS7dgp2RH6hc9AMLdZYUtZN5DJr4molC8BfKrEkPKEnEVjLbgW1fLy77ZVOJagoIcLIl+IxaQZGjiX597HopF5CkaXVMDO9Pyix3AFV3kw4lQLCbHuMovz8FallbcQIJ5Ta0vks9RnolbCK84BtjKRS5uA43hYoZcOBGIG2Epbv6CvFVQ8m8loh66WNySsnN7htL58LNp+NXT8/PhXiBXPMjLSxtwp8W9f/1AngRierBkA+kk/IpUSOeKByzn8y3kAAAfh//0oXgV4roHm/kz4E2z//zRc3/lgwBzbM2mJxQEa5pqgX7d1L0htrhx7LKxOZlKbwcAWyEOWqYSI8YPtgDQVjpB5nvaHaSnBaQSD6hweDi8PosxD6/PT09YY3xQA7LTCTKfYX+QHpA0GCcqmEHvr/cyfKQTEuwgbs2kPxJEB0iNjfJcCTPyocx+A0griHSmADiC91oNGVwJ69RudYe65vJmoqfpul0lrqXadW0jFKH5BKwAeCq+Den7s+3zfRJzA61/Uj/9H/VzLKTx9jFPPdXeeP+L7WEvDLAKAIoF8bPTKT0+TM7W8ePj3Rz/Yn3kOAp2f1Kf0Weony7pn/cPydvhQYV+eFOfmOu7VB/ViPe34/EN3RFHY/yRuT8ddCtMPH/McBAT5s+vRde/gf2c/sPsjLK+m5IBQF5tO+h2tTlBGnP6693JdsvofjOPnnEHkh2TnV/X1fBl9S5zrwuwF8NFrAVJVwCAPTe8gaJlomqlp0pv4Pjn98tJ/t/fL++6unpR1YGC2n/KCoa0tTLoKiEeUPDl94nj+5/Tv3/eT5vBQ60X1S0oZr+IWRR8Ldhu7AlLjPISlJcO9vrFotky9SpzDequlwEir5beYAc0R7D9KS1DXva0jhYRDXoExPdc6yw5GShkZXe9QdO/uOvHofxjrV/TNS6iMJS+4TcSTgk9n5agJdBQbB//IfF/HpvPt3Tbi7b6I6K0R72p6ajryEJrENW2bbeVUGjfgoals4L443c7BEE4mJO2SpbRngxQrAKRudRzGQ8jVOL2qDVjjI8K1gc3TIJ5KiFZ1q+gdsARPB4NQS4AjwVSt72DSoXNyOWUrU5mQ9nRYyjp89Xo7oRI6Bga9QNT1mQ/ptaJq5T/7WcgAZywR/XlPGAUDdet3LE+qS0TI+g+aJU8MIqjo0Kx8Ly+maxLjJmjQ18rA0YCkxLQbUZP1WqdmyQGJLUm7VnQFqodmXSqmRrdVpqdzk5LvmvgtEcW8PMGdaS23EOWyDVbACZzUJPaqMbjDxpA3Qrgl0AikimGDbqmyT8P8NOYiqrldF8rX+YN7TopX4UoHuSCYY7cgX4gHwclQKl1zhx0THf+tCAUValzjI7Wg9EhptrkIcfIJjA94evOn8B2eHaVzvBrnl2ig0So6hvPaz0IGcOvTHvUIlE2+prqAxLSQxZlU2stql1NqCCLdIiIN/i1DBEHUoElM9dBravbiAnKqgpi4IBkw+utSPIoBijDXJipSVV7MpOEJUAc5Qmm3BnUN+w3hteEieYKfRZSIUcXKMVf0u5wD4EwsUNVvZOtUT7A2GkffHjByWpHqvRBYrTV72a6j8zZ6W0DTE86Hn04bmyWX3Ri9WH7ZU6Q7h+ZHo0nHUAcsQvVhXRDZHChwiyi/hnPuOsSEF6Exk3o6Y9DT1eZ+6cASXk2Y9k+6EOQMDGm6WBK10wOQJCBwren86cPPWUcRAnTVjGcU1LBgs9FURiX/e6479yZcLwCBmTxiawEwrOcleuu12t3tbLv/N4RLYIBhYexm7Fcn4OJcn0+zc+s8/VfPeddZHAGN6TT8eGczHdR/Gts1/MzDkThr23zqrVfAMFT33Nx1RJsx1k5zuWILLnG/vsH+Fv5D4NTVcp1Gzo8AAAAAElFTkSuQmCC&labelColor=white)](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)

View File

@ -1,10 +1,27 @@
# ==========================================
# 阶段 1:前端构建 (Node.js Builder)
# ==========================================
FROM node:18-alpine AS frontend-builder
WORKDIR /build
# 利用镜像缓存:先拷贝 package.json
COPY web_ui/package*.json ./
RUN npm config set registry https://registry.npmmirror.com && \
npm install
# 拷贝源码并构建
COPY web_ui/ .
RUN npm run build
# ==========================================
# 阶段 2:最终运行环境 (CoreX Runtime)
# ==========================================
FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10 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 DEBIAN_FRONTEND=noninteractive
ENV MINERU_MODEL_SOURCE=local ENV MINERU_MODEL_SOURCE=local
ENV MINERU_MODEL_DIR=/models
ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json
# 1. 系统级依赖:仅安装运行时必需的字体和工具
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
fonts-noto-core \ fonts-noto-core \
fonts-noto-cjk \ fonts-noto-cjk \
@ -13,53 +30,47 @@ RUN apt-get update && apt-get install -y \
&& fc-cache -fv \ && fc-cache -fv \
&& apt-get clean && rm -rf /var/lib/apt/lists/* && 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 && \ RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
python3 -m pip install 'mineru[core]==2.7.1' --no-deps -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 \ python3 -m pip install \
"numpy==1.26.4" \ "numpy==1.26.4" \
"opencv-python==4.11.0.86" \ "opencv-python==4.11.0.86" \
"pydantic>=2.12,<3" \ "pydantic<2.0" \
"modelscope" \ "modelscope" \
"magic-pdf" \ "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 && \ -i https://mirrors.aliyun.com/pypi/simple && \
python3 -m pip cache purge python3 -m pip cache purge
WORKDIR /app 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 && python3 scripts/check_parser_baseline.py --runtime
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] # 3. 拷贝项目源码(排除 web_ui 源码以减小体积)
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] 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"]

View File

@ -1,65 +0,0 @@
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.1' --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
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 && python3 scripts/check_parser_baseline.py --runtime
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"]
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]

View File

@ -1,36 +0,0 @@
FROM unis-mindmap-api:latest
RUN python3 -m pip install \
boto3 \
"pdfminer.six>=20251230" \
pypdfium2 \
pypdf \
reportlab \
pdftext \
huggingface-hub \
json-repair \
fast-langdetect \
scikit-image \
openai \
beautifulsoup4 \
magika \
mineru-vl-utils \
qwen-vl-utils \
matplotlib \
ultralytics \
doclayout_yolo==0.0.4 \
dill \
PyYAML \
ftfy \
shapely \
pyclipper \
omegaconf \
onnxruntime \
python-pptx \
python-docx \
openpyxl \
xlrd \
xlwt \
pylatexenc \
mammoth \
-i https://mirrors.aliyun.com/pypi/simple && \
python3 -m pip cache purge

View File

@ -1,4 +0,0 @@
FROM unis-mindmap-api:latest
COPY mineru/backend/vlm/vlm_analyze.py /app/mineru/backend/vlm/vlm_analyze.py
COPY mineru/backend/vlm/utils.py /app/mineru/backend/vlm/utils.py

View File

@ -18,8 +18,6 @@ RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \
numpy==1.26.4 \ numpy==1.26.4 \
opencv-python==4.11.0.86 \ opencv-python==4.11.0.86 \
-i https://mirrors.aliyun.com/pypi/simple && \ -i https://mirrors.aliyun.com/pypi/simple && \
python3 -m pip install --force-reinstall --no-cache-dir "pydantic>=2.12,<3" -i https://mirrors.aliyun.com/pypi/simple && \
python3 -c "import pydantic; print('pydantic', pydantic.__version__); from pydantic import TypeAdapter; print('pydantic TypeAdapter ok')" && \
python3 -m pip cache purge python3 -m pip cache purge
# Download models and update the configuration file # Download models and update the configuration file

View File

@ -1,24 +1,87 @@
services: services:
mineru-api: mineru-openai-server:
image: unis-mineru:2.7.1 image: mineru:latest
restart: unless-stopped container_name: mineru-openai-server
runtime: ${MINERU_DOCKER_RUNTIME:-runc} restart: always
privileged: true profiles: ["openai-server"]
ipc: host
shm_size: 32g
ports: ports:
- "127.0.0.1:${MINERU_PORT:-8100}:8000" - 30000:30000
environment: environment:
MINERU_MODEL_SOURCE: local MINERU_MODEL_SOURCE: local
MINERU_MODEL_DIR: /models entrypoint: mineru-openai-server
MINERU_GPU_MEMORY_UTILIZATION: ${MINERU_GPU_MEMORY_UTILIZATION:-0.5} command:
PYTHONPATH: /app:/usr/local/corex-4.4.0/lib64/python3/dist-packages --host 0.0.0.0
CUDA_VISIBLE_DEVICES: ${MINERU_CUDA_VISIBLE_DEVICES:-0} --port 30000
NVIDIA_VISIBLE_DEVICES: ${MINERU_NVIDIA_VISIBLE_DEVICES:-all} # --data-parallel-size 2 # If using multiple GPUs, increase throughput using vllm's multi-GPU parallel mode
NVIDIA_DRIVER_CAPABILITIES: compute,utility # --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.
volumes: ulimits:
- "${MINERU_MODEL_DIR:?Set MINERU_MODEL_DIR}:/models:ro" memlock: -1
- mineru-output:/app/output stack: 67108864
command: ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"] ipc: host
volumes: healthcheck:
mineru-output: 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"]
ports:
- 8000: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]

View File

@ -1,56 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
MODEL_DIR=${MINERU_MODEL_DIR:-/models}
PIPELINE_MODEL_DIR=${MINERU_PIPELINE_MODEL_DIR:-${MODEL_DIR}/pipeline}
VLM_MODEL_DIR=${MINERU_VLM_MODEL_DIR:-${MODEL_DIR}/vlm}
CONFIG_PATH=${MINERU_TOOLS_CONFIG_JSON:-/root/mineru.json}
mkdir -p "$(dirname "$CONFIG_PATH")"
export CONFIG_PATH PIPELINE_MODEL_DIR VLM_MODEL_DIR
if [ ! -f "$CONFIG_PATH" ]; then
python3 - <<'PY'
import json
import os
from pathlib import Path
config_path = Path(os.environ["CONFIG_PATH"])
config = {
"bucket_info": {"[default]": [None, None, None]},
"latex-delimiter-config": {
"display": {"left": "$$", "right": "$$"},
"inline": {"left": "$", "right": "$"},
},
"llm-aided-config": {
"title_aided": {
"api_key": "",
"base_url": "",
"model": "",
"enable_thinking": False,
"enable": False,
}
},
"models-dir": {
"pipeline": os.environ["PIPELINE_MODEL_DIR"],
"vlm": os.environ["VLM_MODEL_DIR"],
},
"config_version": "1.3.1",
}
config_path.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
PY
fi
export MINERU_TOOLS_CONFIG_JSON="$CONFIG_PATH"
export MINERU_MODEL_SOURCE=${MINERU_MODEL_SOURCE:-local}
export PYTHONPATH=${PYTHONPATH:-/app}
# Keep the historical Docker command while passing deployment-only settings
# through the wrapper instead of patching the official MinerU kernel.
if [ "${1:-}" = "mineru-api" ]; then
shift
set -- python3 /app/scripts/run_parser.py "$@"
fi
exec "$@"

View File

@ -1,67 +1,39 @@
FROM pytorch/pytorch:2.7.1-cuda12.6-cudnn9-runtime # 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
ENV DEBIAN_FRONTEND=noninteractive # Use the official vllm image for gpu with Volta、Turing、Blackwell architecture (7.0 < Compute Capability < 8.0 or Compute Capability >= 10.0)
ENV MINERU_MODEL_SOURCE=local # support x86_64 architecture and ARM(AArch64) architecture
ENV MINERU_MODEL_DIR=/models # FROM vllm/vllm-openai:v0.11.0
ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json
RUN apt-get update && apt-get install -y \ # Install libgl for opencv support & Noto fonts for Chinese characters
RUN apt-get update && \
apt-get install -y \
fonts-noto-core \ fonts-noto-core \
fonts-noto-cjk \ fonts-noto-cjk \
fontconfig \ fontconfig \
libgl1 \ libgl1 && \
libglib2.0-0 \ fc-cache -fv && \
git \ apt-get clean && \
&& fc-cache -fv \ rm -rf /var/lib/apt/lists/*
&& apt-get clean && rm -rf /var/lib/apt/lists/*
RUN ln -sf "$(command -v python)" /usr/local/bin/python3 && \ # Install LibreOffice for Word to PDF conversion (minimal installation)
python -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \ RUN apt-get update && \
python -m pip install \ apt-get install -y --no-install-recommends \
'mineru[core]==2.7.1' \ libreoffice-writer \
'vllm==0.11.2' \ libreoffice-core \
'pydantic>=2.12,<3' \ fonts-noto-core \
modelscope \ fonts-noto-cjk && \
magic-pdf \ apt-get clean && \
boto3 \ rm -rf /var/lib/apt/lists/*
'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
WORKDIR /app # Install mineru latest
COPY . . RUN python3 -m pip install -U 'mineru[core]>=2.7.0' --break-system-packages && \
COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh python3 -m pip cache purge
RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh && python3 scripts/check_parser_baseline.py --runtime
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] # Download models and update the configuration file
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] 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 \"$@\"", "--"]

View File

@ -1,67 +0,0 @@
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.1' \
'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
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 && python3 scripts/check_parser_baseline.py --runtime
ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"]
CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"]

View File

@ -1,197 +0,0 @@
{
"baseline": "PyPI mineru==2.7.1",
"url": "https://files.pythonhosted.org/packages/36/fd/d94ab07cbcfabae65a306a6d704214ec6024f443d8119e24234f1b3fa3ba/mineru-2.7.1-py3-none-any.whl",
"sha256": "3c144149f2749a79be240833c392216ddd69c1516de162b29dbaddbc0ce38f73",
"files": 187,
"kernel_modifications": [],
"hash_format": "sha256 after CRLF-to-LF normalization",
"source_hashes": {
"__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"backend/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"backend/hybrid/__init__.py": "20582bd82f0d7d2023f2aec917b40ea8cbc2889e8573c4c8b94dd48760da1595",
"backend/hybrid/hybrid_analyze.py": "49c930e93fa9bccbf757f9ea66405e5bc918e333480655b1a9e4b6bd7a8daad6",
"backend/hybrid/hybrid_magic_model.py": "dfd072799879e0a05b3deefb6f3182a99ad9e51370371198b6d7288ac8033ab7",
"backend/hybrid/hybrid_model_output_to_middle_json.py": "c84f9cd5e19ae4bccfa8b7ca7ef04e37f4894658eacb3d81ecb8a0945704ec54",
"backend/pipeline/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"backend/pipeline/batch_analyze.py": "dd406cd963b0708fa67c6025c59b78dfb3aa48e95e5cf2e7a586eb0fd8790f9e",
"backend/pipeline/model_init.py": "c33f157627945c2c734bd350aa499a897c1e7b2f31cfefc306f982d4eb8afc1e",
"backend/pipeline/model_json_to_middle_json.py": "ade5e4511ff02a6243eb877bbd135733116f8b09330e51a346c869770b15aae2",
"backend/pipeline/model_list.py": "edc5cc05f66b3f42baa96b9e8350fff96a1400d79220dce49ff89cf44ed840bb",
"backend/pipeline/para_split.py": "2aaf79326be43e6eeb2b1942486893bd52b217b084ac7236786180b39b0b9744",
"backend/pipeline/pipeline_analyze.py": "44f413b6efa6e1661543121128b8f7f553f268aaaba22e5373df85084b90857f",
"backend/pipeline/pipeline_magic_model.py": "c3c8c6c7c7fac9937459fdb23cfdcbf6b60a73dae8831ade642ad427326f3cef",
"backend/pipeline/pipeline_middle_json_mkcontent.py": "34908b18a13b06a336e1b45da5709f4da9728aaa33a301598e9773a48532e5a0",
"backend/utils.py": "18b254dc8ce70e6844d7fa8d9a453550eb6cbac9081c17b382c1153ba51aafe6",
"backend/vlm/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"backend/vlm/model_output_to_middle_json.py": "02a617e38812f5cad43bfb7b4ae51ab43ef51158e8c3aa48eb2036224de0434b",
"backend/vlm/utils.py": "b2a712e1654273154bd5a125288235ccd60cbb6c87e6d46956a45be255d59b7f",
"backend/vlm/vlm_analyze.py": "11d7c49a4ae803795a7d164ba8de2e39a2d6c7da3156752872a16c599c92f367",
"backend/vlm/vlm_magic_model.py": "983fa2af16e8a360e632ee10175c27bdbb62db174dc8198d7e56c1e1af939ac5",
"backend/vlm/vlm_middle_json_mkcontent.py": "c3e4b36e6e078ad47b318e298a7482659757b4f4aa9ad954f5c8cd87820e4328",
"cli/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"cli/client.py": "98f35f3044a1546fa2b619a5250e6719121a7768026605230461cdef30262e14",
"cli/common.py": "7cc3dcdb7e43b67ba942487db8520c1d4a71392bc2a79c9cdc0e7ab0069b0166",
"cli/fast_api.py": "4c6a59ab2504d64836797b0fefaa6bd29d72a8d38e53d8f28cbe4f734149c117",
"cli/gradio_app.py": "d882163a6d9b1071eae4164c95f98ddf2009c3535ff125002d343de68f9b632d",
"cli/models_download.py": "2cd7e822952524cee6eea6f64a20b1b63303c388c82c142d67034fd89a18f355",
"cli/vlm_server.py": "dbb1daa8edf0a4c5d203f9c0dc20ba24e0531cadeaeba48fd34703ea6f47b901",
"data/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"data/data_reader_writer/__init__.py": "f6a9c636bb2e181330c1fb10cbaa0285d933fbe6bf2cf758584d15659af4cabe",
"data/data_reader_writer/base.py": "9ea98071d1ce5cc3893ba4404f720b96280315ac3c3a9d124f20b0e723b301b2",
"data/data_reader_writer/dummy.py": "312c5069938af22fa59643d70e7d3c92fbee22d7b9a0907fe25463af59a75ed0",
"data/data_reader_writer/filebase.py": "8255d548927eb80fffa83d09feb7611d4d956043866a20b6824f52270ca73e3e",
"data/data_reader_writer/multi_bucket_s3.py": "6f05488a65556a3d0c35e549a4d000ad6e35746caaaaf0b3abd259e8e85db298",
"data/data_reader_writer/s3.py": "3707fc89c1d542a9bc448da7e00cf356ec0aef9775ab925956e0e97bbe028478",
"data/io/__init__.py": "9a343f2c049a5fee3fa60fb5bb368c272b0812582552cde8f9a92aac03fc3024",
"data/io/base.py": "4aa350a9edf466fa15be0ec656ffa12cc0a337ac81803c9041678b806b137e14",
"data/io/http.py": "776f826411a330f3af7409240bdcf150429862264f80befa66a706e21203793d",
"data/io/s3.py": "ddf0e2b4deeb1069f50ca0e48cab5fdb20baf260eb27eb55cb28bc55890d61e0",
"data/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"data/utils/exceptions.py": "a3116951056e9bc2d1140820d5c66f328378c604947bde6b80d0d4da6cd39707",
"data/utils/path_utils.py": "ca47a8f965b5eb723618a016a34bc8a4fd4caedc08f7d3cfaad082d39ba1bd53",
"data/utils/schemas.py": "30afe99d690aebd3119d56b29278b6b42472eacc7b71d09e3ebcbf5bb5148217",
"model/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/layout/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/layout/doclayoutyolo.py": "0edb4835dba5cd38987150e5ffbd280ed51d7d598673daa429699b3ce180795d",
"model/mfd/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/mfd/yolo_v8.py": "b7ba6d992847a19096f5692a2cd08bd4a442871a5ad84ee3e60e5f89b5e552f6",
"model/mfr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/mfr/pp_formulanet_plus_m/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/mfr/pp_formulanet_plus_m/predict_formula.py": "6a5197fec3c9c5987feefd6c38adc327c6a47e458efb673923f251eda5cc4cb5",
"model/mfr/pp_formulanet_plus_m/processors.py": "3122b26a7c620c38e00d01c1a2ff868cab4f9ccc7db529b1042f462243377edf",
"model/mfr/unimernet/Unimernet.py": "d5218b490dab73aa2c9671303f84e2ec9c5a365c8248681ed23b3e4ebd558a41",
"model/mfr/unimernet/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/mfr/unimernet/unimernet_hf/__init__.py": "907708486f064b84d6256df84822427a2d63c68e87c6f3b4d1a0b476ac8d1602",
"model/mfr/unimernet/unimernet_hf/modeling_unimernet.py": "fe5377cc32b17aab16fa1f6d5f1efd0d8893e6e4f83fd8b11b8f56ad260a1711",
"model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py": "f53dab069c865f96054188fcf7e996ba346890ebb3e3180dade06e7a0720d7f7",
"model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py": "87045aaf7a6a37f715b374d14cd4ae841e3069c06771f27eaaf6936a345bd317",
"model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py": "5e49cbe940f6b217dc12b003f242e4e754f2dcbb5bbfbb838bf6379311b58def",
"model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py": "f3fd432b00c20d4064787622249e8c667a1d641b1ab476ea872821d75b3d7840",
"model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py": "397dde4542819ca097b7124e1b7b1d368075215f99ede7e0594fa069c9583860",
"model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py": "6bd902bf0cc925246b29036d5b6a0ea53c2b6a9cdea7c06318558b84b1754f49",
"model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py": "43f7dd9851d406d12801f5a9f5aa307704c213630814c38f6d88e84b25cada25",
"model/mfr/utils.py": "a408b51e7913b8ed11eb6e751dd97ea39d26d301f409ef3d3c07fbe160ac5cf5",
"model/ocr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/ocr/pytorch_paddle.py": "707313979b0aca7e01636db4efeec643879997d05051cb39b9cc70fcd15ecc82",
"model/ori_cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/ori_cls/paddle_ori_cls.py": "5484b6d887ab1d24fb83ad000bdaf63c44081ba35059e41a1f53ab5c8c4d4ec8",
"model/reading_order/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/reading_order/layout_reader.py": "21550570d303177fa48a8f812318e9a479d64b77873eabef362848c367db2053",
"model/reading_order/xycut.py": "7b3352abf6385178b3b41e7c85b5c9b234c994e06a5888ee5b9036b8b49a652a",
"model/table/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/table/cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/table/cls/paddle_table_cls.py": "e4fb6278a42703380c3514d91609ea42c196293110df2c855909c14488df4380",
"model/table/rec/RapidTable.py": "d9d35d189b1576c19f466eabddd78445432cb79448c47d18ba21802e441b353c",
"model/table/rec/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/table/rec/slanet_plus/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/table/rec/slanet_plus/main.py": "bdfadcbd0f4905fdf661953d78da1eb68a9da5cac536c03558da9006c1bc8b6a",
"model/table/rec/slanet_plus/matcher.py": "bb017ec022da625690dc943ff98cb01959755d0627c7b1bf453b962d6f099419",
"model/table/rec/slanet_plus/matcher_utils.py": "f70b7fc9d79e5622dde7b6d4ea0de59d75e78b8f6a2d2adad82eb0485419922c",
"model/table/rec/slanet_plus/table_structure.py": "aadf873d8210ca9d1a586fcc9a733fb0c40257c64b6f8ac02d2b9ec82a213e03",
"model/table/rec/slanet_plus/table_structure_utils.py": "6184a4c0dd9674bc7baa458c48690f63bc97387e44355860e42b111a1b59e569",
"model/table/rec/unet_table/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/table/rec/unet_table/main.py": "275dd0effeacb58c9e76655e75ff42643ed1d2dba0b867d3837677a1be060ee3",
"model/table/rec/unet_table/table_recover.py": "ad2c9e5b2b8fd7433c74b280e5ed27e0fd835cc61b55b9a02f111c75903cff41",
"model/table/rec/unet_table/table_structure_unet.py": "8679982f36454652b463882bf3be06f4668b6a170a9cd65836e9fcebd15d987f",
"model/table/rec/unet_table/utils.py": "09802a256d3078f264e0d01e99bf16db4dcdec4df6bf4ba38966f16a70e177c2",
"model/table/rec/unet_table/utils_table_line_rec.py": "ceb09d3f023833c9eed0511f77b9512407b4cfc918ab72856f3c0494cf365121",
"model/table/rec/unet_table/utils_table_recover.py": "5e4b09b18f36652d24a949cd4fe8ef698cf1277577b2f312ce3d29bb021abb59",
"model/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/utils/pytorchocr/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/utils/pytorchocr/base_ocr_v20.py": "e5b23b300bbae6bfaf9f6f24af0749ea98d932412f5a3b2913b110693b11111c",
"model/utils/pytorchocr/data/__init__.py": "618bb773e5b87e0104af1c4333df2e437a16c0f121fbac3be4b638cdc8f856d3",
"model/utils/pytorchocr/data/imaug/__init__.py": "7381f48173d1c1e434c0c16792b08b4d1e8caed1be7b89148a7c70ab61b557d5",
"model/utils/pytorchocr/data/imaug/operators.py": "79d05a0de7b39910241a476e3c5e8859c529136597461ee6011a929f0cb29c40",
"model/utils/pytorchocr/modeling/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/utils/pytorchocr/modeling/architectures/__init__.py": "0c203d152e26139a021c3941854ae460b77115e4086e13e3e0ff2827f811643f",
"model/utils/pytorchocr/modeling/architectures/base_model.py": "4615760e6fa8b34f24085ca54f9ef346eef61eafd125d172df141ed4c3da0ae5",
"model/utils/pytorchocr/modeling/backbones/__init__.py": "74e9aa86f2eb04cfb68a6730b7bde44ba00f98c6e1a15613a33966a8e9117ea0",
"model/utils/pytorchocr/modeling/backbones/det_mobilenet_v3.py": "af48169c0d579add19c381502f1ee47fe596c1977fdba3df37384cd3976b72e1",
"model/utils/pytorchocr/modeling/backbones/rec_donut_swin.py": "9530a37bb98fb84f9f1ded3901325ee42efbc319340914e8940b43fe07d04e68",
"model/utils/pytorchocr/modeling/backbones/rec_hgnet.py": "52c21bcea37f928c86a128754c0f6bdbb4a08291db78a4b71e6992f80d80c34e",
"model/utils/pytorchocr/modeling/backbones/rec_lcnetv3.py": "f954734cfb6becb4e6c09e1d0adb08fbe803f35600761de59556aef4ae159dcf",
"model/utils/pytorchocr/modeling/backbones/rec_mobilenet_v3.py": "989984eb11a98c7647d956b0d7a2e5225a911459bd47dc91b122446b7627de7c",
"model/utils/pytorchocr/modeling/backbones/rec_mv1_enhance.py": "2b8a7d28560d9a5b55df2dd0b311c8012371a2a946b71800a02c5e1687f20a6c",
"model/utils/pytorchocr/modeling/backbones/rec_pphgnetv2.py": "61fa75c51e5286ce5bd6ec468e1152ad880fabd065dcda20612a3e28e26ed3c9",
"model/utils/pytorchocr/modeling/backbones/rec_svtrnet.py": "008694677216064473da95a66a70634b441d25c6278a6312578316a1f36941c8",
"model/utils/pytorchocr/modeling/common.py": "debda34ef3d8412e08813bc8a91e25e9b055c11ee39fef3bad29a9bf7b65ab12",
"model/utils/pytorchocr/modeling/heads/__init__.py": "7650d6008083ff73eb622862a421c33f91822551fff9fc128fb59fa237c808ca",
"model/utils/pytorchocr/modeling/heads/cls_head.py": "a6e232e46954b4029eafa792e0758abb4ecfcd177e1e50c0a88cf95aa8c11da0",
"model/utils/pytorchocr/modeling/heads/det_db_head.py": "fa4f1ba6e190c3fc48543b2e9ab7e298ec60d0efa83f630e0320c94e353bd11a",
"model/utils/pytorchocr/modeling/heads/rec_ctc_head.py": "cb0ca4e512605084dd5efad4664db205258ab1a648aa74e87dd15bb9052dc235",
"model/utils/pytorchocr/modeling/heads/rec_multi_head.py": "2b8d12300f2d0155aefb77f081f8778c659e54501d5673321e3799788f4e3bb4",
"model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py": "e5c2c951ab032ab6020b8ef34f1d83e4eb25e829cf87a24099dc1beac69e0d68",
"model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py": "c2c1f16445f654eea43442d1e37794325796257ac352070fe672d67cd22b33e1",
"model/utils/pytorchocr/modeling/necks/__init__.py": "eb7e0bd72f905afe4ff28a4d89298abd0131dd4b24736d111bc0d888275b97c5",
"model/utils/pytorchocr/modeling/necks/db_fpn.py": "4cb176a52caf442d283f32f4795c8d960dd6e99bdfaf827c7c3d67ce2541eee2",
"model/utils/pytorchocr/modeling/necks/intracl.py": "c3641dc1d23d069896f76552e26a8bdf5b1511121b639dd37db0f943aa2489a6",
"model/utils/pytorchocr/modeling/necks/rnn.py": "4c052ae267b883fc97c5ab79c053a0193aa7a82d9450ad456762defb61162aa0",
"model/utils/pytorchocr/postprocess/__init__.py": "882d4e97a093c51599054c90ff9215311ea422eaeff5624f3965a8ecd02e6410",
"model/utils/pytorchocr/postprocess/cls_postprocess.py": "d555565d3fdbd6f8466fb3c6beac9f510dc8a7b2eea47eb6bcfbdaf7c1ad8d30",
"model/utils/pytorchocr/postprocess/db_postprocess.py": "01d64f17b7eb850dbb555769d0616631c5ed8afc036597d7621cc93a53f8cd4b",
"model/utils/pytorchocr/postprocess/rec_postprocess.py": "a86077a271441611e3aa4b0847520a3b1d8463df1ec1fb268c00e3ad15e0df46",
"model/utils/pytorchocr/utils/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/utils/pytorchocr/utils/resources/arch_config.yaml": "06f697b075d7572c5838562392dec7b72656884c8baef1ec1ec2587d06528436",
"model/utils/pytorchocr/utils/resources/dict/ka_dict.txt": "fad3f765943275eec2134a6fbc9b52785426641104d4e7db3a159dc73f341dde",
"model/utils/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt": "a5bc3887c43c901e5a3f97b13ffadf1c5754ede7cc8c9f5abe22e875a7c48372",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt": "7f92f7dbb9b75a4787a83bfb4f6d14a8ab515525130c9d40a9036f61cf6999e9",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt": "db40aa52ceb112055be80c694afdf655d5d2c4f7873704524cc16a447ca913ba",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt": "09c7440bfc5477e5c41052304b6b185aff8c4a5e8b2b4c23c1c706f6fe1ee9fc",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_dict.txt": "d1979e9f794c464c0d2e0b70a7fe14dd978e9dc644c0e71f14158cdf8342af1b",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt": "31defc62c0c3ad3674a82da6192226a2ba98ef4ff014a7045cb88d59f9c3de31",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_en_dict.txt": "e025a66d31f327ba0c232e03f407ae8d105e1e709e7ccb3f408aa778c24e70d6",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt": "3e95f1581557162870cacdba5af91a4c6be2890710d395b0c3c7578e7ee5e6eb",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt": "a88071c68c01707489baa79ebe0405b7beb5cca229f4fc94cc3ef992328802d7",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_latin_dict.txt": "ccbcc45730b3fbbd9050c5bc74db6a99067141ef1035e3d14889a84a6b9b1aff",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt": "85b541352ae18dc6ba6d47152d8bf8adff6b0266e605d2eef2990c1bf466117b",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt": "42f83f5d3fdb50778e4fa5b66c58d99a59ab7792151c5e74f34b8ffd7b61c9d6",
"model/utils/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt": "57f5406f94bb6688fb7077f7be65f08bbd71cecf48c01ea26c522cb5c4836b7a",
"model/utils/pytorchocr/utils/resources/models_config.yml": "408baa7aef75a5fbaac9ae096f199941290e6247be876073db53b6a4e2d03d87",
"model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml": "6bbcae78e4d4adfa59a3c0ac2babd0a246cb341d89f8fefb8a168287f2e8cef4",
"model/utils/tools/__init__.py": "c44a91eb967c60ecce2e8acb8cad0b087a2cdb35feb42bb14abc67763534d211",
"model/utils/tools/infer/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"model/utils/tools/infer/predict_cls.py": "f1198a975bde8e7665eb971a1d9355dad6ba84cb20e41fcb13e16ea823bc4fc0",
"model/utils/tools/infer/predict_det.py": "bd8411127eef10b5f106cafbd8208256f9b583057cd8e35a0b019fc542239def",
"model/utils/tools/infer/predict_rec.py": "f811fddc90e2b2ed244fa0b21c0e2995438a71bd8bf94bc393b4de8a7e6ec2de",
"model/utils/tools/infer/predict_system.py": "8647a0927ea1ab6bf6cea1d500feb5e7e93e7e44d2f2cc116126d97a8aa6488f",
"model/utils/tools/infer/pytorchocr_utility.py": "8b53c537efe479f254519e1593b8a0b354d4f207c4ad30e50d763afbc51ababc",
"model/vlm/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"model/vlm/lmdeploy_server.py": "3efc4935c508281f15cd63035de575b744874a0cff50b3b7e9903325ba69cfdd",
"model/vlm/vllm_server.py": "c3975dbac3db715684a16028fc14639b0bff630c6b73f6c23118718a1a32ca46",
"resources/fasttext-langdetect/lid.176.ftz": "e33db98de5d095f003b0645244841d33b0763864daf8d0516ae3cc1cfa759a56",
"resources/header.html": "ef1adfe9b1a5a11fb765e4c3c80f89bdabc4fcd791b940dede9d3b7042945d22",
"utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97",
"utils/block_pre_proc.py": "b86066c5fd8c47d6e99539d023cc478c223e923de9951849af485c58a89d6ce4",
"utils/block_sort.py": "e5ed6638b0775bbc6ee58d619a1bc64873cbfda438d51ff855770fe2f8d800e5",
"utils/boxbase.py": "c67180d64ee156d4d0aeb7aa94998af92037cbd79d4c780b9868aa1ab4977241",
"utils/char_utils.py": "ef84f9625af99a2d6e75d008b8992ef59eac1fbbe147bb79f79fc7eea99bbb87",
"utils/check_sys_env.py": "4d18f3838c56ca8486ae0bf829a3f6db903ef7dc4180b01f67570f706aab0400",
"utils/cli_parser.py": "e2c78502ed64ba5b189f0e96336abf7318043addad12b655908f8b34417f906c",
"utils/config_reader.py": "2115564e90676e7469724e9e5d950ac3e7dc2edee1a27e52e2ea965be4416f5c",
"utils/cut_image.py": "8379b89df7093569718be3f49295d3b659aca5790c70b09f1b0998b90f99da11",
"utils/draw_bbox.py": "164829a6353346137ebb1bc285d9211d77036af244680a4c0faa82eaaa11c1f4",
"utils/engine_utils.py": "2666a8f7e3beb190f31fbbc034a103698e8d27cb6eb612ac4ebdb72c521e04b5",
"utils/enum_class.py": "59e8edef35fe11b9af40cfda8883c24b870537f2b4fbc398ce53b93f2cacba07",
"utils/format_utils.py": "dacf3dbc77122128eea2593c1ef8372bee7ead16e24f752cede14bcd42ab34ab",
"utils/guess_suffix_or_lang.py": "6940b6c002706b92c7d121f1c136ce109a95560be9754096145ea87fc7835647",
"utils/hash_utils.py": "50f4bff0d441995ba67723afd7a2e6bfa2f2db12bc3950c911ee601ba80a2059",
"utils/language.py": "ed14f79b149aee3769a02e7249ded975d1c0ed33bb52c9e60ce5a2619031bb28",
"utils/llm_aided.py": "f56532b6fc5e9d202e696478b1342154f43987ca58d3054e1f53b6b23ffa74bb",
"utils/magic_model_utils.py": "23abdd379e9aaa140118e6aca161e225b8e75ec0705288f0eb11636d66521da5",
"utils/model_utils.py": "ea6a0e42a1394a11da24a9043573fc057240ed1096b4e1a56076779e2770999b",
"utils/models_download_utils.py": "51f8efc21c4ee819091dae494a9115359ef51a82cc3cc989a729b74c7113d93e",
"utils/ocr_utils.py": "94f22bc0d5226f99abcd4929a274581ee502763576aaf11334b4b338bc9f96b5",
"utils/os_env_config.py": "64db644782ab256ef609e2284cdcc60cbead30abff84bf27cef588b2c1966ea6",
"utils/pdf_classify.py": "e83179a47ffd52af377ec16da7b9f88be39d6101b3a0d395f4bd1505486004c4",
"utils/pdf_image_tools.py": "2f69072a815a428e021a34b577af09002ae5072731ea0c829e71656c11512aec",
"utils/pdf_page_id.py": "7a6f7aea4d760915b8463e3d44688b07ff082f09173c19d645eb40a5ac77793b",
"utils/pdf_reader.py": "59e20d9b94b25815174f4c0ff65cc86de1ecf0fe9650890dea754be57e0bcc6e",
"utils/pdf_text_tool.py": "284ced8df76ab081c7ba24c400c00becbaf5392dd1ed4afeb93a8688246345e4",
"utils/run_async.py": "acf78fe010997ab47c541c910e1898cdf6626a12d5aa8644055012e787408cd8",
"utils/span_block_fix.py": "d1e5508c90ab4f4df0a11b7d86887a52ee364e9d5d69c7c64efdb1dc1f6aabde",
"utils/span_pre_proc.py": "9eee818794d63ca1731ee15f6c4b3402caf4e0ce3138be4838dcfff062479f8e",
"utils/table_merge.py": "5f6bd00822b1f211bd222a67e1410ff295c773d8de36660d62f979cf16934b61",
"version.py": "c91a521fa9816f804981b1654fbaedf0c4a30945b5ed8731d11ce22dffa540b0"
}
}

View File

@ -1,85 +0,0 @@
{
"baseline": "PyPI mineru==2.7.1 bdist_wheel",
"url": "https://files.pythonhosted.org/packages/36/fd/d94ab07cbcfabae65a306a6d704214ec6024f443d8119e24234f1b3fa3ba/mineru-2.7.1-py3-none-any.whl",
"sha256": "3c144149f2749a79be240833c392216ddd69c1516de162b29dbaddbc0ce38f73",
"upstream_files": 187,
"local_files": 200,
"changes": [
{
"path": "mineru/backend/vlm/utils.py",
"status": "modified"
},
{
"path": "mineru/backend/vlm/vlm_analyze.py",
"status": "modified"
},
{
"path": "mineru/cli/common.py",
"status": "modified"
},
{
"path": "mineru/cli/fast_api.py",
"status": "modified"
},
{
"path": "mineru/cli/gradio_app.py",
"status": "modified"
},
{
"path": "mineru/cli/static/markmap/d3.min.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-lib.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-toolbar.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-view.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/index-B_viQAxH.css",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/index-zcV97yfy.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/markdown-_Dy2zPzC.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/vendor-DSv9k51x.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/index.html",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/d3.min.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-lib.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-toolbar.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-view.js",
"status": "added"
},
{
"path": "mineru/utils/table_merge.py",
"status": "modified"
}
]
}

View File

@ -1,6 +0,0 @@
{
"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
}

View File

@ -1,8 +0,0 @@
{
"baseline": "PyPI mineru==4.0.12 bdist_wheel",
"url": "https://files.pythonhosted.org/packages/3e/ef/cdf3279dc11a02acfeff4733a29762d2c539f9739c31e2ada8ec37705840/mineru-4.0.12-py3-none-any.whl",
"sha256": "a3ff8582a4608eb1f4dde55800ac156d59b01ceabd2ab4002bdf8e86306b1eab",
"upstream_files": 630,
"local_files": 630,
"changes": []
}

View File

@ -1,107 +0,0 @@
> 状态更新(2026-11-06):下文仅保留历史盘点,4.0.12 及后续 2.7.4 方案已被替代。当前按用户要求恢复纯官方 2.7.1,暂不加六级标题补丁;业务功能继续位于 MaxKB。参见仓库 README 和 2.7.1-baseline.json。
# MinerU 2.7.1 定制盘点与 4.0.12 合并方案
核验日期:2026-10-22。此次完成源码与发布包对比,尚未替换旧内核、安装新依赖或切换运行服务。
## 1. 基线与核验方法
分别下载 PyPI 官方 `mineru==2.7.1`、`mineru==4.0.12` wheel,验证发布元数据中的 SHA-256,再比较包内 `mineru/` 与本地源码目录。忽略 CRLF/LF 差异、`__pycache__` 和 `.pyc`,不安装依赖、不加载模型。
| 项目 | 本地位置 | 发布包比较结果 |
| --- | --- | --- |
| 旧内核 | `markitdown/mineru` | 官方 187 个文件;本地 200 个;6 个 Python 文件修改,13 个静态文件新增,无删除 |
| 新内核 | `ares/third_party/mineru/mineru` | 官方与本地各 630 个文件;全部一致 |
新内核所在独立 Git 仓库 HEAD 为 `b7f3dd0`,标签为 `mineru-4.0.12-released`,工作区干净。发布包比对进一步确认:**ares 这份 4.0.12 的 MinerU 包没有项目定制修改**。Git 仓库为浅克隆,未通过完整上游历史推断来源。
两个发布包的 URL、哈希、文件数及逐文件差异见同目录 `2.7.1-inventory.json` 和 `4.0.12-inventory.json`。该核验范围是 Python 包 `mineru/`;Dockerfile、业务调用和部署脚本另行检查,不能由包一致推导外围项目也无定制。
旧项目 Git 初始化提交 `e5d281a` 已包含部分定制;仅比较初始化提交到 HEAD 会遗漏 `common.py`、`gradio_app.py`、`table_merge.py`。因此本清单以官方发布包为基准。
## 2. 旧版包内定制:逐项迁移结论
| 文件 | 项目差异 | 4.0.12 现状 | 合并位置与处理 |
| --- | --- | --- | --- |
| `mineru/cli/common.py` | 增加 DOC/DOCX;LibreOffice 转 PDF,失败后 DOCX 使用 python-docx + ReportLab 转文本 PDF;增加解析进度回调 | 原生 Office 等格式交由 DocVortex;PDF/图片仍使用 OCR/VLM;文件完成进度已有,但不等于页级进度 | 原生 Office 路径替代转 PDF;进度改为任务内结构化事件,不照搬旧转换实现 |
| `mineru/cli/fast_api.py` | `/api/file_parse`;解析任务进度注册/查询;内存+原子 JSON 文件状态;日志和 tqdm 推断阶段;智能整理异步任务;长文标题分块、局部整理、全局合并;模型参数;OOM 提示、缓存清理;静态工作台挂载 | v1 自带任务、结果、文件、并发和终态清理机制;没有本项目智能整理接口,也没有旧版日志阶段百分比 | 解析生命周期复用 v1;兼容层只翻译协议;智能整理迁到 MaxKB AI Hub;工作台由现有 Vue 页面承接;OOM 分类和阶段事件按新架构接入 |
| `mineru/backend/vlm/utils.py` | `MINERU_GPU_MEMORY_UTILIZATION` 环境变量覆盖默认显存比例,校验 `0 < value < 1` | 新路径 `model/vlm/engine_utils.py` 有默认计算;VLM server 可显式传 `--gpu-memory-utilization`,但未保留该旧环境变量入口 | 保留旧环境变量兼容,转换到实际本地引擎参数;显式参数优先;远程 VLM 的限额在 VLM 服务端配置 |
| `mineru/backend/vlm/vlm_analyze.py` | 按 `AsyncEngineArgs` 签名过滤参数,适应运行时参数差异 | 新路径 `model/vlm/runtime.py`、新的配置/引擎依赖;4.x 未带相同过滤补丁 | 不原样复制“静默丢弃不支持参数”;厂商适配明确白名单、映射或报错,避免显存等关键配置失效 |
| `mineru/cli/gradio_app.py` | Markmap iframe 导图、普通段落提升为子标题、Word 上传和 PDF 预览、内嵌图片、ZIP 输出、页面文案和布局改造 | 新 Gradio 位于 `kit/gradio`,主项目已有 Vue 工作台 | 保留用户可见能力于 Vue,保留现有风格;不把旧 Gradio 整页移进新版内核 |
| `mineru/utils/table_merge.py` | 新增 `(…continued)` 后缀和 caption 内 `(continued)` 匹配;存在续表标识时允许前表最多一条脚注;合并时清掉前表脚注再接后表脚注 | 新架构的通用表格处理主要归 DocVortex,MinerU 另有 LLM 跨页单元格合并;不能把“已有表格合并”当作旧规则完全等价 | 用真实续表样本验证;需要的规则在新后处理扩展点/依赖层迁移;旧版删除脚注的行为需重点核验,不能无条件照搬造成内容丢失 |
新增 13 个静态文件:4 个 `cli/static/markmap` 资源、9 个 `cli/static/web` 页面及依赖资源。它们属于旧界面交付,不是 OCR 算法或天数算子补丁。
旧进度并非完整的引擎真实完成率:包含固定权重日志阶段和文件回调;使用进程全局当前任务 ID、日志 sink 和 stderr 捕获。迁移后要提供任务隔离的阶段事件;只有明确页数/块数时才显示可计算比例,模型加载等阶段显示文字和耗时。
旧长文整理也不宜逐行照搬:它使用估算 token 预算和分块合并,需要补充超长单段切分、超限/截断识别、失败重试及图片引用保留验证。
## 3. 天数适配实际在哪里
旧项目相对官方 2.7.1 **未发现额外修改 OCR/表格/公式模型或新增天数算子源码**。可见的项目适配主要在:
- `docker/china/Dockerfile.corex`、`docker/china/Dockerfile`:采用天数 CoreX 厂商镜像,保留厂商 Torch/vLLM;使用 `--no-deps` 安装及补齐依赖。
- `scripts/build-images.sh`:区分 CoreX/CUDA 构建,默认 CoreX。
- `scripts/start-mindmap.sh`:设置显存比例与 CoreX `PYTHONPATH`。
- `docker/entrypoint.mineru-api.sh`:注入本地 pipeline/VLM 模型路径、公式分隔符和旧 JSON 配置。
- 包内两项 VLM 补丁:显存比例环境变量、AsyncEngineArgs 参数过滤。
这不覆盖厂商基础镜像中未展开的私有补丁、驱动或 wheel 内容,不能凭仓库源码证明这些二进制已兼容新版。
| 项目 | 旧 CoreX 镜像/项目 | 4.0.12 源码要求或现状 |
| --- | --- | --- |
| 基础运行时 | CoreX 4.4.0 / Torch 2.7.1 / vLLM 0.11.2 / Python 3.10 | `torch` extra:Torch >=2.7,<3、Transformers >=5.10.1,<6;`full` extra:Linux vLLM >=0.19.1,<0.29 |
| VLM 工具依赖 | mineru-vl-utils 0.x 范围 | mineru-vl-utils >=2.0.5,<3 |
| 安装 extras | core/pipeline/vlm 等旧分组 | torch/full/all;不能继续照搬 `[core]` |
| 通用文档转换 | 旧 Word 转 PDF | DocVortex >=0.5.16,<1 原生转换 |
| 配置 | 旧 mineru.json、pipeline/vlm 目录 | 新 config.yaml / `MINERU_CONFIG`、`model.base_dir`、`model.small_backend`、`model.vlm`;模型也要单独核对 |
| 天数参数分支 | 依赖厂商运行环境与旧引擎 | 仍有 `MINERU_VLLM_DEVICE=corex` 和编译参数分支;不等于依赖组合/硬件已验证 |
4.0.12 自带 `docs/zh/usage/compatibility.md` 明确:旧 13 类平台适配指南只适用于 MinerU <4,4.0 不自动继承兼容保证。保留的 `docker/china/corex.Dockerfile` 也实际安装 `mineru[core]>=3.4.0,<4`,**不能把它当成 4.0.12 天数镜像**。
另一个版本隐患:旧 CoreX Dockerfile 安装 `mineru[core]>=2.7.4 --no-deps`,随后复制版本号为 2.7.1 的本地源码。镜像内 distribution metadata 与实际 import 的源码可能不同;新构建应固定版本、打印安全的来源清单并校验导入路径,避免混用。
旧启动脚本含删除重建容器、递归 chmod 等步骤,只供审阅,不应用于此次增量发布。旧 entrypoint 每次重写 JSON 配置,也不能直接用于新版配置。
## 4. ares 外围接入:哪些沿用、哪些不迁
`ares/code/backend/services/parser.py` 的 `_parse_pdf_mineru`:
- multipart 同步调用 `/v1/file_parse?tier=basic`,最长等待 1200 秒。
- 读取 `files[].content.markdown`,提取首标题作为文档名。
- 将 Markdown 中 `data:image/...;base64,...` 替换成 `[图片]`。
- PDF 页数达到阈值(默认 8)或文本密度低时才选择 MinerU,失败则继续本地 PDF/OCR 路线。
以上是 ares 的业务集成,不是 4.0.12 内核定制。当前 MaxKB/思维导图已有异步解析资源和图片资产机制,继续使用自己的集成;不复制“图片改占位符”及静默降级策略。
## 5. 统一到 4.0.12 的落点
目标:主维护目录仍在 `markitdown` 和 `maxkb`,`ares` 只提供已核验的源码来源。保留旧版可回退版本;最终活动内核固定为 4.0.12,项目补丁单独登记。
| 层 | 负责的能力 |
| --- | --- |
| MinerU 4.0.12 | 格式识别、原生 Office、PDF/图片 OCR/VLM、渲染输出、模型生命周期 |
| 项目解析扩展 | 结构化阶段进度、必要的续表规则、经过验证的天数引擎/显存配置 |
| 兼容层 | 有实际调用者时保留旧 `/api/file_parse`、任务查询和结果结构;不重新实现一套任务执行器 |
| MaxKB AI Hub | 资源授权、默认服务/流程、智能整理与长文分块、任务和成果、图片资产鉴权及缓存 |
| 思维导图 Vue 工作台 | 直接上传原文件、Markdown/导图预览、折叠状态、图片展示和导出 |
| 部署配置 | 独立虚拟环境或镜像、固定依赖、本地模型挂载、安全增量启动与回退 |
4.0.12 并不是每种格式都走四档模型:Office/HTML/CSV/EPUB/OFD 等为原生 Flash 路径,PDF/图片才是质量分档解析。前端和服务端需按格式路由,不能把 DOCX 原文件上传后仍机械传 PDF 专用页范围或任意档位。
当前两个需要补齐的业务差异:
1. `web_ui/src/composables/useDocumentProcessor.ts` 仍在上传前做 Word→PDF;应改为原文件直传,旧资源仅在明确需要时回退。
2. `maxkb/apps/system_manage/ai_hub_worker.py` 当前智能整理对超过 60000 字符的输入直接拒绝;旧服务的分块整理能力尚未等价迁入。
## 6. 合并与验收顺序
1. 固定官方 4.0.12 来源与依赖清单,保留旧源代码回退点;移入主维护目录时保留官方许可证及声明,不复制 ares 的虚拟环境、业务数据或凭据。
2. 迁移原文件上传及按格式路由;复用 AI Hub 图片资产、任务和结果处理,验证 DOC/DOCX、表格、幻灯片、PDF 和图片。图片型 Office 内容是否 OCR 需按真实文档单独验收。
3. 迁入长文整理,保留标题、图片引用、上下文预算和中间结果;验证超长单段、多块、模型失败和截断。
4. 在 v1 任务中增加结构化阶段/页块进度,贯通 AI Hub 与工作台;验证多任务互不串状态,不用旧日志百分比模拟真实完成率。
5. 按真实样本校验续表的 caption、脚注和跨页单元格;确认 DocVortex 已覆盖的行为后只补缺失规则。
6. 适配 CoreX:优先验证“4.0.12 文档服务 + 独立厂商 VLM 服务”的可行性(协议、模型、OCR 后端均需验证);若选择本地引擎,则先取得兼容的新厂商依赖组合,不在旧镜像中盲目升级。
7. 通过本地检查及隔离接口验证后,按增量发布约定部署;涉及页面同时发布 8080 使用的 `/admin/` 构建产物。检查远端差异和入口,保留旧服务回退,真实验证后再完成默认资源切换。
尚未完成的验证:4.0.12 在目标天数硬件上的模型启动/精度/显存/持续运行;续表规则的新旧等价性;新原生格式在工作台和知识库全链路的验收。本次源码审计不能替代这些运行测试。

View File

@ -1,37 +0,0 @@
# MinerU 与天数发布基线核查 · 2026-11-06
更新:用户随后明确要求恢复 2.7.1。现已恢复官方 2.7.1 的全部 187 个文件,移除三处六级标题补丁及其它内核定制,CoreX/CUDA 构建恢复原厂商镜像和安装流程,仅固定 MinerU 为 `==2.7.1` 并增加完整性检查。以下表格是改动前的核查记录,保留用于追溯;恢复源码不代表 MR100 真机验收通过。
## 当前事实
| 对象 | 核查结果 |
|---|---|
| `develop` 源码 | `mineru/version.py` 为 2.7.1 |
| `develop-refact` 源码 | 2.7.4,187 个包内文件;相对登记的官方 2.7.4 仅 3 个文件有六级标题保留改动 |
| 两分支 Python 依赖声明 | 主依赖、extras、Python 版本要求完全相同,pyproject 的差异仅是 README 路径 |
| CoreX 基础镜像声明 | 两分支均为 CoreX 4.4.0 / Torch 2.7.1 / vLLM 0.11.2 / Python 3.10 的同一厂商镜像标签 |
| 旧 CoreX 构建方式 | 先安装 `mineru[core]>=2.7.4 --no-deps`,补依赖后复制版本号 2.7.1 的本地源码;不能由版本号认定完整环境等于官方 2.7.1 |
| 当前 52.118 旧 CUDA 镜像 | 源码与安装元数据均 2.7.1;Torch 2.9.0、Torchvision 0.24.0、vLLM 0.11.2、Transformers 4.57.6、NumPy 2.2.6、OpenCV 5.0.0.93。这不是天数环境验证结果 |
旧源码到新源码的差异同时包含业务下沉 MaxKB 和上游内核更新,不能用总 diff 行数衡量 GPU 适配风险。当前三处项目内核定制只是保留已识别的五/六级标题,不是新增标题识别。官方 2.7.4 中还增加了 CoreX 编译配置分支;旧 2.7.1 定制中则存在按 AsyncEngineArgs 签名筛参数的补丁。新入口继续将显存环境变量转成启动参数。两者不能只改版本号就视为等价环境。
## 找到的旧天数离线包
- 位置:`/home/tlw/unis/deploy_artifacts/unis-mindmap-api-corex-latest.tar`
- 大小:5,148,194,816 bytes
- 镜像标签:`unis-mindmap-api:corex`
- 镜像 ID:`sha256:e62ab163bb950875307adeda9d4e0923eaed51a92a29c1ab89f52ac34cf15a21`
- 归档 SHA256:`8c41177ab73119d6032254fe4c2d7af3eae81436df4e34cbfd2ac032bbdfc1b7`
- 归档中最后生效的 `/app/mineru/version.py`:2.7.1;镜像环境 `COREX_VERSION=4.4.0`;架构 amd64。
核查直接读取 tar 的 manifest、镜像配置和小型源代码层并计算哈希,未将该包加载进 Docker、未启动 CoreX 容器。没有遍历/导入全部厂商二进制,更没有 MR100 实机验证;是否正是当初跑通的那份包仍需与既有交付记录对应。
## 建议
无 MR100 真机时,本次天数发布优先以原完整 CoreX 镜像作为兼容基线候选,避免同时重建依赖和更换解析内核;保留 2.7.4 重构分支供后续升级验证。MaxKB 的新工作台、任务、总结、授权及数据迁移继续保留,不回退整条 `develop` 业务分支。
只重新构建 2.7.1 源码不等于恢复旧环境:两个版本的依赖范围相同,仍会解析到新的依赖;厂商 Torch/vLLM、NumPy、模型权重、驱动和引擎参数也共同决定兼容性。没有实际显卡时,CPU 导入/接口模拟检查不能证明 GPU 算子、模型加载、显存或长文解析可用。
旧镜像若接入新版还需要最小协议兼容验证:旧路径 `/api/file_parse`,新版 `/file_parse`;同步返回均有 `results` / `md_content`,但平台的版本目录、资源连通性检查及部署启动校验当前固定 2.7.4。现有升级脚本会拒绝直接替入未标记的旧镜像,不能把本记录当作可直接替换标签的操作手册。
采用上述旧交付镜像时仍需核对是否为原交付包,并处理它的旧 API 路径。当前纯官方 2.7.1 自身提供 `/file_parse`,不带原项目的 `/api` 前缀;无需为新源码恢复旧业务接口。拿到 MR100 后仍需完成真实 PDF/图片、公式、表格、显存及连续任务验收。

View File

@ -26,6 +26,7 @@ if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":
pdf_suffixes = ["pdf"] pdf_suffixes = ["pdf"]
image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"] image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"]
word_suffixes = ["docx", "doc"]
os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["TOKENIZERS_PARALLELISM"] = "false"
@ -39,6 +40,109 @@ def read_fn(path):
return images_bytes_to_pdf_bytes(file_bytes) return images_bytes_to_pdf_bytes(file_bytes)
elif file_suffix in pdf_suffixes: elif file_suffix in pdf_suffixes:
return file_bytes 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: else:
raise Exception(f"Unknown file suffix: {file_suffix}") raise Exception(f"Unknown file suffix: {file_suffix}")
@ -237,6 +341,7 @@ async def _async_process_vlm(
f_dump_content_list, f_dump_content_list,
f_make_md_mode, f_make_md_mode,
server_url=None, server_url=None,
progress_callback=None,
**kwargs, **kwargs,
): ):
"""异步处理VLM后端逻辑""" """异步处理VLM后端逻辑"""
@ -245,15 +350,24 @@ async def _async_process_vlm(
if not backend.endswith("client"): if not backend.endswith("client"):
server_url = None server_url = None
total_files = len(pdf_bytes_list)
for idx, pdf_bytes in enumerate(pdf_bytes_list): for idx, pdf_bytes in enumerate(pdf_bytes_list):
pdf_file_name = pdf_file_names[idx] pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method) 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) 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( middle_json, infer_result = await aio_vlm_doc_analyze(
pdf_bytes, image_writer=image_writer, backend=backend, server_url=server_url, **kwargs, 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"] pdf_info = middle_json["pdf_info"]
_process_output( _process_output(
@ -375,6 +489,7 @@ async def _async_process_hybrid(
f_dump_content_list, f_dump_content_list,
f_make_md_mode, f_make_md_mode,
server_url=None, server_url=None,
progress_callback=None,
**kwargs, **kwargs,
): ):
from mineru.backend.hybrid.hybrid_analyze import aio_doc_analyze as aio_hybrid_doc_analyze from mineru.backend.hybrid.hybrid_analyze import aio_doc_analyze as aio_hybrid_doc_analyze
@ -382,11 +497,16 @@ async def _async_process_hybrid(
if not backend.endswith("client"): if not backend.endswith("client"):
server_url = None server_url = None
total_files = len(pdf_bytes_list)
for idx, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, h_lang_list)): for idx, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, h_lang_list)):
pdf_file_name = pdf_file_names[idx] pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}") 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) 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( middle_json, infer_result, _vlm_ocr_enable = await aio_hybrid_doc_analyze(
pdf_bytes, pdf_bytes,
image_writer=image_writer, image_writer=image_writer,
@ -398,6 +518,10 @@ async def _async_process_hybrid(
**kwargs, **kwargs,
) )
# 更新进度
if progress_callback:
progress_callback(((idx + 1) / total_files) * 100, f"完成文件 {idx+1}/{total_files}")
pdf_info = middle_json["pdf_info"] pdf_info = middle_json["pdf_info"]
# f_draw_span_bbox = not _vlm_ocr_enable # f_draw_span_bbox = not _vlm_ocr_enable
@ -503,6 +627,7 @@ async def aio_do_parse(
f_make_md_mode=MakeMode.MM_MD, f_make_md_mode=MakeMode.MM_MD,
start_page_id=0, start_page_id=0,
end_page_id=None, end_page_id=None,
progress_callback=None,
**kwargs, **kwargs,
): ):
# 预处理PDF字节数据 # 预处理PDF字节数据
@ -529,11 +654,12 @@ async def aio_do_parse(
os.environ['MINERU_VLM_FORMULA_ENABLE'] = str(formula_enable) os.environ['MINERU_VLM_FORMULA_ENABLE'] = str(formula_enable)
os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable) os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
# 传递进度回调
await _async_process_vlm( await _async_process_vlm(
output_dir, pdf_file_names, pdf_bytes_list, backend, 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_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, f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
server_url, **kwargs, server_url, progress_callback=progress_callback, **kwargs,
) )
elif backend.startswith("hybrid-"): elif backend.startswith("hybrid-"):
backend = backend[7:] backend = backend[7:]
@ -547,11 +673,12 @@ async def aio_do_parse(
os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable) os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
os.environ['MINERU_VLM_FORMULA_ENABLE'] = "true" os.environ['MINERU_VLM_FORMULA_ENABLE'] = "true"
# 传递进度回调
await _async_process_hybrid( await _async_process_hybrid(
output_dir, pdf_file_names, pdf_bytes_list, p_lang_list, parse_method, formula_enable, backend, 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_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, f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
server_url, **kwargs, server_url, progress_callback=progress_callback, **kwargs,
) )

View File

@ -4,100 +4,239 @@ import os
import re import re
import tempfile import tempfile
import asyncio import asyncio
import threading
import uvicorn import uvicorn
import click import click
import zipfile import zipfile
from pathlib import Path from pathlib import Path
import glob import glob
from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form, APIRouter, Header
from fastapi.middleware.gzip import GZipMiddleware from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from starlette.background import BackgroundTask from starlette.background import BackgroundTask
from typing import List, Optional from typing import List, Optional
from loguru import logger from loguru import logger
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
logger.remove() # 移除默认handler
logger.add(sys.stderr, level=log_level) # 添加新handler
from base64 import b64encode from base64 import b64encode
from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes # MinerU 内部导入
from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes, word_suffixes
from mineru.utils.cli_parser import arg_parse from mineru.utils.cli_parser import arg_parse
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
from mineru.version import __version__ from mineru.version import __version__
# 并发控制器 # --- 日志配置 ---
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
logger.remove()
logger.add(sys.stderr, level=log_level)
# --- 全局变量与辅助类 ---
_request_semaphore: Optional[asyncio.Semaphore] = None _request_semaphore: Optional[asyncio.Semaphore] = None
# 并发控制依赖函数 # --- 任务进度跟踪 ---
_task_progress: dict = {}
def _update_task_progress(task_id: Optional[str], progress: int, stage: str):
"""更新任务进度(安全调用,task_id 为 None 时静默跳过)"""
if task_id and task_id in _task_progress:
_task_progress[task_id]["progress"] = min(progress, 100)
_task_progress[task_id]["stage"] = stage
class ProgressTracker:
def __init__(self):
self.progress = 0
self.status = "初始化"
def update(self, progress: float, status: str):
self.progress = progress
self.status = status
def get_progress(self):
return {"progress": self.progress, "status": self.status}
# --- 当前活跃任务ID(用于日志捕获) ---
_current_task_id: Optional[str] = None
def _log_progress_sink(message):
"""loguru 日志捕获:根据日志内容自动更新进度"""
task_id = _current_task_id
if not task_id or task_id not in _task_progress:
return
try:
msg = str(message)
except Exception:
return
# VLM 引擎加载阶段 (5% ~ 40%)
if "Automatically detected platform" in msg:
_update_task_progress(task_id, 7, "检测计算平台")
elif "Resolved architecture" in msg:
_update_task_progress(task_id, 10, "解析模型架构")
elif "Starting to load model" in msg:
_update_task_progress(task_id, 12, "开始加载模型权重")
elif "Loading weights took" in msg:
_update_task_progress(task_id, 18, "模型权重加载完成")
elif "Model loading took" in msg:
_update_task_progress(task_id, 22, "模型加载完成,初始化引擎")
elif "Dynamo bytecode transform" in msg:
_update_task_progress(task_id, 27, "编译优化计算图")
elif "torch.compile takes" in msg:
_update_task_progress(task_id, 30, "计算图编译完成")
elif "Available KV cache memory" in msg:
_update_task_progress(task_id, 32, "分配显存缓存")
elif "Graph capturing finished" in msg:
_update_task_progress(task_id, 36, "CUDA图捕获完成")
elif "init engine" in msg and "took" in msg:
_update_task_progress(task_id, 38, "VLM引擎初始化完成")
elif "get vllm" in msg and "predictor cost" in msg:
_update_task_progress(task_id, 40, "VLM预测器就绪")
elif "hybrid batch ratio" in msg:
_update_task_progress(task_id, 42, "开始文档分析")
# VLM 推理阶段 (40% ~ 65%) 由 progress_callback 处理
# Pipeline 模型加载和推理阶段 (65% ~ 97%)
elif "Target directory already exists" in msg:
cur = _task_progress.get(task_id, {}).get("progress", 0)
if cur < 75:
_update_task_progress(task_id, max(cur, 66), "加载Pipeline模型")
elif "MFD Predict:" in msg:
_update_task_progress(task_id, 78, "数学公式检测")
elif "MFR Predict:" in msg:
_update_task_progress(task_id, 85, "数学公式识别")
elif "OCR-det:" in msg:
_update_task_progress(task_id, 90, "文字区域检测")
elif "OCR-rec Predict:" in msg:
_update_task_progress(task_id, 95, "文字识别")
elif "local output dir is" in msg:
_update_task_progress(task_id, 97, "保存输出结果")
class _StderrProgressCapture:
"""后台线程捕获 stderr 中的 tqdm 进度条输出,解析并更新任务进度"""
# tqdm 进度条模式:名称: 百分比|...| 当前/总数
_PATTERNS = [
(re.compile(r'Two Step Extraction:\s*(\d+)%.*?(\d+)/(\d+)'), 'extract'),
(re.compile(r'MFD Predict:\s*(\d+)%.*?(\d+)/(\d+)'), 'mfd'),
(re.compile(r'MFR Predict:\s*(\d+)%.*?(\d+)/(\d+)'), 'mfr'),
(re.compile(r'OCR-det:\s*(\d+)%.*?(\d+)/(\d+)'), 'ocr_det'),
(re.compile(r'OCR-rec Predict:\s*(\d+)%.*?(\d+)/(\d+)'), 'ocr_rec'),
(re.compile(r'Loading safetensors.*?:\s*(\d+)%'), 'load_model'),
(re.compile(r'Capturing CUDA graphs.*?:\s*(\d+)%'), 'cuda_graph'),
]
# 各阶段的进度映射范围 [start%, end%]
_RANGES = {
'load_model': (12, 18),
'cuda_graph': (33, 37),
'extract': (42, 65),
'mfd': (75, 80),
'mfr': (80, 87),
'ocr_det': (87, 92),
'ocr_rec': (92, 96),
}
_STAGE_LABELS = {
'load_model': '加载模型权重',
'cuda_graph': '捕获CUDA计算图',
'extract': 'VLM文档分析',
'mfd': '数学公式检测',
'mfr': '数学公式识别',
'ocr_det': '文字区域检测',
'ocr_rec': '文字识别',
}
def __init__(self, task_id: str):
self.task_id = task_id
self._active = False
self._thread: Optional[threading.Thread] = None
self._orig_stderr = None
def start(self):
self._active = True
self._orig_stderr = sys.stderr
self._thread = threading.Thread(target=self._reader_loop, daemon=True)
self._thread.start()
def stop(self):
self._active = False
if self._thread and self._thread.is_alive():
self._thread.join(timeout=2)
self._thread = None
def _reader_loop(self):
buf = ""
orig = self._orig_stderr
while self._active:
try:
ch = orig.read(1)
if not ch:
break
buf += ch
# tqdm 用 \r 更新同一行,\n 表示新行
if ch == '\r' or ch == '\n':
if buf.strip():
self._parse_line(buf.strip())
buf = ""
except Exception:
break
def _parse_line(self, line: str):
for pattern, stage in self._PATTERNS:
m = pattern.search(line)
if m:
pct = int(m.group(1))
lo, hi = self._RANGES.get(stage, (0, 100))
mapped = lo + int((hi - lo) * pct / 100)
label = self._STAGE_LABELS.get(stage, stage)
if stage == 'extract' and len(m.groups()) >= 3:
cur, total = m.group(2), m.group(3)
label = f"VLM文档分析 ({cur}/{total}页)"
elif stage in ('mfd', 'mfr', 'ocr_det', 'ocr_rec') and len(m.groups()) >= 3:
cur, total = m.group(2), m.group(3)
label = f"{label} ({cur}/{total})"
_update_task_progress(self.task_id, mapped, label)
break
async def limit_concurrency(): async def limit_concurrency():
if _request_semaphore is not None: if _request_semaphore is not None:
if _request_semaphore.locked(): if _request_semaphore.locked():
raise HTTPException( raise HTTPException(
status_code=503, status_code=503,
detail=f"Server is at maximum capacity: {os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS', 'unset')}. Please try again later." detail=f"Server is at maximum capacity: {os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS', '0')}."
) )
async with _request_semaphore: async with _request_semaphore:
yield yield
else: else:
yield yield
def create_app():
# By default, the OpenAPI documentation endpoints (openapi_url, docs_url, redoc_url) are enabled.
# To disable the FastAPI docs and schema endpoints, set the environment variable MINERU_API_ENABLE_FASTAPI_DOCS=0.
enable_docs = str(os.getenv("MINERU_API_ENABLE_FASTAPI_DOCS", "1")).lower() in ("1", "true", "yes")
app = FastAPI(
openapi_url="/openapi.json" if enable_docs else None,
docs_url="/docs" if enable_docs else None,
redoc_url="/redoc" if enable_docs else None,
)
# 初始化并发控制器:从环境变量MINERU_API_MAX_CONCURRENT_REQUESTS读取
global _request_semaphore
try:
max_concurrent_requests = int(os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "0"))
except ValueError:
max_concurrent_requests = 0
if max_concurrent_requests > 0:
_request_semaphore = asyncio.Semaphore(max_concurrent_requests)
logger.info(f"Request concurrency limited to {max_concurrent_requests}")
app.add_middleware(GZipMiddleware, minimum_size=1000)
return app
app = create_app()
def sanitize_filename(filename: str) -> str: def sanitize_filename(filename: str) -> str:
"""
格式化压缩文件的文件名
移除路径遍历字符, 保留 Unicode 字母、数字、._-
禁止隐藏文件
"""
sanitized = re.sub(r'[/\\\.]{2,}|[/\\]', '', filename) sanitized = re.sub(r'[/\\\.]{2,}|[/\\]', '', filename)
sanitized = re.sub(r'[^\w.-]', '_', sanitized, flags=re.UNICODE) sanitized = re.sub(r'[^\w.-]', '_', sanitized, flags=re.UNICODE)
if sanitized.startswith('.'): if sanitized.startswith('.'):
sanitized = '_' + sanitized[1:] sanitized = '_' + sanitized[1:]
return sanitized or 'unnamed' return sanitized or 'unnamed'
def cleanup_file(file_path: str) -> None: def cleanup_file(file_path: str) -> None:
"""清理临时 zip 文件"""
try: try:
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
except Exception as e: except Exception as e:
logger.warning(f"fail clean file {file_path}: {e}") logger.warning(f"fail clean file {file_path}: {e}")
def encode_image(image_path: str) -> str: def encode_image(image_path: str) -> str:
"""Encode image using base64"""
with open(image_path, "rb") as f: with open(image_path, "rb") as f:
return b64encode(f.read()).decode() return b64encode(f.read()).decode()
def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str) -> Optional[str]: def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str) -> Optional[str]:
"""从结果文件中读取推理结果"""
result_file_path = os.path.join(parse_dir, f"{pdf_name}{file_suffix_identifier}") result_file_path = os.path.join(parse_dir, f"{pdf_name}{file_suffix_identifier}")
if os.path.exists(result_file_path): if os.path.exists(result_file_path):
with open(result_file_path, "r", encoding="utf-8") as fp: with open(result_file_path, "r", encoding="utf-8") as fp:
@ -105,266 +244,240 @@ def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str)
return None return None
@app.post(path="/file_parse", dependencies=[Depends(limit_concurrency)]) # --- 创建 API 路由组 ---
async def parse_pdf( api_router = APIRouter(prefix="/api")
files: List[UploadFile] = File(..., description="Upload pdf or image files for parsing"),
output_dir: str = Form("./output", description="Output local directory"),
lang_list: List[str] = Form(
["ch"],
description="""(Adapted only for pipeline and hybrid backend)Input the languages in the pdf to improve OCR accuracy.Options:
- 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.
- th: Thai, English.
- el: Greek, English.
- 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.
"""
),
backend: str = Form(
"hybrid-auto-engine",
description="""The backend for parsing:
- pipeline: More general, supports multiple languages, hallucination-free.
- vlm-auto-engine: High accuracy via local computing power, supports Chinese and English documents only.
- vlm-http-client: High accuracy via remote computing power(client suitable for openai-compatible servers), supports Chinese and English documents only.
- hybrid-auto-engine: Next-generation high accuracy solution via local computing power, supports multiple languages.
- hybrid-http-client: High accuracy via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages."""
),
parse_method: str = Form(
"auto",
description="""(Adapted only for pipeline and hybrid backend)The method for parsing PDF:
- auto: Automatically determine the method based on the file type
- txt: Use text extraction method
- ocr: Use OCR method for image-based PDFs
"""
),
formula_enable: bool = Form(True, description="Enable formula parsing."),
table_enable: bool = Form(True, description="Enable table parsing."),
server_url: Optional[str] = Form(
None,
description="(Adapted only for <vlm/hybrid>-http-client backend)openai compatible server url, e.g., http://127.0.0.1:30000"
),
return_md: bool = Form(True, description="Return markdown content in response"),
return_middle_json: bool = Form(False, description="Return middle JSON in response"),
return_model_output: bool = Form(False, description="Return model output JSON in response"),
return_content_list: bool = Form(False, description="Return content list JSON in response"),
return_images: bool = Form(False, description="Return extracted images in response"),
response_format_zip: bool = Form(False, description="Return results as a ZIP file instead of JSON"),
start_page_id: int = Form(0, description="The starting page for PDF parsing, beginning from 0"),
end_page_id: int = Form(99999, description="The ending page for PDF parsing, beginning from 0"),
):
# 获取命令行配置参数
@api_router.get("/parse_progress/{task_id}")
async def get_parse_progress(task_id: str):
"""查询解析任务的实时进度"""
if task_id not in _task_progress:
raise HTTPException(status_code=404, detail="Task not found")
return _task_progress[task_id]
@api_router.post(path="/file_parse", dependencies=[Depends(limit_concurrency)])
async def parse_pdf(
files: List[UploadFile] = File(..., description="Upload pdf, image, or Word files for parsing"),
output_dir: str = Form("./output", description="Output local directory"),
lang_list: List[str] = Form(["ch"]),
backend: str = Form("hybrid-auto-engine"),
parse_method: str = Form("auto"),
formula_enable: bool = Form(True),
table_enable: bool = Form(True),
server_url: Optional[str] = Form(None),
return_md: bool = Form(True),
return_middle_json: bool = Form(False),
return_model_output: bool = Form(False),
return_content_list: bool = Form(False),
return_images: bool = Form(False),
response_format_zip: bool = Form(False),
start_page_id: int = Form(0),
end_page_id: int = Form(99999),
x_task_id: Optional[str] = Header(None),
):
# 从 app 实例状态中获取配置 (FastAPI 实例会在下方创建)
from fastapi import Request
config = getattr(app.state, "config", {}) config = getattr(app.state, "config", {})
# 初始化进度跟踪
task_id = x_task_id or str(uuid.uuid4())
file_names_str = ", ".join(f.filename or "unknown" for f in files)
_task_progress[task_id] = {
"progress": 0, "stage": "准备中", "status": "processing",
"error": None, "file_names": file_names_str,
}
try: try:
# 创建唯一的输出目录
unique_dir = os.path.join(output_dir, str(uuid.uuid4())) unique_dir = os.path.join(output_dir, str(uuid.uuid4()))
os.makedirs(unique_dir, exist_ok=True) os.makedirs(unique_dir, exist_ok=True)
# 处理上传的PDF文件
pdf_file_names = [] pdf_file_names = []
pdf_bytes_list = [] pdf_bytes_list = []
for file in files: for file in files:
content = await file.read() content = await file.read()
file_path = Path(file.filename) file_path = Path(file.filename)
# 创建临时文件
temp_path = Path(unique_dir) / file_path.name temp_path = Path(unique_dir) / file_path.name
with open(temp_path, "wb") as f: with open(temp_path, "wb") as f:
f.write(content) f.write(content)
# 如果是图像文件或PDF,使用read_fn处理
file_suffix = guess_suffix_by_path(temp_path) file_suffix = guess_suffix_by_path(temp_path)
if file_suffix in pdf_suffixes + image_suffixes: if file_suffix in pdf_suffixes + image_suffixes + word_suffixes:
try: try:
pdf_bytes = read_fn(temp_path) pdf_bytes = read_fn(temp_path)
pdf_bytes_list.append(pdf_bytes) pdf_bytes_list.append(pdf_bytes)
pdf_file_names.append(file_path.stem) pdf_file_names.append(file_path.stem)
os.remove(temp_path) # 删除临时文件 os.remove(temp_path)
except Exception as e: except Exception as e:
return JSONResponse( return JSONResponse(status_code=400, content={"error": f"Failed to load file: {str(e)}"})
status_code=400,
content={"error": f"Failed to load file: {str(e)}"}
)
else: else:
return JSONResponse( return JSONResponse(status_code=400, content={"error": f"Unsupported file type: {file_suffix}"})
status_code=400,
content={"error": f"Unsupported file type: {file_suffix}"}
)
# 设置语言列表,确保与文件数量一致
actual_lang_list = lang_list actual_lang_list = lang_list
if len(actual_lang_list) != len(pdf_file_names): if len(actual_lang_list) != len(pdf_file_names):
# 如果语言列表长度不匹配,使用第一个语言或默认"ch"
actual_lang_list = [actual_lang_list[0] if actual_lang_list else "ch"] * len(pdf_file_names) actual_lang_list = [actual_lang_list[0] if actual_lang_list else "ch"] * len(pdf_file_names)
# 调用异步处理函数 # 进度回调:将 common.py 内部进度映射为细粒度阶段
def progress_callback(pct, msg):
msg_str = str(msg)
if "处理文件" in msg_str:
_update_task_progress(task_id, 40, f"VLM文档分析: {msg_str}")
elif "完成文件" in msg_str:
_update_task_progress(task_id, 65, f"VLM分析完成: {msg_str}")
else:
_update_task_progress(task_id, int(40 + pct * 0.25), msg_str)
_update_task_progress(task_id, 5, "开始解析文档")
# 设置日志捕获(将当前任务ID绑定到日志 sink)
global _current_task_id
_current_task_id = task_id
sink_id = logger.add(_log_progress_sink, level="DEBUG")
# 启动 stderr 捕获(解析 tqdm 进度条输出)
stderr_capture = _StderrProgressCapture(task_id)
stderr_capture.start()
await aio_do_parse( await aio_do_parse(
output_dir=unique_dir, output_dir=unique_dir, pdf_file_names=pdf_file_names, pdf_bytes_list=pdf_bytes_list,
pdf_file_names=pdf_file_names, p_lang_list=actual_lang_list, backend=backend, parse_method=parse_method,
pdf_bytes_list=pdf_bytes_list, formula_enable=formula_enable, table_enable=table_enable, server_url=server_url,
p_lang_list=actual_lang_list, f_draw_layout_bbox=False, f_draw_span_bbox=False, f_dump_md=return_md,
backend=backend, f_dump_middle_json=return_middle_json, f_dump_model_output=return_model_output,
parse_method=parse_method, f_dump_orig_pdf=False, f_dump_content_list=return_content_list,
formula_enable=formula_enable, start_page_id=start_page_id, end_page_id=end_page_id,
table_enable=table_enable, progress_callback=progress_callback, **config
server_url=server_url,
f_draw_layout_bbox=False,
f_draw_span_bbox=False,
f_dump_md=return_md,
f_dump_middle_json=return_middle_json,
f_dump_model_output=return_model_output,
f_dump_orig_pdf=False,
f_dump_content_list=return_content_list,
start_page_id=start_page_id,
end_page_id=end_page_id,
**config
) )
# 根据 response_format_zip 决定返回类型 _update_task_progress(task_id, 97, "生成结果文件")
_update_task_progress(task_id, 100, "转换完成")
_task_progress[task_id]["status"] = "completed"
# 清理日志捕获和 stderr 捕获
stderr_capture.stop()
logger.remove(sink_id)
_current_task_id = None
if response_format_zip: if response_format_zip:
zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_results_") zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_results_")
os.close(zip_fd) os.close(zip_fd)
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for pdf_name in pdf_file_names: for pdf_name in pdf_file_names:
safe_pdf_name = sanitize_filename(pdf_name) safe_pdf_name = sanitize_filename(pdf_name)
# 路径匹配逻辑
if backend.startswith("pipeline"): if backend.startswith("pipeline"):
parse_dir = os.path.join(unique_dir, pdf_name, parse_method) p_dir = os.path.join(unique_dir, pdf_name, parse_method)
elif backend.startswith("vlm"): elif backend.startswith("vlm"):
parse_dir = os.path.join(unique_dir, pdf_name, "vlm") p_dir = os.path.join(unique_dir, pdf_name, "vlm")
elif backend.startswith("hybrid"): else:
parse_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}") p_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}")
if not os.path.exists(parse_dir): if not os.path.exists(p_dir): continue
continue if return_md:
path = os.path.join(p_dir, f"{pdf_name}.md")
# 写入文本类结果 if os.path.exists(path): zf.write(path,
if return_md: arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md"))
path = os.path.join(parse_dir, f"{pdf_name}.md") if return_images:
if os.path.exists(path): images_dir = os.path.join(p_dir, "images")
zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md")) for img in glob.glob(os.path.join(glob.escape(images_dir), "*.jpg")):
zf.write(img, arcname=os.path.join(safe_pdf_name, "images", os.path.basename(img)))
if return_middle_json:
path = os.path.join(parse_dir, f"{pdf_name}_middle.json") return FileResponse(path=zip_path, media_type="application/zip", filename="results.zip",
if os.path.exists(path): background=BackgroundTask(cleanup_file, zip_path))
zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_middle.json"))
if return_model_output:
path = os.path.join(parse_dir, f"{pdf_name}_model.json")
if os.path.exists(path):
zf.write(path, arcname=os.path.join(safe_pdf_name, os.path.basename(path)))
if return_content_list:
path = os.path.join(parse_dir, f"{pdf_name}_content_list.json")
if os.path.exists(path):
zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_content_list.json"))
# 写入图片
if return_images:
images_dir = os.path.join(parse_dir, "images")
image_paths = glob.glob(os.path.join(glob.escape(images_dir), "*.jpg"))
for image_path in image_paths:
zf.write(image_path, arcname=os.path.join(safe_pdf_name, "images", os.path.basename(image_path)))
return FileResponse(
path=zip_path,
media_type="application/zip",
filename="results.zip",
background=BackgroundTask(cleanup_file, zip_path)
)
else: else:
# 构建 JSON 结果
result_dict = {} result_dict = {}
for pdf_name in pdf_file_names: for pdf_name in pdf_file_names:
result_dict[pdf_name] = {} result_dict[pdf_name] = {}
data = result_dict[pdf_name] data = result_dict[pdf_name]
if backend.startswith("pipeline"): if backend.startswith("pipeline"):
parse_dir = os.path.join(unique_dir, pdf_name, parse_method) p_dir = os.path.join(unique_dir, pdf_name, parse_method)
elif backend.startswith("vlm"): elif backend.startswith("vlm"):
parse_dir = os.path.join(unique_dir, pdf_name, "vlm") p_dir = os.path.join(unique_dir, pdf_name, "vlm")
elif backend.startswith("hybrid"): else:
parse_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}") p_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}")
if os.path.exists(parse_dir): if os.path.exists(p_dir):
if return_md: if return_md: data["md_content"] = get_infer_result(".md", pdf_name, p_dir)
data["md_content"] = get_infer_result(".md", pdf_name, parse_dir)
if return_middle_json:
data["middle_json"] = get_infer_result("_middle.json", pdf_name, parse_dir)
if return_model_output:
data["model_output"] = get_infer_result("_model.json", pdf_name, parse_dir)
if return_content_list:
data["content_list"] = get_infer_result("_content_list.json", pdf_name, parse_dir)
if return_images: if return_images:
images_dir = os.path.join(parse_dir, "images") img_dir = os.path.join(p_dir, "images")
safe_pattern = os.path.join(glob.escape(images_dir), "*.jpg") data["images"] = {os.path.basename(p): f"data:image/jpeg;base64,{encode_image(p)}"
image_paths = glob.glob(safe_pattern) for p in glob.glob(os.path.join(glob.escape(img_dir), "*.jpg"))}
data["images"] = {
os.path.basename(
image_path
): f"data:image/jpeg;base64,{encode_image(image_path)}"
for image_path in image_paths
}
return JSONResponse( return JSONResponse(status_code=200,
status_code=200, content={"backend": backend, "version": __version__, "results": result_dict})
content={
"backend": backend,
"version": __version__,
"results": result_dict
}
)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(e)
return JSONResponse( # 清理日志捕获和 stderr 捕获
status_code=500, try:
content={"error": f"Failed to process file: {str(e)}"} stderr_capture.stop()
logger.remove(sink_id)
_current_task_id = None
except Exception:
pass
_task_progress[task_id]["status"] = "failed"
_task_progress[task_id]["error"] = str(e)
return JSONResponse(status_code=500, content={"error": f"Internal Error: {str(e)}"})
# --- FastAPI 核心应用 ---
def create_app():
enable_docs = str(os.getenv("MINERU_API_ENABLE_FASTAPI_DOCS", "1")).lower() in ("1", "true", "yes")
app = FastAPI(
openapi_url="/openapi.json" if enable_docs else None,
docs_url="/docs" if enable_docs else None,
redoc_url="/redoc" if enable_docs else None,
) )
global _request_semaphore
try:
mcr = int(os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "0"))
if mcr > 0:
_request_semaphore = asyncio.Semaphore(mcr)
logger.info(f"Concurrency limited to {mcr}")
except:
pass
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"],
allow_headers=["*"])
app.add_middleware(GZipMiddleware, minimum_size=1000)
# 1. 首先挂载 API 路由组 (处理所有 /api/* 请求)
app.include_router(api_router)
# 2. 根路径重定向或特定处理 (可选)
@app.get("/health")
async def health():
return {"status": "ok"}
# 3. 最后挂载静态文件服务 (处理剩下的所有请求,如 /, /index.html, /assets/*)
static_dir = Path(__file__).parent / "static" / "web"
if static_dir.exists():
logger.info(f"Mounting static files from {static_dir}")
app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
else:
logger.warning("Static directory not found, web UI will not be available.")
return app
app = create_app()
@click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True)) @click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context @click.pass_context
@click.option('--host', default='127.0.0.1', help='Server host (default: 127.0.0.1)') @click.option('--host', default='127.0.0.1')
@click.option('--port', default=8000, type=int, help='Server port (default: 8000)') @click.option('--port', default=8000, type=int)
@click.option('--reload', is_flag=True, help='Enable auto-reload (development mode)') @click.option('--reload', is_flag=True)
def main(ctx, host, port, reload, **kwargs): def main(ctx, host, port, reload, **kwargs):
kwargs.update(arg_parse(ctx)) kwargs.update(arg_parse(ctx))
# 将配置参数存储到应用状态中
app.state.config = kwargs app.state.config = kwargs
# 将 CLI 的并发参数同步到环境变量,确保 uvicorn 重载子进程可见 mcr = str(kwargs.get("mineru_api_max_concurrent_requests", "0") or "0")
try: os.environ["MINERU_API_MAX_CONCURRENT_REQUESTS"] = mcr
mcr = int(kwargs.get("mineru_api_max_concurrent_requests", 0) or 0)
except ValueError:
mcr = 0
os.environ["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(mcr)
"""启动MinerU FastAPI服务器的命令行入口""" uvicorn.run("mineru.cli.fast_api:app", host=host, port=port, reload=reload)
print(f"Start MinerU FastAPI Service: http://{host}:{port}")
print(f"API documentation: http://{host}:{port}/docs")
uvicorn.run(
"mineru.cli.fast_api:app",
host=host,
port=port,
reload=reload
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -23,26 +23,143 @@ from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.hash_utils import str_sha256 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('"', '&quot;')
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): 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) os.makedirs(output_dir, exist_ok=True)
try: try:
file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}' file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
pdf_data = read_fn(doc_path) pdf_data = read_fn(doc_path)
# 根据 backend 确定 parse_method
if backend.startswith("vlm"): if backend.startswith("vlm"):
parse_method = "vlm" parse_method = "vlm"
else: else:
parse_method = 'ocr' if is_ocr else 'auto' parse_method = 'ocr' if is_ocr else 'auto'
# 根据 backend 类型准备环境目录
if backend.startswith("hybrid"): if backend.startswith("hybrid"):
env_name = f"hybrid_{parse_method}" env_name = f"hybrid_{parse_method}"
else: else:
env_name = parse_method env_name = parse_method
local_image_dir, local_md_dir = prepare_env(output_dir, file_name, env_name) local_image_dir, local_md_dir = prepare_env(output_dir, file_name, env_name)
await aio_do_parse( await aio_do_parse(
output_dir=output_dir, output_dir=output_dir,
pdf_file_names=[file_name], pdf_file_names=[file_name],
@ -62,22 +179,12 @@ 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): def compress_directory_to_zip(directory_path, output_zip_path):
"""压缩指定目录到一个 ZIP 文件。
:param directory_path: 要压缩的目录路径
:param output_zip_path: 输出的 ZIP 文件路径
"""
try: try:
with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
# 遍历目录中的所有文件和子目录
for root, dirs, files in os.walk(directory_path): for root, dirs, files in os.walk(directory_path):
for file in files: for file in files:
# 构建完整的文件路径
file_path = os.path.join(root, file) file_path = os.path.join(root, file)
# 计算相对路径
arcname = os.path.relpath(file_path, directory_path) arcname = os.path.relpath(file_path, directory_path)
# 添加文件到 ZIP 文件
zipf.write(file_path, arcname) zipf.write(file_path, arcname)
return 0 return 0
except Exception as e: except Exception as e:
@ -91,31 +198,32 @@ def image_to_base64(image_path):
def replace_image_with_base64(markdown_text, image_dir_path): def replace_image_with_base64(markdown_text, image_dir_path):
# 匹配Markdown中的图片标签
pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)' pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
# 替换图片链接
def replace(match): def replace(match):
relative_path = match.group(1) relative_path = match.group(1)
# 只处理以.jpg结尾的图片
if relative_path.endswith('.jpg'): if relative_path.endswith('.jpg'):
full_path = os.path.join(image_dir_path, relative_path) full_path = os.path.join(image_dir_path, relative_path)
base64_image = image_to_base64(full_path) base64_image = image_to_base64(full_path)
return f'![{relative_path}](data:image/jpeg;base64,{base64_image})' return f'![{relative_path}](data:image/jpeg;base64,{base64_image})'
else:
# 其他格式的图片保持原样
return match.group(0) return match.group(0)
# 应用替换
return re.sub(pattern, replace, markdown_text) 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包含(),则提取括号前的内容作为实际语言 # 如果language包含(),则提取括号前的内容作为实际语言
if '(' in language and ')' in language: if '(' in language and ')' in language:
language = language.split('(')[0].strip() language = language.split('(')[0].strip()
file_path = to_pdf(file_path) 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文件以及压缩包文件路径 # 获取识别的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') 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) zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
if zip_archive_success == 0: if zip_archive_success == 0:
@ -125,74 +233,55 @@ 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') md_path = os.path.join(local_md_dir, file_name + '.md')
with open(md_path, 'r', encoding='utf-8') as f: with open(md_path, 'r', encoding='utf-8') as f:
txt_content = f.read() txt_content = f.read()
# ────────────── 自动补全:根据 # 标题补全后续段落为 ## ──────────────
txt_content = auto_promote_paragraphs_to_subheading(txt_content)
# ────────────────────────────────────────────────────────────────
md_content = replace_image_with_base64(txt_content, local_md_dir) md_content = replace_image_with_base64(txt_content, local_md_dir)
# 生成思维导图HTML - 使用新的实现
mind_map_html = md_to_markmap_html(txt_content)
# 返回转换后的PDF路径 # 返回转换后的PDF路径
new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.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 return md_content, txt_content, archive_zip_path, new_pdf_path, mind_map_html
latex_delimiters_type_all = [
{'left': '$$', 'right': '$$', 'display': True},
{'left': '$', 'right': '$', 'display': False},
{'left': '\\(', 'right': '\\)', 'display': False},
{'left': '\\[', 'right': '\\]', 'display': True},
]
latex_delimiters_type_a = [ latex_delimiters_type_a = [
{'left': '$$', 'right': '$$', 'display': True}, {'left': '$$', 'right': '$$', 'display': True},
{'left': '$', 'right': '$', 'display': False}, {'left': '$', 'right': '$', 'display': False},
] ]
latex_delimiters_type_b = [ latex_delimiters_type_b = [
{'left': '\\(', 'right': '\\)', 'display': False}, {'left': '\\(', 'right': '\\)', 'display': False},
{'left': '\\[', 'right': '\\]', 'display': True}, {'left': '\\[', 'right': '\\]', 'display': True},
] ]
latex_delimiters_type_all = latex_delimiters_type_a + latex_delimiters_type_b
header_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'resources', 'header.html') other_lang = ['ch (Chinese, English, Chinese Traditional)', 'en (English)', 'korean', 'japan']
with open(header_path, mode='r', encoding='utf-8') as header_file: all_lang = [*other_lang]
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): def safe_stem(file_path):
stem = Path(file_path).stem stem = Path(file_path).stem
# 只保留字母、数字、下划线和点,其他字符替换为下划线
return re.sub(r'[^\w.]', '_', stem) return re.sub(r'[^\w.]', '_', stem)
def to_pdf(file_path): 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) pdf_bytes = read_fn(file_path)
# unique_filename = f'{uuid.uuid4()}.pdf'
unique_filename = f'{safe_stem(file_path)}.pdf' unique_filename = f'{safe_stem(file_path)}.pdf'
# 构建完整的文件路径
tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename) tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
# 将字节数据写入文件
with open(tmp_file_path, 'wb') as tmp_pdf_file: with open(tmp_file_path, 'wb') as tmp_pdf_file:
tmp_pdf_file.write(pdf_bytes) tmp_pdf_file.write(pdf_bytes)
return tmp_file_path return tmp_file_path
@ -255,8 +344,30 @@ def main(ctx,
api_enable, max_convert_pages, api_enable, max_convert_pages,
server_name, server_port, latex_delimiters_type, **kwargs server_name, server_port, latex_delimiters_type, **kwargs
): ):
# 检测系统语言环境,默认为中文
import locale
import os
# 创建 i18n 实例,支持中英文 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 = gr.I18n( i18n = gr.I18n(
en={ en={
"upload_file": "Please upload a PDF or image", "upload_file": "Please upload a PDF or image",
@ -264,7 +375,7 @@ def main(ctx,
"backend": "Backend", "backend": "Backend",
"server_url": "Server URL", "server_url": "Server URL",
"server_url_info": "OpenAI-compatible server URL for http-client backend.", "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_enable": "Enable table recognition",
"table_info": "If disabled, tables will be shown as images.", "table_info": "If disabled, tables will be shown as images.",
"formula_label_vlm": "Enable display formula recognition", "formula_label_vlm": "Enable display formula recognition",
@ -284,6 +395,7 @@ def main(ctx,
"convert_result": "Convert result", "convert_result": "Convert result",
"md_rendering": "Markdown rendering", "md_rendering": "Markdown rendering",
"md_text": "Markdown text", "md_text": "Markdown text",
"mind_map": "Mind Map", # 新增
"backend_info_vlm": "High-precision parsing via VLM, supports Chinese and English documents only.", "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_pipeline": "Traditional Multi-model pipeline parsing, supports multiple languages, hallucination-free.",
"backend_info_hybrid": "High-precision hybrid parsing, supports multiple languages.", "backend_info_hybrid": "High-precision hybrid parsing, supports multiple languages.",
@ -295,7 +407,7 @@ def main(ctx,
"backend": "解析后端", "backend": "解析后端",
"server_url": "服务器地址", "server_url": "服务器地址",
"server_url_info": "http-client 后端的 OpenAI 兼容服务器地址。", "server_url_info": "http-client 后端的 OpenAI 兼容服务器地址。",
"recognition_options": "**识别选项:**", "recognition_options": "识别选项",
"table_enable": "启用表格识别", "table_enable": "启用表格识别",
"table_info": "禁用后,表格将显示为图片。", "table_info": "禁用后,表格将显示为图片。",
"formula_label_vlm": "启用行间公式识别", "formula_label_vlm": "启用行间公式识别",
@ -315,6 +427,7 @@ def main(ctx,
"convert_result": "转换结果", "convert_result": "转换结果",
"md_rendering": "Markdown 渲染", "md_rendering": "Markdown 渲染",
"md_text": "Markdown 文本", "md_text": "Markdown 文本",
"mind_map": "思维导图", # 新增
"backend_info_vlm": "多模态大模型高精度解析,仅支持中英文文档。", "backend_info_vlm": "多模态大模型高精度解析,仅支持中英文文档。",
"backend_info_pipeline": "传统多模型管道解析,支持多语言,无幻觉。", "backend_info_pipeline": "传统多模型管道解析,支持多语言,无幻觉。",
"backend_info_hybrid": "高精度混合解析,支持多语言。", "backend_info_hybrid": "高精度混合解析,支持多语言。",
@ -368,7 +481,6 @@ def main(ctx,
return client_options_update, ocr_options_update, formula_label_update, backend_info_update return client_options_update, ocr_options_update, formula_label_update, backend_info_update
kwargs.update(arg_parse(ctx)) kwargs.update(arg_parse(ctx))
if latex_delimiters_type == 'a': if latex_delimiters_type == 'a':
@ -399,8 +511,10 @@ def main(ctx,
logger.exception(e) logger.exception(e)
suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes] suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes]
with gr.Blocks() as demo: with gr.Blocks(title="多模态思维导图助手",
gr.HTML(header) fill_height=True) as demo:
# gr.HTML(header)
gr.HTML("<h1 style='text-align: center;'>多模态思维导图助手</h1>")
with gr.Row(): with gr.Row():
with gr.Column(variant='panel', scale=5): with gr.Column(variant='panel', scale=5):
with gr.Row(): with gr.Row():
@ -412,16 +526,21 @@ def main(ctx,
preferred_option = "hybrid-auto-engine" preferred_option = "hybrid-auto-engine"
if http_client_enable: if http_client_enable:
drop_list.extend(["vlm-http-client", "hybrid-http-client"]) 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: 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.Row(equal_height=True):
with gr.Column(): with gr.Column():
gr.Markdown(i18n("recognition_options")) gr.Markdown(i18n("recognition_options"))
table_enable = gr.Checkbox(label=i18n("table_enable"), value=True, info=i18n("table_info")) 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: 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")) is_ocr = gr.Checkbox(label=i18n("force_ocr"), value=False, info=i18n("force_ocr_info"))
with gr.Row(): with gr.Row():
change_bu = gr.Button(i18n("convert")) change_bu = gr.Button(i18n("convert"))
@ -444,50 +563,46 @@ def main(ctx,
md = gr.Markdown( md = gr.Markdown(
label=i18n("md_rendering"), label=i18n("md_rendering"),
height=1200, height=1200,
# buttons=["copy"], # gradio 6 以上版本使用 show_copy_button=True,
show_copy_button=True, # gradio 6 以下版本使用
latex_delimiters=latex_delimiters, latex_delimiters=latex_delimiters,
line_breaks=True line_breaks=True
) )
with gr.Tab(i18n("md_text")): with gr.Tab(i18n("md_text")):
md_text = gr.TextArea( md_text = gr.TextArea(
lines=45, lines=45,
# buttons=["copy"], # gradio 6 以上版本使用 show_copy_button=True,
show_copy_button=True, # gradio 6 以下版本使用
label=i18n("md_text") label=i18n("md_text")
) )
with gr.Tab(i18n("mind_map")): # 新增的思维导图tab
mind_map = gr.HTML(label=i18n("mind_map")) # 使用HTML组件来渲染markmap
# 添加事件处理 # 添加事件处理
backend.change( backend.change(
fn=update_interface, fn=update_interface,
inputs=[backend], inputs=[backend],
outputs=[client_options, ocr_options, formula_enable, backend], outputs=[client_options, ocr_options, formula_enable, backend],
# api_visibility="private" # gradio 6 以上版本使用 api_name=False
api_name=False # gradio 6 以下版本使用
) )
# 添加demo.load事件,在页面加载时触发一次界面更新 # 添加demo.load事件,在页面加载时触发一次界面更新
demo.load( demo.load(
fn=update_interface, fn=update_interface,
inputs=[backend], inputs=[backend],
outputs=[client_options, ocr_options, formula_enable, backend], outputs=[client_options, ocr_options, formula_enable, backend],
# api_visibility="private" # gradio 6 以上版本使用 api_name=False
api_name=False # gradio 6 以下版本使用
) )
clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr]) clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr, mind_map])
input_file.change( input_file.change(
fn=to_pdf, fn=to_pdf,
inputs=input_file, inputs=input_file,
outputs=pdf_show, outputs=pdf_show,
api_name="to_pdf" if api_enable else False, # gradio 6 以下版本使用 api_name="to_pdf" if api_enable else False
# api_visibility="public" if api_enable else "private" # gradio 6 以上版本使用
) )
change_bu.click( change_bu.click(
fn=to_markdown, fn=to_markdown,
inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url], inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
outputs=[md, md_text, output_file, pdf_show], outputs=[md, md_text, output_file, pdf_show, mind_map], # 添加mind_map输出
api_name="to_markdown" if api_enable else False, # gradio 6 以下版本使用 api_name="to_markdown" if api_enable else False
# api_visibility="public" if api_enable else "private" # gradio 6 以上版本使用
) )
footer_links = ["gradio", "settings"] footer_links = ["gradio", "settings"]
@ -496,9 +611,10 @@ def main(ctx,
demo.launch( demo.launch(
server_name=server_name, server_name=server_name,
server_port=server_port, server_port=server_port,
# footer_links=footer_links, # gradio 6 以上版本使用 show_api=api_enable,
show_api=api_enable, # gradio 6 以下版本使用 i18n=i18n,
i18n=i18n # title = "多模态思维导图助手",
# favicon_path = "logo.png"
) )

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

View File

@ -0,0 +1,28 @@
<!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

View File

@ -9,13 +9,18 @@ from mineru.utils.char_utils import full_to_half
from mineru.utils.enum_class import BlockType, SplitFlag from mineru.utils.enum_class import BlockType, SplitFlag
CONTINUATION_MARKERS = [ CONTINUATION_END_MARKERS = [
"(续)", "(续)",
"(续表)", "(续表)",
"(续上表)", "(续上表)",
"(continued)", "(continued)",
"(cont.)", "(cont.)",
"(cont’d)", "(cont’d)",
"(…continued)",
]
CONTINUATION_INLINE_MARKERS = [
"(continued)",
] ]
@ -163,19 +168,31 @@ def detect_table_headers(soup1, soup2, max_header_rows=5):
def can_merge_tables(current_table_block, previous_table_block): def can_merge_tables(current_table_block, previous_table_block):
"""判断两个表格是否可以合并""" """判断两个表格是否可以合并"""
# 检查表格是否有caption和footnote # 检查表格是否有caption和footnote
# 计算previous_table_block中的footnote数量
footnote_count = sum(1 for block in previous_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE)
# 如果有TABLE_CAPTION类型的块,检查是否至少有一个以"(续)"结尾 # 如果有TABLE_CAPTION类型的块,检查是否至少有一个以"(续)"结尾
caption_blocks = [block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION] caption_blocks = [block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION]
if caption_blocks: if caption_blocks:
# 如果所有caption都不以"(续)"、"(续表)"、"(continued)"或"(cont.)"结尾,则不合并 # 检查是否至少有一个caption包含续表标识
has_continuation_marker = False
if not any( for block in caption_blocks:
any(full_to_half(merge_para_with_text(block).strip()).lower().endswith(marker.lower()) caption_text = full_to_half(merge_para_with_text(block).strip()).lower()
for marker in CONTINUATION_MARKERS) if (
for block in caption_blocks any(caption_text.endswith(marker.lower()) for marker in CONTINUATION_END_MARKERS)
or any(marker.lower() in caption_text for marker in CONTINUATION_INLINE_MARKERS)
): ):
has_continuation_marker = True
break
# 如果所有caption都不包含续表标识,则不允许合并
if not has_continuation_marker:
return False, None, None, None, None return False, None, None, None, None
if any(block["type"] == BlockType.TABLE_FOOTNOTE for block in previous_table_block["blocks"]): # 如果current_table_block的caption存在续标识,放宽footnote的限制允许previous_table_block有最多一条footnote
if footnote_count > 1:
return False, None, None, None, None
else:
if footnote_count > 0:
return False, None, None, None, None return False, None, None, None, None
# 获取两个表格的HTML内容 # 获取两个表格的HTML内容
@ -363,6 +380,11 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo
row.extract() row.extract()
tbody1.append(row) tbody1.append(row)
# 清空previous_table_block的footnote
previous_table_block["blocks"] = [
block for block in previous_table_block["blocks"]
if block["type"] != BlockType.TABLE_FOOTNOTE
]
# 添加待合并表格的footnote到前一个表格中 # 添加待合并表格的footnote到前一个表格中
for table_footnote in wait_merge_table_footnotes: for table_footnote in wait_merge_table_footnotes:
temp_table_footnote = table_footnote.copy() temp_table_footnote = table_footnote.copy()

View File

@ -7,7 +7,7 @@ name = "mineru"
dynamic = ["version"] dynamic = ["version"]
license = { text = "AGPL-3.0" } license = { text = "AGPL-3.0" }
description = "A practical tool for converting PDF to Markdown" description = "A practical tool for converting PDF to Markdown"
readme = "README.mineru-upstream.md" readme = "README.md"
requires-python = ">=3.10,<3.14" requires-python = ">=3.10,<3.14"
keywords = ["magic-pdf", "mineru", "MinerU", "convert", "pdf", "markdown"] keywords = ["magic-pdf", "mineru", "MinerU", "convert", "pdf", "markdown"]
classifiers = [ classifiers = [

View File

@ -1,16 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd)
API_FLAVOR=${API_FLAVOR:-corex}
VERSION=${VERSION:-2.7.1}
[[ "$VERSION" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$ ]] || exit 2
case "$API_FLAVOR" 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
exec docker build -f "$ROOT_DIR/$FILE" \
--label io.unis.component=parser --label io.unis.layout=refact --label "io.unis.gpu=$API_FLAVOR" \
--label "org.opencontainers.image.revision=$(git -C "$ROOT_DIR" rev-parse HEAD)" \
-t "unis-mineru:$VERSION-$API_FLAVOR" -t "unis-mineru:$VERSION" \
-t "unis-mindmap-api:$VERSION" -t "unis-mindmap-api:$API_FLAVOR" -t unis-mindmap-api:latest "$ROOT_DIR"

View File

@ -1,46 +0,0 @@
"""Check the official parser tree; no model loading, DB, Redis or network."""
import argparse
import ast
import hashlib
import json
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
def check(root=ROOT, runtime=False):
manifest = json.loads((root / 'docs/mineru-migration/2.7.1-baseline.json').read_text(encoding='utf-8'))
package = root / 'mineru'
files = {p.relative_to(package).as_posix(): p for p in package.rglob('*')
if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')}
if set(files) != set(manifest['source_hashes']):
raise ValueError('Parser file set differs from the official 2.7.1 baseline')
for name, path in files.items():
if hashlib.sha256(path.read_bytes().replace(b'\r\n', b'\n')).hexdigest() != manifest['source_hashes'][name]:
raise ValueError('Parser source differs from official 2.7.1: ' + name)
module = ast.parse((package / 'version.py').read_text(encoding='utf-8'))
version = next(ast.literal_eval(n.value) for n in module.body if isinstance(n, ast.Assign)
and any(getattr(target, 'id', None) == '__version__' for target in n.targets))
if version != '2.7.1' or len(files) != 187:
raise ValueError('Unexpected parser baseline version or file count')
result = {'version': version, 'official_files': len(files), 'kernel_modifications': 0}
if runtime:
import importlib.metadata as metadata
sys.path.insert(0, str(root))
import mineru
from mineru.version import __version__
if Path(mineru.__file__).resolve() != (package / '__init__.py').resolve() or __version__ != version:
raise ValueError('The imported parser does not match the local official baseline')
if metadata.version('mineru') != version:
raise ValueError('Installed MinerU metadata does not match the source version')
result['installed_version'] = version
result['source_path'] = str(package)
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runtime', action='store_true')
args = parser.parse_args()
print(json.dumps(check(runtime=args.runtime)))

View File

@ -1,52 +0,0 @@
"""Start the pinned upstream parser; application features live in MaxKB."""
import os
import argparse
from pathlib import Path
import sys
from types import SimpleNamespace
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.1' or not Path(module_path).resolve().is_relative_to(ROOT / 'mineru'):
raise RuntimeError('解析服务版本或源码路径不匹配')
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', type=int, default=8000)
parser.add_argument('--mineru-api-max-concurrent-requests', type=int,
default=int(os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS']))
parser.add_argument('--gpu-memory-utilization', type=float,
default=float(os.environ['MINERU_GPU_MEMORY_UTILIZATION'])
if os.getenv('MINERU_GPU_MEMORY_UTILIZATION') else None)
parser.add_argument('--reload', action='store_true')
args, engine_args = parser.parse_known_args()
if args.reload:
raise ValueError('解析服务使用单进程启动,请移除 --reload')
if args.mineru_api_max_concurrent_requests < 0:
raise ValueError('解析请求并发数不能小于 0')
if args.gpu_memory_utilization is not None and not 0 < args.gpu_memory_utilization < 1:
raise ValueError('MINERU_GPU_MEMORY_UTILIZATION must be between 0 and 1')
os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS'] = str(args.mineru_api_max_concurrent_requests)
# Official 2.7.1's CLI puts every extra flag in app.state.config. The API
# forwards that dict to vLLM, where API-only flags are invalid EngineArgs.
# Configure the unmodified upstream ASGI app and pass only engine options.
from mineru.utils.cli_parser import arg_parse
from mineru.cli.fast_api import app
normalized = []
for value in engine_args:
normalized.extend(value.split('=', 1) if value.startswith('--') and '=' in value else [value])
app.state.config = arg_parse(SimpleNamespace(args=normalized))
if args.gpu_memory_utilization is not None:
app.state.config['gpu_memory_utilization'] = args.gpu_memory_utilization
import uvicorn
uvicorn.run(app, host=args.host, port=args.port)
if __name__ == '__main__':
main()

View File

@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# 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

View File

@ -1,54 +0,0 @@
"""Official 2.7.1 heading behavior; the optional six-level patch is disabled."""
import copy
import json
from types import SimpleNamespace
import unittest
from unittest.mock import MagicMock, patch
from mineru.backend.pipeline import pipeline_middle_json_mkcontent as pipeline
from mineru.backend.vlm import vlm_middle_json_mkcontent as vlm
from mineru.utils.enum_class import MakeMode
from mineru.utils import llm_aided
class HeadingLevelsTests(unittest.TestCase):
def blocks(self):
return [{'type': 'title', 'level': level, 'bbox': [0, level * 10, 100, level * 10 + 8],
'line_avg_height': 20 - level,
'lines': [{'bbox': [0, 0, 100, 8], 'spans': [{'type': 'text', 'content': f'Heading{level}'}]}]}
for level in range(1, 7)]
def pages(self):
return [{'page_idx': 0, 'page_size': [600, 800], 'para_blocks': self.blocks(), 'discarded_blocks': []}]
def test_both_output_backends_keep_the_official_four_level_limit(self):
for converter in (pipeline, vlm):
with self.subTest(converter=converter.__name__), patch.object(converter, 'detect_lang', return_value='en'):
markdown = converter.union_make(copy.deepcopy(self.pages()), MakeMode.MM_MD)
self.assertEqual(markdown.split('\n\n'), [f'{"#" * min(i, 4)} Heading{i}' for i in range(1, 7)])
content = converter.union_make(copy.deepcopy(self.pages()), MakeMode.CONTENT_LIST)
self.assertEqual([item['text_level'] for item in content], [1, 2, 3, 4, 4, 4])
content_v2 = vlm.union_make(self.pages(), MakeMode.CONTENT_LIST_V2)
self.assertEqual([item['content']['level'] for page in content_v2 for item in page], [1, 2, 3, 4, 4, 4])
def test_out_of_range_levels_still_produce_valid_markdown(self):
for converter in (pipeline, vlm):
self.assertEqual(converter.get_title_level({}), 1)
for value, expected in [(-1, 0), (0, 0), (5, 4), (6, 4), (7, 4), (99, 4)]:
self.assertEqual(converter.get_title_level({'level': value}), expected)
def test_assisted_title_prompt_keeps_the_official_four_level_limit(self):
client = MagicMock()
client.chat.completions.create.return_value = [SimpleNamespace(choices=[SimpleNamespace(
delta=SimpleNamespace(content=json.dumps({str(i): i + 1 for i in range(6)})))])]
pages = self.pages()
with patch.object(llm_aided, 'OpenAI', return_value=client), patch.object(pipeline, 'detect_lang', return_value='en'):
llm_aided.llm_aided_title(pages, {'api_key': 'unused-test-value', 'base_url': 'https://example.invalid', 'model': 'test'})
instruction = client.chat.completions.create.call_args.kwargs['messages'][0]['content']
self.assertIn('标题层级最多为4级', instruction)
self.assertNotIn('标题层级最多为6级', instruction)
self.assertEqual([block['level'] for block in pages[0]['para_blocks']], list(range(1, 7)))
if __name__ == '__main__':
unittest.main(verbosity=2)

View File

@ -1,92 +0,0 @@
"""Baseline and launcher checks requiring only Python's standard library."""
import importlib.util
import json
import os
from pathlib import Path
import shutil
import sys
import tempfile
from types import ModuleType, SimpleNamespace
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
def load(name, relative):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
baseline = load('parser_baseline_check', 'scripts/check_parser_baseline.py')
launcher = load('parser_launch_check', 'scripts/run_parser.py')
class ParserBaselineTests(unittest.TestCase):
def test_entire_kernel_matches_the_official_271_package(self):
self.assertEqual(baseline.check(), {'version': '2.7.1', 'official_files': 187, 'kernel_modifications': 0})
def test_modified_or_extra_source_is_rejected(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
shutil.copytree(ROOT / 'mineru', root / 'mineru', ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
(root / 'docs/mineru-migration').mkdir(parents=True)
shutil.copyfile(ROOT / 'docs/mineru-migration/2.7.1-baseline.json', root / 'docs/mineru-migration/2.7.1-baseline.json')
source = root / 'mineru/version.py'
original = source.read_bytes()
source.write_bytes(original + b'\n# custom patch\n')
with self.assertRaisesRegex(ValueError, 'source differs'):
baseline.check(root)
source.write_bytes(original)
(root / 'mineru/retired_custom_api.py').write_text('')
with self.assertRaisesRegex(ValueError, 'file set differs'):
baseline.check(root)
def launch(self, version='2.7.1', path=None, args=None, memory='0.5'):
package = ModuleType('mineru'); package.__file__ = str(path or ROOT / 'mineru/__init__.py')
release = ModuleType('mineru.version'); release.__version__ = version
api = ModuleType('mineru.cli.fast_api'); api.app = SimpleNamespace(state=SimpleNamespace())
cli = ModuleType('mineru.utils.cli_parser')
cli.arg_parse = lambda ctx: {ctx.args[i][2:].replace('-', '_'): ctx.args[i + 1] for i in range(0, len(ctx.args), 2)}
server = ModuleType('uvicorn')
captured = {}
def run(app, **kwargs):
captured.update(config=app.state.config, server=kwargs,
concurrency=os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS'])
server.run = run
with patch.dict(sys.modules, {'mineru': package, 'mineru.version': release, 'mineru.cli.fast_api': api,
'mineru.utils.cli_parser': cli, 'uvicorn': server}), \
patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': memory, 'MINERU_API_MAX_CONCURRENT_REQUESTS': '1'}, clear=True), \
patch.object(sys, 'argv', ['run_parser.py', *(args or [])]):
launcher.main()
return captured
def test_deployment_options_are_forwarded_without_kernel_patches(self):
args = self.launch()
self.assertEqual(args['concurrency'], '1')
self.assertEqual(args['config'], {'gpu_memory_utilization': 0.5})
explicit = self.launch(args=['--gpu-memory-utilization=0.4'])
self.assertEqual(explicit['config'], {'gpu_memory_utilization': 0.4})
def test_api_flags_never_leak_into_vllm_engine_arguments(self):
result = self.launch(args=['--host', '0.0.0.0', '--port', '8100',
'--mineru-api-max-concurrent-requests=2', '--tensor-parallel-size=2'])
self.assertEqual(result['server'], {'host': '0.0.0.0', 'port': 8100})
self.assertEqual(result['concurrency'], '2')
self.assertEqual(result['config'], {'tensor_parallel_size': '2', 'gpu_memory_utilization': 0.5})
def test_wrong_version_or_import_path_is_rejected(self):
for kwargs in ({'version': '2.7.4'}, {'path': ROOT / 'other/mineru/__init__.py'}):
with self.subTest(kwargs=kwargs), self.assertRaises(RuntimeError):
self.launch(**kwargs)
def test_invalid_memory_limit_is_rejected(self):
for value in ('0', '1', 'invalid'):
with self.subTest(value=value), self.assertRaises(ValueError):
self.launch(memory=value)
if __name__ == '__main__':
unittest.main(verbosity=2)

View File

@ -1,49 +0,0 @@
"""Real upstream FastAPI protocol with inference mocked; no GPU or model requests."""
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
from mineru.cli import fast_api
class ParserProtocolTests(unittest.TestCase):
def test_official_routes_do_not_restore_retired_application_features(self):
with TestClient(fast_api.app) as client:
schema = client.get('/openapi.json').json()
self.assertIn('/file_parse', schema['paths'])
self.assertNotIn('/api/file_parse', schema['paths'])
self.assertFalse(any('organize' in path or 'mindmap' in path for path in schema['paths']))
def test_pipeline_response_matches_maxkb_markdown_middle_json_and_images_contract(self):
async def infer(**kwargs):
for name in kwargs['pdf_file_names']:
output = Path(kwargs['output_dir']) / name / kwargs['parse_method']
(output / 'images').mkdir(parents=True)
(output / (name + '.md')).write_text('# CODEX 271 protocol\n\n![image](images/test.jpg)', encoding='utf-8')
(output / (name + '_middle.json')).write_text(json.dumps({'pdf_info': [{'page_idx': 0, 'para_blocks': []}]}), encoding='utf-8')
(output / 'images/test.jpg').write_bytes(b'isolated-test-image')
with tempfile.TemporaryDirectory() as folder, \
patch.object(fast_api, 'aio_do_parse', side_effect=infer), \
patch.object(fast_api, 'guess_suffix_by_path', return_value='pdf'), \
patch.object(fast_api, 'read_fn', return_value=b'isolated-pdf'), \
TestClient(fast_api.app) as client:
response = client.post('/file_parse', files={'files': ('CODEX_271_PROTOCOL.pdf', b'%PDF-test', 'application/pdf')},
data={'backend': 'pipeline', 'parse_method': 'auto', 'output_dir': folder,
'return_md': 'true', 'return_middle_json': 'true', 'return_images': 'true',
'response_format_zip': 'false'})
self.assertEqual(response.status_code, 200, response.text[:300])
payload = response.json()
self.assertEqual(payload['version'], '2.7.1')
self.assertEqual(payload['backend'], 'pipeline')
self.assertEqual(len(payload['results']), 1)
result = next(iter(payload['results'].values()))
self.assertIn('# CODEX 271 protocol', result['md_content'])
self.assertEqual(json.loads(result['middle_json'])['pdf_info'][0]['page_idx'], 0)
self.assertTrue(result['images']['test.jpg'].startswith('data:image/jpeg;base64,'))
if __name__ == '__main__':
unittest.main(verbosity=2)

View File

36
web_ui/Dockerfile 100644
View File

@ -0,0 +1,36 @@
# 构建阶段
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;"]

169
web_ui/README.md 100644
View File

@ -0,0 +1,169 @@
# 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 界面。

25
web_ui/index.html 100644
View File

@ -0,0 +1,25 @@
<!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>

47
web_ui/nginx.back 100644
View File

@ -0,0 +1,47 @@
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

45
web_ui/nginx.conf 100644
View File

@ -0,0 +1,45 @@
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;
}
}

3392
web_ui/package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,31 @@
{
"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

40
web_ui/src/App.vue 100644
View File

@ -0,0 +1,40 @@
<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>

View File

@ -0,0 +1,91 @@
import request from '@/utils/request'
import type { AxiosResponse } from 'axios'
export interface ParseParams {
files: File[]
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
stage: string
status: 'processing' | 'completed' | 'failed'
error: string | null
file_names: string
}
export const documentApi = {
/**
* 解析文档
*/
parseDocument(params: ParseParams, taskId?: string): Promise<ParseResult> {
const formData = new FormData()
// 添加文件
params.files.forEach(file => {
formData.append('files', file)
})
// 添加其他参数
formData.append('output_dir', params.output_dir)
formData.append('lang_list', params.lang_list)
formData.append('backend', params.backend)
formData.append('parse_method', params.parse_method)
formData.append('formula_enable', params.formula_enable.toString())
formData.append('table_enable', params.table_enable.toString())
formData.append('start_page_id', params.start_page_id.toString())
formData.append('end_page_id', params.end_page_id.toString())
formData.append('return_md', params.return_md.toString())
formData.append('return_middle_json', params.return_middle_json.toString())
formData.append('response_format_zip', params.response_format_zip.toString())
if (params.server_url) {
formData.append('server_url', params.server_url)
}
return request.post('/api/file_parse', formData, {
headers: {
'Content-Type': 'multipart/form-data',
...(taskId ? { 'X-Task-ID': taskId } : {})
}
}).then(result => {
console.log("解析成功:", result);
return result as unknown as ParseResult;
}).catch(error => {
console.error("解析失败:", error);
throw error;
})
},
/**
* 查询解析进度
*/
getParseProgress(taskId: string): Promise<ParseProgress> {
return request.get(`/api/parse_progress/${taskId}`).then(result => {
return result as unknown as ParseProgress
})
}
}

View File

@ -0,0 +1,307 @@
<template>
<div class="config-panel">
<h3 class="panel-title">{{ $t('config.title') }}</h3>
<el-form :model="config" label-position="top" label-width="120px" class="config-form">
<!-- 最大页数 -->
<el-form-item :label="$t('config.maxPages')" class="form-item">
<el-slider
v-model="draftConfig.maxPages"
:min="1"
:max="1000"
show-input
class="slider"
/>
</el-form-item>
<!-- 解析后端 -->
<el-form-item :label="$t('config.backend')" class="form-item">
<el-select
v-model="draftConfig.backend"
style="width: 100%"
@change="onBackendChange"
class="select"
>
<el-option
v-for="option in backendOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
<div class="form-item-description">
{{ getBackendDescription(draftConfig.backend) }}
</div>
</el-form-item>
<!-- 服务器URL (仅当使用http-client时显示) -->
<el-form-item
v-if="showServerUrl"
:label="$t('config.serverUrl')"
class="form-item"
>
<el-input
v-model="draftConfig.serverUrl"
:placeholder="'http://localhost:30000'"
class="input"
/>
<div class="form-item-description">
{{ $t('config.serverUrlInfo') }}
</div>
</el-form-item>
<div class="divider"></div>
<!-- 识别选项 -->
<div class="section-title">{{ $t('config.recognitionOptions') }}</div>
<!-- 表格识别 -->
<el-form-item class="form-item">
<el-checkbox v-model="draftConfig.tableEnable" class="checkbox">
{{ $t('config.tableEnable') }}
</el-checkbox>
<div class="form-item-description">
{{ $t('config.tableInfo') }}
</div>
</el-form-item>
<!-- 公式识别 -->
<el-form-item class="form-item">
<el-checkbox v-model="draftConfig.formulaEnable" class="checkbox">
{{ getFormulaLabel(draftConfig.backend) }}
</el-checkbox>
<div class="form-item-description">
{{ getFormulaInfo(draftConfig.backend) }}
</div>
</el-form-item>
<!-- OCR选项 (非VLM后端时显示) -->
<template v-if="!isVlmBackend">
<div class="divider"></div>
<!-- OCR语言 -->
<el-form-item :label="$t('config.ocrLanguage')" class="form-item">
<el-select v-model="draftConfig.language" style="width: 100%" class="select">
<el-option
v-for="option in languageOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
<div class="form-item-description">
{{ $t('config.ocrLanguageInfo') }}
</div>
</el-form-item>
<!-- 强制OCR -->
<el-form-item class="form-item">
<el-checkbox v-model="draftConfig.forceOcr" class="checkbox">
{{ $t('config.forceOcr') }}
</el-checkbox>
<div class="form-item-description">
{{ $t('config.forceOcrInfo') }}
</div>
</el-form-item>
</template>
<div class="config-actions">
<el-button @click="resetDraft">重置</el-button>
<el-button type="primary" @click="confirmConfig">确认</el-button>
</div>
</el-form>
</div>
</template>
<script setup lang="ts">
import { computed, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { DocumentConfig } from '@/composables/useDocumentProcessor'
interface Props {
modelValue: DocumentConfig
backendOptions: Array<{ value: string; label: string }>
languageOptions: Array<{ value: string; label: string }>
}
interface Emits {
(e: 'update:modelValue', value: DocumentConfig): void
(e: 'backendChange', backend: string): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const createDraft = (value: DocumentConfig): DocumentConfig => ({ ...value })
const draftConfig = reactive<DocumentConfig>(createDraft(props.modelValue))
const syncDraft = (value: DocumentConfig) => {
Object.assign(draftConfig, createDraft(value))
}
watch(
() => props.modelValue,
(value) => syncDraft(value),
{ deep: true }
)
const showServerUrl = computed(() => {
return draftConfig.backend.includes('http-client')
})
const isVlmBackend = computed(() => {
return draftConfig.backend.startsWith('vlm')
})
const onBackendChange = (backend: string) => {
if (!backend.includes('http-client')) {
draftConfig.serverUrl = props.modelValue.serverUrl
}
}
const resetDraft = () => {
syncDraft(props.modelValue)
}
const confirmConfig = () => {
const confirmed = createDraft(draftConfig)
emit('update:modelValue', confirmed)
emit('backendChange', confirmed.backend)
ElMessage.success('设置已确认')
}
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 ''
}
const getBackendDescription = (backend: string) => {
const descriptions: Record<string, string> = {
'pipeline': '传统多模型管道解析,支持多语言,无幻觉。',
'vlm-auto-engine': '多模态大模型高精度解析,仅支持中英文文档。',
'hybrid-auto-engine': '高精度混合解析,支持多语言。',
'vlm-http-client': '多模态大模型高精度解析,通过远程服务器处理。',
'hybrid-http-client': '高精度混合解析,通过远程服务器处理。'
}
return descriptions[backend] || '选择文档解析的后端引擎。'
}
</script>
<style scoped>
.config-panel {
margin-bottom: 24px;
}
.panel-title {
font-weight: 600;
font-size: 16px;
color: #303133;
margin: 0 0 20px 0;
}
.config-form {
width: 100%;
}
.form-item {
margin-bottom: 20px;
}
.form-item label {
font-size: 14px;
font-weight: 500;
color: #303133;
margin-bottom: 8px;
}
.divider {
height: 1px;
background-color: #E4E7ED;
margin: 24px 0;
}
.section-title {
font-weight: 500;
margin: 0 0 16px 0;
color: #303133;
font-size: 14px;
}
.form-item-description {
font-size: 12px;
color: #909399;
margin-top: 8px;
line-height: 1.4;
}
.config-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 8px;
border-top: 1px solid #E4E7ED;
}
.slider :deep(.el-slider__runway) {
background-color: #E4E7ED;
}
.slider :deep(.el-slider__bar) {
background-color: #1677FF;
}
.slider :deep(.el-slider__button) {
border-color: #1677FF;
}
.select :deep(.el-select__input) {
color: #303133;
}
.select :deep(.el-select__wrapper) {
border: 1px solid #E4E7ED;
border-radius: 4px;
box-shadow: none;
}
.select :deep(.el-select__wrapper.is-focus) {
border-color: #1677FF;
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}
.input :deep(.el-input__wrapper) {
border: 1px solid #E4E7ED;
border-radius: 4px;
box-shadow: none;
}
.input :deep(.el-input__wrapper.is-focus) {
border-color: #1677FF;
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}
.checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
background-color: #1677FF;
border-color: #1677FF;
}
.checkbox :deep(.el-checkbox__label) {
color: #303133;
}
</style>

View File

@ -0,0 +1,246 @@
<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>

View File

@ -0,0 +1,654 @@
<template>
<div class="markdown-renderer">
<template v-if="content">
<div class="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>
<el-button type="primary" size="small" class="action-button primary" @click="handleDownload()">
<template #icon>
<el-icon><Download /></el-icon>
</template>
下载
</el-button>
</div>
<div class="render-content">
<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 class="richtext-stage">
<article ref="richtextRef" class="richtext-document">
<div class="markdown-content richtext-content" v-html="renderedContent"></div>
</article>
</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'
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[]>([])
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 renderedContent = computed(() => {
if (!props.content) return ''
const flavor = props.mode === 'markdown' ? activeFlavor.value : 'gfm'
const renderer = createMarkdownRenderer(flavor)
return renderer.render(props.content)
})
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
}
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(innerHtml, fileName)
downloadBlob(new Blob([html], { type: 'text/html;charset=utf-8' }), fileName)
}
async function exportMarkdown(markdown: string, fileName: string) {
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(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() {
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`)
}
</script>
<style scoped>
.markdown-renderer {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background-color: #FFFFFF;
border-radius: 8px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
min-height: 0;
}
.render-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 10px 16px;
flex-shrink: 0;
position: sticky;
top: 0;
z-index: 2;
background-color: #FFFFFF;
}
.render-actions-left {
display: flex;
align-items: center;
gap: 12px;
min-height: 32px;
}
.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 16px 16px;
}
.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: 10px;
min-height: 400px;
}
.rendered-html {
border: 1px solid #e9ecef;
}
.pdf-stage {
padding: 20px;
border-radius: 12px;
background:
radial-gradient(circle at top, rgba(22, 93, 255, 0.08), transparent 30%),
#eef2f7;
}
.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-radius: 12px;
background: linear-gradient(180deg, #f3f4f6 0%, #eef2f7 100%);
}
.richtext-document {
min-height: 100%;
background: white;
border: 1px solid #dde3ea;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
}
.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-left {
flex: 1;
min-width: 0;
}
.pdf-page {
padding: 24px 20px 32px;
min-height: auto;
}
.richtext-content {
padding: 24px 18px 32px;
}
.action-button {
flex-shrink: 0;
}
}
</style>

View File

@ -0,0 +1,473 @@
<template>
<div class="mindmap-container">
<div class="mindmap-actions">
<span class="mindmap-subtitle" v-if="content">已生成 {{ nodeCount }} 个节点</span>
<el-dropdown @command="handleDownload">
<el-button
type="primary"
size="small"
class="action-button primary"
>
<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 class="mindmap-content" @wheel.prevent="handleWheel" @click="handleNodeClick">
<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'
const props = defineProps({
content: {
type: String,
default: ''
}
})
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
const transformer = new Transformer()
const scale = ref(1)
const isRendering = ref(false)
const nodeCount = computed(() => {
if (!props.content) return 0
return (props.content.match(/^#{1,6}\s+/gm) || []).length
})
const initMarkmap = async () => {
if (!svgRef.value) return
if (!props.content) {
svgRef.value.innerHTML = ''
if (mmInstance && typeof mmInstance.destroy === 'function') {
mmInstance.destroy()
}
mmInstance = null
return
}
isRendering.value = true
try {
const { root } = transformer.transform(props.content)
const { styles, scripts } = transformer.getAssets()
if (styles) loadCSS(styles)
if (scripts) loadJS(scripts)
await nextTick()
const initialExpandLevel = nodeCount.value > 80 ? 2 : -1
if (mmInstance) {
if (typeof mmInstance.setData === 'function') {
mmInstance.setData(root)
mmInstance.fit()
} else {
mmInstance = Markmap.create(svgRef.value, {
autoFit: true,
fitRatio: 0.9,
initialExpandLevel
}, root)
}
} else {
mmInstance = Markmap.create(svgRef.value, {
autoFit: true,
fitRatio: 0.9,
initialExpandLevel
}, root)
}
await nextTick()
svgRef.value?.querySelectorAll('text').forEach((text) => {
text.setAttribute('data-editable-node', 'true')
})
} catch (error) {
console.error('Error initializing markmap:', error)
mmInstance = null
} finally {
isRendering.value = false
}
}
// 监听内容变化自动重绘
watch(() => props.content, () => {
window.clearTimeout(renderTimer)
renderTimer = window.setTimeout(() => {
initMarkmap()
}, 160)
})
onMounted(() => {
initMarkmap()
// 窗口缩放时自动调整导图大小
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
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)
}
function createExportSvg() {
const svg = svgRef.value
if (!svg) return null
const svgCopy = svg.cloneNode(true) as SVGElement
if (!svgCopy.getAttribute('xmlns')) {
svgCopy.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
}
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}`
svgCopy.setAttribute('viewBox', viewBox)
svgCopy.setAttribute('width', String(width))
svgCopy.setAttribute('height', String(height))
svgCopy.querySelectorAll('[style*="cursor"]').forEach((node) => node.removeAttribute('style'))
return {
data: new XMLSerializer().serializeToString(svgCopy),
width,
height
}
}
// 下载思维导图
const downloadMindMap = async (format: 'svg' | 'png' | 'jpeg' = 'svg') => {
const exportSvg = createExportSvg()
if (!exportSvg) return
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 maxCanvasPixels = 16_000_000
const scaleFactor = Math.min(3, Math.max(1, Math.sqrt(maxCanvasPixels / (exportSvg.width * exportSvg.height))))
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 (command === 'svg' || command === 'png' || command === 'jpeg') {
downloadMindMap(command)
}
}
// 重置视图
const resetView = () => {
mmInstance?.fit()
scale.value = 1
}
// 放大
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)
} else if (mmInstance) {
console.error('mmInstance does not have setScale method:', mmInstance)
}
}
// 处理鼠标滚轮缩放
const handleWheel = (event: WheelEvent) => {
event.preventDefault()
const delta = event.deltaY > 0 ? -0.1 : 0.1
if ((scale.value > 0.5 || delta > 0) && (scale.value < 2 || delta < 0)) {
scale.value += delta
applyZoom()
}
}
const handleNodeClick = async (event: MouseEvent) => {
const textNode = (event.target as Element | null)?.closest?.('text')
const oldText = textNode?.textContent?.trim()
if (!oldText || !props.content || oldText === '文档思维导图') 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: #FFFFFF;
border-radius: 8px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
min-height: 0;
}
.mindmap-actions {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 16px;
gap: 12px;
}
.mindmap-subtitle {
font-size: 12px;
color: #86909C;
background-color: #F2F3F5;
padding: 2px 8px;
border-radius: 10px;
margin-right: auto;
}
.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;
}
.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-header {
padding: 12px 16px;
}
.mindmap-title {
font-size: 14px;
}
.mindmap-subtitle {
font-size: 10px;
}
.action-button {
padding: 0 8px;
font-size: 12px;
}
.mindmap-actions {
gap: 4px;
}
}
</style>

View File

@ -0,0 +1,198 @@
<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>

View File

@ -0,0 +1,298 @@
import { ref, reactive } from 'vue'
import type { Ref } from 'vue'
import { documentApi, type ParseParams } from '@/api/document'
import { convertWordToPdf, isWordFile } from '@/utils/wordToPdf'
import { buildMindmapMarkdown } from '@/utils/mindmapMarkdown'
// 根据上一级标题自动补全下一级标题
export function autoPromoteParagraphsToSubheading(text: string): string {
return buildMindmapMarkdown(text)
}
export interface DocumentConfig {
maxPages: number
backend: string
serverUrl: string
tableEnable: boolean
formulaEnable: boolean
language: string
forceOcr: boolean
}
export interface ProcessResult {
markdown: string
source: string
mindmap: string
downloadUrl?: string
}
export function useDocumentProcessor() {
// 文件相关
const uploadedFiles: Ref<File[]> = ref([])
const isUploading = ref(false)
// 配置相关
const config = reactive<DocumentConfig>({
maxPages: 1000,
backend: 'hybrid-auto-engine',
serverUrl: 'http://localhost:30000',
tableEnable: true,
formulaEnable: true,
language: 'ch',
forceOcr: false
})
// 结果相关
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[] = []
for (let i = 0; i < files.length; i++) {
const file = files[i]
const fileType = file.type
const fileName = file.name.toLowerCase()
console.log('Processing file:', fileName, 'type:', fileType)
// 验证文件类型 - 支持 PDF、图片和 Word 文档
const isImage = fileType.startsWith('image/')
const isPdf = fileType === 'application/pdf'
const isWord = fileName.endsWith('.docx') || fileName.endsWith('.doc') || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
console.log('File type checks - isImage:', isImage, 'isPdf:', isPdf, 'isWord:', isWord)
if (!isImage && !isPdf && !isWord) {
error.value = '不支持的文件类型'
console.log('Unsupported file type:', fileName, fileType)
continue
}
// 验证文件大小 (100MB)
if (file.size > 100 * 1024 * 1024) {
error.value = '文件大小超出限制'
console.log('File too large:', fileName, file.size)
continue
}
// 如果是 Word 文档,转换为 PDF
if (isWord) {
try {
isUploading.value = true
error.value = '正在将 Word 文档转换为 PDF...'
console.log('Converting Word to PDF:', fileName)
const pdfFile = await convertWordToPdf(file)
console.log('Conversion successful, PDF file:', pdfFile.name, pdfFile.size)
validFiles.push(pdfFile)
error.value = null
} catch (err) {
error.value = 'Word 转换为 PDF 失败: ' + (err as Error).message
console.error('Conversion failed:', (err as Error).message)
continue
} finally {
isUploading.value = false
}
} else {
validFiles.push(file)
console.log('Adding file directly:', fileName)
}
}
uploadedFiles.value = validFiles
console.log('Final uploaded files:', validFiles.map(f => f.name))
}
// 清除所有数据
const clearAll = () => {
uploadedFiles.value = []
results.value = null
error.value = null
processingStage.value = ''
}
// 演示模式:上传文件后由用户手动粘贴 Markdown 源码
const initializeManualResult = () => {
results.value = {
markdown: '',
source: '',
mindmap: ''
}
error.value = null
}
// 进度相关
const progressPercent = ref(0)
const progressStage = ref('')
let progressTimer: ReturnType<typeof setInterval> | null = null
// 启动进度轮询
const startProgressPolling = (taskId: string) => {
stopProgressPolling()
progressPercent.value = 0
progressStage.value = '准备中'
progressTimer = setInterval(async () => {
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
}
isProcessing.value = true
error.value = null
processingStage.value = '准备提交解析任务'
// 生成任务ID
const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
startProgressPolling(taskId)
try {
processingStage.value = '提交文档到解析服务'
const params: ParseParams = {
files: uploadedFiles.value,
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)
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,
config,
results,
isUploading,
isProcessing,
processingStage,
progressPercent,
progressStage,
error,
// 选项
backendOptions,
languageOptions,
// 方法
handleFileUpload,
initializeManualResult,
clearAll,
processDocument,
getFormulaLabel,
getFormulaInfo
}
}

View File

@ -0,0 +1,87 @@
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'
}
}

View File

@ -0,0 +1,2 @@
export { default as zh } from './zh'
export { default as en } from './en'

View File

@ -0,0 +1,87 @@
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: '网络连接错误'
}
}

21
web_ui/src/main.ts 100644
View File

@ -0,0 +1,21 @@
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')

View File

@ -0,0 +1,55 @@
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)
}

View File

@ -0,0 +1,45 @@
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}`
}
}
}

View File

@ -0,0 +1,181 @@
const MAX_NODE_TEXT_LENGTH = 72
const MAX_PARAGRAPH_SUMMARY_LENGTH = 90
const MAX_CHILDREN_PER_HEADING = 18
const ROOT_TITLE = '文档思维导图'
type BlockType = 'paragraph' | 'list' | 'table' | 'code' | 'math' | 'image'
interface HeadingState {
level: number
childCount: number
}
function normalizeWhitespace(text: string) {
return text.replace(/\s+/g, ' ').trim()
}
function stripMarkdownInline(text: string) {
return normalizeWhitespace(text)
.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
.replace(/[*_`~>#]/g, '')
}
function truncateText(text: string, maxLength = MAX_NODE_TEXT_LENGTH) {
const normalized = normalizeWhitespace(text)
if (normalized.length <= maxLength) return normalized
return `${normalized.slice(0, maxLength - 1)}...`
}
function summarizeParagraph(text: string) {
const cleaned = stripMarkdownInline(text)
const sentence = cleaned.match(/^(.+?[。!?!?;;::]|\S.{20,}?[,,])/)
return truncateText(sentence?.[1] || cleaned, MAX_PARAGRAPH_SUMMARY_LENGTH)
}
function isHeading(line: string) {
return /^#{1,6}\s+/.test(line.trim())
}
function getHeadingLevel(line: string) {
return line.trim().match(/^#{1,6}/)?.[0].length || 0
}
function getHeadingText(line: string) {
return stripMarkdownInline(line.trim().replace(/^#{1,6}\s+/, ''))
}
function getListText(line: string) {
return stripMarkdownInline(line.trim().replace(/^[-*+]\s+|^\d+[.)、]\s+/, ''))
}
function countHeadingChildren(stack: HeadingState[], level: number) {
while (stack.length && stack[stack.length - 1].level >= level) {
stack.pop()
}
const parent = stack[stack.length - 1]
if (!parent) return true
parent.childCount += 1
return parent.childCount <= MAX_CHILDREN_PER_HEADING
}
function pushBlock(result: string[], stack: HeadingState[], blockType: BlockType, text: string) {
const cleaned = text.trim()
if (!cleaned) return
const parentLevel = stack.length ? stack[stack.length - 1].level : 1
const level = Math.min(parentLevel + 1, 6)
if (!countHeadingChildren(stack, level)) return
const prefixMap: Record<BlockType, string> = {
paragraph: '摘要',
list: '要点',
table: '表格',
code: '代码',
math: '公式',
image: '图片'
}
result.push(`${'#'.repeat(level)} ${prefixMap[blockType]}:${cleaned}`)
}
export function buildMindmapMarkdown(markdown: string) {
const lines = markdown.split(/\r?\n/)
const result: string[] = [`# ${ROOT_TITLE}`]
const stack: HeadingState[] = [{ level: 1, childCount: 0 }]
let paragraphBuffer: string[] = []
let inCodeBlock = false
let codeBlockTitle = ''
const flushParagraph = () => {
if (paragraphBuffer.length === 0) return
const text = summarizeParagraph(paragraphBuffer.join(' '))
pushBlock(result, stack, 'paragraph', text)
paragraphBuffer = []
}
for (const line of lines) {
const trimmed = line.trim()
if (/^```/.test(trimmed)) {
if (inCodeBlock) {
pushBlock(result, stack, 'code', codeBlockTitle || '代码块')
codeBlockTitle = ''
} else {
flushParagraph()
codeBlockTitle = trimmed.replace(/^```/, '').trim()
}
inCodeBlock = !inCodeBlock
continue
}
if (inCodeBlock) continue
if (!trimmed) {
flushParagraph()
continue
}
if (isHeading(trimmed)) {
flushParagraph()
const rawLevel = getHeadingLevel(trimmed)
const level = Math.min(rawLevel + 1, 6)
while (stack.length && stack[stack.length - 1].level >= level) {
stack.pop()
}
result.push(`${'#'.repeat(level)} ${truncateText(getHeadingText(trimmed)) || '未命名章节'}`)
stack.push({ level, childCount: 0 })
continue
}
if (/^\|.+\|$/.test(trimmed)) {
flushParagraph()
pushBlock(result, stack, 'table', '表格内容')
continue
}
if (/^!\[[^\]]*]\([^)]+\)/.test(trimmed)) {
flushParagraph()
pushBlock(result, stack, 'image', stripMarkdownInline(trimmed) || '图片')
continue
}
if (/^\$\$.*\$\$$/.test(trimmed) || /^\$[^$].*\$$/.test(trimmed)) {
flushParagraph()
pushBlock(result, stack, 'math', truncateText(trimmed, 80))
continue
}
if (/^[-*+]\s+|^\d+[.)、]\s+/.test(trimmed)) {
flushParagraph()
pushBlock(result, stack, 'list', truncateText(getListText(trimmed)))
continue
}
paragraphBuffer.push(trimmed)
}
flushParagraph()
return result.join('\n')
}
export function replaceFirstMindmapText(markdown: string, oldText: string, newText: string) {
const normalizedOld = oldText.replace(/^(摘要|要点|表格|代码|公式|图片):/, '').trim()
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) => stripMarkdownInline(line).includes(normalizedOld))
if (targetLineIndex >= 0) {
lines[targetLineIndex] = lines[targetLineIndex].replace(normalizedOld, newText.trim())
return lines.join('\n')
}
return markdown
}

View File

@ -0,0 +1,67 @@
import axios from 'axios'
// 创建 axios 实例
const request = axios.create({
baseURL: '',
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) {
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

View File

@ -0,0 +1,143 @@
/**
* 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

15
web_ui/start.sh 100644
View File

@ -0,0 +1,15 @@
#!/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

View File

@ -0,0 +1,25 @@
{
"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" }]
}

View File

@ -0,0 +1,9 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler"
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,33 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true
}
}
},
build: {
outDir: 'dist',
assetsDir: 'assets',
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'element-plus'],
markdown: ['markdown-it']
}
}
}
}
})