Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (23)
- .env.templateAdded+2
- .gitignoreAdded+9
- DockerfileAdded+38
- LICENSEAdded+674
- app/auth.pyAdded+15
- app/config.pyAdded+21
- app/deploy.pyAdded+111
- app/exceptions.pyAdded+18
- app/models.pyAdded+19
- app/routes.pyAdded+104
- app/static/i18n.jsAdded+307
- app/static/style.cssAdded+737
- app/store.pyAdded+43
- app/templates/base.htmlAdded+216
- app/templates/deploy_status.htmlAdded+430
- app/templates/index.htmlAdded+817
- app/utils.pyAdded+6
- images/img0.pngAdded
- images/img1.pngAdded
- images/img2.pngAdded
- main.pyAdded+17
- requirements.txtAdded+11
- start.shAdded+11
12REDIS_URL=redis://localhost:6379API_KEY=123456123456789.DS_Store__pycache__test/venv/.github/.idea.env*.log*.md1234567891011121314151617181920212223242526272829303132333435363738# 使用Python 3.11作为基础镜像FROM python:3.11-slim
# 设置工作目录WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
# 安装依赖,包括 git 和 redis-serverRUN apt-get update && apt-get install -y --no-install-recommends \ git \ redis-server \ && apt-get clean \ && rm -rf /var/lib/apt/lists/*
# 复制并安装 Python 依赖COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# 复制应用代码和启动脚本COPY . .COPY start.sh .RUN chmod +x start.sh # 赋予脚本执行权限
# 创建非 root 用户,并赋予 /app 目录和脚本权限RUN adduser --disabled-password --gecos "" appuser \ && chown -R appuser:appuser /app \ && chown appuser:appuser start.sh
# 切换到非 root 用户USER appuser
# 暴露端口EXPOSE 7860
# 使用启动脚本启动 Redis 和 Python 应用CMD ["./start.sh"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 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 General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. 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 workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha 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 visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation 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 toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients 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 toproduce it from the Program, in the form of source code under theterms 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 independentworks, 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 notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-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 excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe 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 installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional 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 youadd to a covered work, you may (if authorized by the copyright holders ofthat 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 "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform 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 expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered 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 automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent 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 anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain 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 limitingany implied license or other defenses to infringement that mayotherwise 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 orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES 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 OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy 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 greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "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 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
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 GPL, see<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<https://www.gnu.org/licenses/why-not-lgpl.html>.123456789101112131415from fastapi import Depends, HTTPException, Securityfrom fastapi.security.api_key import APIKeyHeaderfrom starlette.status import HTTP_403_FORBIDDENfrom .config import get_settings
api_key_header = APIKeyHeader(name="X-API-KEY", auto_error=False)
def require_api_key(api_key: str | None = Security(api_key_header)) -> str: settings = get_settings() if api_key is None or api_key not in settings.api_key: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid or missing API key", ) return api_key # returned value can be injected downstream if needed123456789101112131415161718192021from functools import lru_cachefrom pydantic_settings import BaseSettings, SettingsConfigDictfrom pydantic import Fieldfrom pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
class Settings(BaseSettings): """Global configuration loaded from environment variables.""" redis_url: str = Field("redis://localhost:6379") api_key: str = Field("123456")
model_config = SettingsConfigDict( env_file = BASE_DIR / ".env", env_file_encoding = "utf-8", )
@lru_cachedef get_settings() -> Settings: return Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from __future__ import annotationsimport shutil, tempfile, textwrap, timefrom pathlib import Pathfrom typing import Dictimport gitfrom huggingface_hub import HfApifrom huggingface_hub.errors import HfHubHTTPErrorfrom .exceptions import ( DockerfileMissingError, RepoCloneError, SpaceBuildTimeoutError, SpaceCreationError, SpaceDeployError,)
__all__ = [ "deploy_space", "SpaceDeployError",]
from .utils import _chmod_and_retry
def deploy_space(*, hf_token: str, git_repo_url: str, deploy_path: str, space_name: str, space_port: int, description: str, env_vars: Dict[str, str], private: bool) -> str: deploy_path = deploy_path.strip(".").strip("/") api = HfApi(token=hf_token) try: username = api.whoami().get("name", None) repo_id = f"{username}/{space_name}" api.create_repo( repo_id=repo_id, repo_type="space", space_sdk="docker", private=private, # space_variables=[{}], space_secrets=[{"key": k, "value": v} for k, v in env_vars.items()], exist_ok=False, ) except HfHubHTTPError as exc: raise SpaceCreationError(exc) from exc
tmp = tempfile.mkdtemp(prefix="hf_space_") try: try: if not deploy_path: git.Repo.clone_from( git_repo_url, tmp, depth=1, multi_options=["--single-branch"] ) else: repo = git.Repo.clone_from( git_repo_url, tmp, depth=1, no_checkout=True, filter=["tree:0"], sparse=True, multi_options=["--single-branch"], ) repo.git.sparse_checkout("init", "--no-cone") repo.git.sparse_checkout("set", "--no-cone", f"/{deploy_path}/**") repo.git.checkout()
# 平移文件到根目录 src = Path(tmp, deploy_path) for item in src.iterdir(): shutil.move(item, tmp) # 根目录目前是空的 shutil.rmtree(src) except git.GitCommandError as exc: raise RepoCloneError(str(exc)) from exc
git_dir = Path(tmp, ".git") if git_dir.exists() and git_dir.is_dir(): shutil.rmtree(git_dir, onerror=_chmod_and_retry)
if not Path(tmp, "Dockerfile").exists(): raise DockerfileMissingError()
readme = Path(tmp, "README.md") header = ( f"---\n" f"title: \"{space_name}\"\n" f"emoji: \"🚀\"\n" f"colorFrom: blue\n" f"colorTo: green\n" f"sdk: docker\n" f"app_port: {space_port}\n" f"---\n" ) badge = ( f"### 🚀 一键部署\n" f"[](https://github.com/kfcx/HFSpaceDeploy)\n\n" f"本项目由[HFSpaceDeploy](https://github.com/kfcx/HFSpaceDeploy)一键部署\n" ) readme.write_text(f"{header}\n{badge}\n{description}\n", encoding="utf-8") api.upload_folder(folder_path=tmp, repo_id=repo_id, repo_type="space", ignore_patterns=[".git"]) finally: shutil.rmtree(tmp, ignore_errors=True)
deadline = time.time() + 15 * 60 while time.time() < deadline: stage = api.get_space_runtime(repo_id).stage if stage == "RUNNING": return f"https://huggingface.co/spaces/{repo_id}" if stage in ("BUILD_ERROR", "CONFIG_ERROR", "RUNTIME_ERROR",): raise SpaceDeployError("Space failed during config/build/runtime") if stage in ("NO_APP_FILE", "STOPPED", "PAUSED", "DELETING", ): raise SpaceDeployError("Space is currently unavailable") time.sleep(5) raise SpaceBuildTimeoutError()123456789101112131415161718
class SpaceDeployError(Exception): """Base for deployment‑related faults."""
class RepoCloneError(SpaceDeployError): pass
class DockerfileMissingError(SpaceDeployError): pass
class SpaceCreationError(SpaceDeployError): pass
class SpaceBuildTimeoutError(SpaceDeployError): pass
class SpaceAlreadyExistsError(SpaceDeployError): pass12345678910111213141516171819from typing import Any, Dict, Optional# from huggingface_hub import SpaceStagefrom pydantic import BaseModel, Field
class DeployRequest(BaseModel): hf_token: str = Field(..., description="HF token with write permission") git_repo_url: str = Field(...) deploy_path: str = Field("/") space_name: str = Field(...) space_port: int = Field(7860) description: str = Field("") env_vars: Dict[str, str] = Field(default_factory=dict) private: bool = Field(False)
class DeployStatus(BaseModel): task_id: str status: str # PENDING | IN_PROGRESS | SUCCESS | FAILED detail: Optional[Any] = None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from fastapi import BackgroundTasks, FastAPI, HTTPException, Depends, Request, Formfrom fastapi.responses import HTMLResponse, RedirectResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom fastapi.middleware.gzip import GZipMiddlewareimport uuidfrom app.models import DeployRequest, DeployStatusfrom app.store import TaskStorefrom app.deploy import deploy_space, SpaceDeployErrorfrom app.auth import require_api_key
app = FastAPI(title="HF Space Deployer", version="1.0.0")
# Static files and templatesapp.mount("/static", StaticFiles(directory="app/static"), name="static")app.add_middleware(GZipMiddleware)templates = Jinja2Templates(directory="app/templates")
# Web Interface Routes@app.get("/", response_class=HTMLResponse)async def index(request: Request): return templates.TemplateResponse("index.html", {"request": request})
@app.post("/web/deploy")async def web_deploy( request: Request, hf_token: str = Form(...), git_repo_url: str = Form(...), space_name: str = Form(...), description: str = Form(""), space_port: int = Form(7860), private: bool = Form(False), env_vars_text: str = Form(""), deploy_path: str = Form("/"), bg: BackgroundTasks = BackgroundTasks()): # Parse environment variables from textarea env_vars = {} if env_vars_text.strip(): for line in env_vars_text.strip().split('\n'): if '=' in line: key, value = line.split('=', 1) env_vars[key.strip()] = value.strip()
deploy_req = DeployRequest( hf_token=hf_token, git_repo_url=git_repo_url, space_name=space_name, description=description, space_port=space_port, private=private, env_vars=env_vars, deploy_path=deploy_path )
task_id = str(uuid.uuid4()) TaskStore.save(DeployStatus(task_id=task_id, status="PENDING")) bg.add_task(_run_task, task_id, deploy_req)
# Redirect to status page instead of returning HTML return RedirectResponse(url=f"/deploy/{task_id}", status_code=303)
@app.get("/deploy/{task_id}", response_class=HTMLResponse)async def deploy_status_page(request: Request, task_id: str): status = TaskStore.load(task_id) if not status: raise HTTPException(status_code=404, detail="Task not found")
return templates.TemplateResponse("deploy_status.html", { "request": request, "task_id": task_id, "status": status.status })
# API Routes@app.post("/deploy", response_model=DeployStatus, status_code=202)async def deploy(req: DeployRequest, bg: BackgroundTasks): task_id = str(uuid.uuid4()) TaskStore.save(DeployStatus(task_id=task_id, status="PENDING")) bg.add_task(_run_task, task_id, req) return TaskStore.load(task_id)
@app.get("/deploy/status/{task_id}", response_model=DeployStatus)async def status(task_id: str): status = TaskStore.load(task_id) if not status: raise HTTPException(status_code=404, detail="Task not found") return status
# ------------------------------------------------------------------ #
def _run_task(task_id: str, req: DeployRequest): TaskStore.save(DeployStatus(task_id=task_id, status="IN_PROGRESS")) try: url = deploy_space(**req.dict()) TaskStore.save(DeployStatus(task_id=task_id, status="SUCCESS", detail={"space_url": url})) except SpaceDeployError as exc: TaskStore.save(DeployStatus(task_id=task_id, status="FAILED", detail={"error": str(exc)}))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307// Internationalization (i18n) supportconst translations = { en: { // Navigation 'nav.title': 'HF Space Deployer', 'nav.theme': 'Toggle Theme', 'nav.language': 'Language', // Hero Section 'hero.title': 'One-Click Deploy', 'hero.subtitle': 'Deploy to HuggingFace Spaces instantly', 'hero.deployTime': 'Deploy Time', 'hero.freeHosting': 'Free Hosting', 'hero.minutes': '2-5min', 'hero.percentage': '100%', // Features 'feature.fast.title': 'Lightning Fast', 'feature.fast.desc': 'Deploy from Git in minutes', 'feature.secure.title': 'Secure', 'feature.secure.desc': 'Full control with your token', 'feature.monitor.title': 'Real-time', 'feature.monitor.desc': 'Live deployment status', // Form 'form.title': 'Configuration', 'form.token': 'HuggingFace Token', 'form.token.placeholder': 'hf_...', 'form.token.get': 'Get Token', 'form.token.hint': 'Write permission required', 'form.token.toggle': 'Toggle visibility', 'form.token.clear': 'Clear cached token', 'form.token.cleared': 'Token cache cleared', 'form.repo': 'Git Repository', 'form.repo.placeholder': 'https://github.com/user/repo.git', 'form.repo.hint': 'GitHub, GitLab, etc.', 'form.space': 'Space Name', 'form.space.placeholder': 'my-app', 'form.space.hint': 'Letters, numbers, hyphens only', 'form.desc': 'Description', 'form.desc.placeholder': 'Brief description...', 'form.advanced': 'Advanced', 'form.deployPath': 'Deploy Path', 'form.deployPath.placeholder': '/', 'form.deployPath.hint': 'Subdirectory to deploy (default: root)', 'form.port': 'Port', 'form.private': 'Private Space', 'form.env': 'Environment Variables', 'form.env.placeholder': 'KEY1=value\nKEY2=value', 'form.env.hint': 'One per line', 'form.submit': 'Deploy', // Requirements 'req.title': 'Requirements', 'req.dockerfile': 'Repository must contain Dockerfile', 'req.token': 'Token needs write permissions', 'req.time': 'Deployment takes 2-5 minutes', 'req.docker': 'Supports Dockerized apps', // Pro Tips 'tips.title': 'Tips', 'tips.test': 'Test Dockerfile locally', 'tips.env': 'Use env vars for secrets', 'tips.size': 'Keep image size small', 'tips.limits': 'Check HF resource limits', // Status Page 'status.title': 'Deployment Status', 'status.taskId': 'Task ID', 'status.initializing': 'Initializing...', 'status.preparing': 'Preparing your Space...', 'status.queued': 'Queued', 'status.queued.desc': 'Request received', 'status.progress': 'In Progress', 'status.progress.desc': 'Building and deploying...', 'status.success': 'Success!', 'status.success.desc': 'Your Space is live', 'status.failed': 'Failed', 'status.failed.desc': 'Deployment error', 'status.url': 'Space URL', 'status.visit': 'Visit Space', 'status.error': 'Error Details', 'status.troubleshoot': 'Troubleshooting', 'status.newDeploy': 'New Deploy', 'status.refresh': 'Refresh', 'status.copy': 'Copy', 'status.autoRefresh': 'Auto-refresh every 2s', // Loading 'loading.title': 'Deploying...', 'loading.desc': 'Please wait...', // Configuration Import/Export 'config.import': 'Import', 'config.export': 'Export', 'config.import.title': 'Import Configuration', 'config.import.info': 'Paste your configuration JSON or share configuration URL', 'config.import.label': 'Configuration JSON', 'config.import.placeholder': '{"space_name": "my-app", "git_repo_url": "https://github.com/..."}', 'config.import.apply': 'Apply Configuration', 'config.import.success': 'Configuration imported successfully', 'config.import.error': 'Failed to import configuration', 'config.import.empty': 'Please enter configuration JSON', 'config.import.invalid': 'Invalid configuration format', 'config.export.title': 'Export Configuration', 'config.export.info': 'Configuration exported successfully', 'config.export.label': 'Configuration JSON', 'config.export.url': 'Share URL', 'config.export.save': 'Save as File', 'config.export.saved': 'Configuration saved to file', 'config.copy': 'Copy', 'config.copied': 'Configuration copied!', 'config.url.copied': 'Share URL copied!', 'config.cancel': 'Cancel', 'config.close': 'Close', // Footer 'footer.title': 'HF Space Deployer', 'footer.desc': 'Quick deployment tool', // Copied toast 'toast.copied': 'Copied!', 'toast.copyFailed': 'Copy failed', 'toast.deploySuccess': 'Deployment successful!', 'toast.deployFailed': 'Deployment failed', 'toast.requestFailed': 'Request failed' }, zh: { // Navigation 'nav.title': 'HF Space 部署器', 'nav.theme': '切换主题', 'nav.language': '语言', // Hero Section 'hero.title': '一键部署', 'hero.subtitle': '快速部署到 HuggingFace Spaces', 'hero.deployTime': '部署时间', 'hero.freeHosting': '免费托管', 'hero.minutes': '2-5分钟', 'hero.percentage': '100%', // Features 'feature.fast.title': '极速部署', 'feature.fast.desc': '分钟级 Git 部署', 'feature.secure.title': '安全可靠', 'feature.secure.desc': 'Token 完全掌控', 'feature.monitor.title': '实时监控', 'feature.monitor.desc': '部署状态实时更新', // Form 'form.title': '配置设置', 'form.token': 'HuggingFace 令牌', 'form.token.placeholder': 'hf_...', 'form.token.get': '获取令牌', 'form.token.hint': '需要写入权限', 'form.token.toggle': '切换可见性', 'form.token.clear': '清除缓存令牌', 'form.token.cleared': '令牌缓存已清除', 'form.repo': 'Git 仓库', 'form.repo.placeholder': 'https://github.com/用户名/仓库名.git', 'form.repo.hint': '支持 GitHub、GitLab 等', 'form.space': '空间名称', 'form.space.placeholder': 'my-app', 'form.space.hint': '仅限字母、数字、连字符', 'form.desc': '描述', 'form.desc.placeholder': '简短描述...', 'form.advanced': '高级设置', 'form.deployPath': '部署路径', 'form.deployPath.placeholder': '/', 'form.deployPath.hint': '要部署的子目录(默认:根目录)', 'form.port': '端口', 'form.private': '私有空间', 'form.env': '环境变量', 'form.env.placeholder': 'KEY1=value\nKEY2=value', 'form.env.hint': '每行一个', 'form.submit': '部署', // Requirements 'req.title': '要求', 'req.dockerfile': '仓库需包含 Dockerfile', 'req.token': '令牌需要写入权限', 'req.time': '部署需要 2-5 分钟', 'req.docker': '支持 Docker 应用', // Pro Tips 'tips.title': '提示', 'tips.test': '先本地测试 Dockerfile', 'tips.env': '敏感数据用环境变量', 'tips.size': '保持镜像体积小', 'tips.limits': '检查 HF 资源限制', // Status Page 'status.title': '部署状态', 'status.taskId': '任务 ID', 'status.initializing': '初始化中...', 'status.preparing': '准备 Space 中...', 'status.queued': '排队中', 'status.queued.desc': '已接收请求', 'status.progress': '进行中', 'status.progress.desc': '构建部署中...', 'status.success': '成功!', 'status.success.desc': 'Space 已上线', 'status.failed': '失败', 'status.failed.desc': '部署出错', 'status.url': 'Space 地址', 'status.visit': '访问 Space', 'status.error': '错误详情', 'status.troubleshoot': '故障排除', 'status.newDeploy': '新建部署', 'status.refresh': '刷新', 'status.copy': '复制', 'status.autoRefresh': '每2秒自动刷新', // Loading 'loading.title': '部署中...', 'loading.desc': '请稍候...', // Configuration Import/Export 'config.import': '导入', 'config.export': '导出', 'config.import.title': '导入配置', 'config.import.info': '粘贴配置 JSON 或分享配置链接', 'config.import.label': '配置 JSON', 'config.import.placeholder': '{"space_name": "my-app", "git_repo_url": "https://github.com/..."}', 'config.import.apply': '应用配置', 'config.import.success': '配置导入成功', 'config.import.error': '配置导入失败', 'config.import.empty': '请输入配置 JSON', 'config.import.invalid': '配置格式无效', 'config.export.title': '导出配置', 'config.export.info': '配置导出成功', 'config.export.label': '配置 JSON', 'config.export.url': '分享链接', 'config.export.save': '保存为文件', 'config.export.saved': '配置已保存到文件', 'config.copy': '复制', 'config.copied': '配置已复制!', 'config.url.copied': '分享链接已复制!', 'config.cancel': '取消', 'config.close': '关闭', // Footer 'footer.title': 'HF Space 部署器', 'footer.desc': '快速部署工具', // Copied toast 'toast.copied': '已复制!', 'toast.copyFailed': '复制失败', 'toast.deploySuccess': '部署成功!', 'toast.deployFailed': '部署失败', 'toast.requestFailed': '请求失败' }};
// Current languagelet currentLang = localStorage.getItem('language') || 'en';
// Translate functionfunction t(key) { return translations[currentLang][key] || translations['en'][key] || key;}
// Set languagefunction setLanguage(lang) { currentLang = lang; localStorage.setItem('language', lang); updatePageTranslations();}
// Toggle languagefunction toggleLanguage() { const newLang = currentLang === 'en' ? 'zh' : 'en'; setLanguage(newLang);}
// Update all translations on pagefunction updatePageTranslations() { // Update all elements with data-i18n attribute document.querySelectorAll('[data-i18n]').forEach(element => { const key = element.getAttribute('data-i18n'); element.textContent = t(key); }); // Update all elements with data-i18n-placeholder attribute document.querySelectorAll('[data-i18n-placeholder]').forEach(element => { const key = element.getAttribute('data-i18n-placeholder'); element.placeholder = t(key); }); // Update all elements with data-i18n-title attribute document.querySelectorAll('[data-i18n-title]').forEach(element => { const key = element.getAttribute('data-i18n-title'); element.title = t(key); }); // Update document title document.title = t('nav.title'); // Dispatch custom event document.dispatchEvent(new Event('languageChanged'));}
// Initialize on page loaddocument.addEventListener('DOMContentLoaded', () => { updatePageTranslations();}); 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737/* Custom styles for HuggingFace Space Deployer */
/* Light Theme Configuration - CMYK Theme */[data-theme="light"] { /* Color scheme */ color-scheme: light; /* Base colors */ --b1: 100% 0 0; /* base-100 - Pure white */ --b2: 95% 0 0; /* base-200 */ --b3: 90% 0 0; /* base-300 */ --bc: 20% 0 0; /* base-content - Dark gray */ /* Brand colors */ --p: 71.772% 0.133 239.443; /* primary - Blue */ --pc: 14.354% 0.026 239.443; /* primary-content */ --s: 64.476% 0.202 359.339; /* secondary - Red/Pink */ --sc: 12.895% 0.04 359.339; /* secondary-content */ --a: 94.228% 0.189 105.306; /* accent - Yellow-green */ --ac: 18.845% 0.037 105.306; /* accent-content */ --n: 21.778% 0 0; /* neutral - Dark gray */ --nc: 84.355% 0 0; /* neutral-content */ /* State colors */ --in: 68.475% 0.094 217.284; /* info - Light blue */ --inc: 13.695% 0.018 217.284; /* info-content */ --su: 46.949% 0.162 321.406; /* success - Magenta */ --suc: 89.389% 0.032 321.406; /* success-content */ --wa: 71.236% 0.159 52.023; /* warning - Orange */ --wac: 14.247% 0.031 52.023; /* warning-content */ --er: 62.013% 0.208 28.717; /* error - Red-orange */ --erc: 12.402% 0.041 28.717; /* error-content */ /* Design tokens */ --rounded-box: 1rem; /* Larger border radius */ --rounded-btn: 1rem; /* Rounded buttons */ --rounded-badge: 0.5rem; /* Medium rounded badges */ --border-btn: 1px; /* Border width */ /* Effects */ --animation-btn: 0.25s; --animation-input: 0.2s; --btn-focus-scale: 0.98; --tab-radius: 1rem;}
/* Dark Theme Configuration - Aqua Theme */[data-theme="dark"] { /* Color scheme */ color-scheme: dark; /* Base colors */ --b1: 37% 0.146 265.522; /* base-100 - Deep blue-purple */ --b2: 28% 0.091 267.935; /* base-200 */ --b3: 22% 0.091 267.935; /* base-300 */ --bc: 90% 0.058 230.902; /* base-content - Light cyan */ /* Brand colors */ --p: 85.661% 0.144 198.645; /* primary - Cyan */ --pc: 40.124% 0.068 197.603; /* primary-content */ --s: 60.682% 0.108 309.782; /* secondary - Purple */ --sc: 96% 0.016 293.756; /* secondary-content */ --a: 93.426% 0.102 94.555; /* accent - Yellow */ --ac: 18.685% 0.02 94.555; /* accent-content */ --n: 27% 0.146 265.522; /* neutral - Dark blue */ --nc: 80% 0.146 265.522; /* neutral-content */ /* State colors */ --in: 54.615% 0.215 262.88; /* info - Blue */ --inc: 90.923% 0.043 262.88; /* info-content */ --su: 62.705% 0.169 149.213; /* success - Green */ --suc: 12.541% 0.033 149.213; /* success-content */ --wa: 66.584% 0.157 58.318; /* warning - Orange */ --wac: 27% 0.077 45.635; /* warning-content */ --er: 73.95% 0.19 27.33; /* error - Red */ --erc: 14.79% 0.038 27.33; /* error-content */ /* Design tokens */ --rounded-box: 1rem; /* Larger border radius */ --rounded-btn: 1rem; /* Rounded buttons */ --rounded-badge: 0.5rem; /* Medium rounded badges */ --border-btn: 1px; /* Border width */ /* Effects */ --animation-btn: 0.25s; --animation-input: 0.2s; --btn-focus-scale: 0.98; --tab-radius: 1rem;}
/* Custom theme variables */:root { --hover-opacity: 0.08; --focus-opacity: 0.12; --transition-speed: 0.2s;}
/* Animations */@keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); }}
@keyframes slideIn { from { opacity: 0; transform: translateX(-20px); } to { opacity: 1; transform: translateX(0); }}
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; }}
@keyframes shimmer { 0% { background-position: -1000px 0; } 100% { background-position: 1000px 0; }}
/* Animation Classes */.fade-in { animation: fadeIn 0.5s ease-out;}
.slide-in { animation: slideIn 0.3s ease-out;}
.animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;}
/* Loading States */.loading-spinner { animation: spin 2s linear infinite;}
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}
/* Gradient backgrounds */.gradient-primary { background: linear-gradient(135deg, oklch(var(--p)) 0%, oklch(var(--s)) 100%);}
.gradient-success { background: linear-gradient(135deg, oklch(var(--su)) 0%, oklch(var(--a)) 100%);}
.gradient-warning { background: linear-gradient(135deg, oklch(var(--wa)) 0%, oklch(var(--wa) / 0.8) 100%);}
.gradient-error { background: linear-gradient(135deg, oklch(var(--er)) 0%, oklch(var(--er) / 0.8) 100%);}
/* Card hover effects */.card { transition: all 0.3s ease; position: relative; z-index: 1; border-radius: var(--rounded-box);}
.card:hover { transform: translateY(-2px);}
/* Form enhancements */.form-control input:focus,.form-control textarea:focus { outline: none; box-shadow: 0 0 0 3px oklch(var(--p) / 0.1);}
/* Status indicators */.status-pending { background: linear-gradient(90deg, oklch(var(--wa)), oklch(var(--wa) / 0.8)); background-size: 200% 200%; animation: gradient-shift 2s ease-in-out infinite;}
.status-in-progress { background: linear-gradient(90deg, oklch(var(--in)), oklch(var(--in) / 0.8)); background-size: 200% 200%; animation: gradient-shift 2s ease-in-out infinite;}
@keyframes gradient-shift { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; }}
/* Steps animation */.step.step-primary { animation: step-complete 0.5s ease-in-out;}
@keyframes step-complete { 0% { transform: scale(0.8); opacity: 0; } 100% { transform: scale(1); opacity: 1; }}
/* Copy button animation */.copy-success { animation: copy-feedback 0.3s ease-in-out;}
@keyframes copy-feedback { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); }}
/* Mobile responsiveness */@media (max-width: 768px) { .steps-horizontal { display: block !important; } .hero-content { padding: 2rem 1rem !important; } .card-body { padding: 1.5rem !important; }}
/* Remove old dark mode color overrides since we now have proper theme variables */[data-theme="dark"] .gradient-primary { /* Let it use the theme colors defined above */ opacity: 1;}
/* Animations for theme transitions */* { transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;}
/* Button Enhancements */.btn { transition: all 0.2s ease; position: relative; overflow: hidden; z-index: 2; border-radius: var(--rounded-btn);}
.btn::before { content: ''; position: absolute; top: 50%; left: 50%; width: 0; height: 0; background: rgba(255, 255, 255, 0.2); border-radius: 50%; transform: translate(-50%, -50%); transition: width 0.3s, height 0.3s;}
.btn:active::before { width: 300px; height: 300px;}
/* Status Badge Animations */.badge { transition: all 0.2s ease;}
/* Copy Button Enhancement */.copy-btn:active { transform: scale(0.95);}
/* Toast Animations */.toast-enter { animation: slideIn 0.3s ease-out;}
.toast-exit { animation: fadeOut 0.3s ease-out;}
@keyframes fadeOut { from { opacity: 1; transform: translateY(0); } to { opacity: 0; transform: translateY(-10px); }}
/* Responsive Design Enhancements */@media (max-width: 768px) { .hero h1 { font-size: 2.5rem; } .stats { flex-direction: column; }}
/* Shimmer Effect for Loading */.shimmer { background: linear-gradient( 90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0) 100% ); background-size: 1000px 100%; animation: shimmer 2s infinite;}
/* Custom Scrollbar */::-webkit-scrollbar { width: 8px; height: 8px;}
::-webkit-scrollbar-track { background: oklch(var(--b2));}
::-webkit-scrollbar-thumb { background: oklch(var(--b3)); border-radius: 4px;}
::-webkit-scrollbar-thumb:hover { background: oklch(var(--bc) / 0.3);}
/* Code Block Styling */code { font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 0.875rem; padding: 0.125rem 0.25rem; border-radius: var(--rounded-badge);}
pre { font-family: 'Consolas', 'Monaco', 'Courier New', monospace; line-height: 1.5;}
/* Status Update Transitions */#status-container > * { animation: fadeIn 0.5s ease-out;}
/* Fixed Overlay Blur */.backdrop-blur-sm { backdrop-filter: blur(4px);}
/* Icon Hover Effects */[data-lucide]:hover { opacity: 0.8; transition: opacity 0.2s ease;}
/* Fix z-index and overlay issues */.card-body { position: relative; z-index: 1;}
/* Ensure form controls are interactive */.form-control { position: relative; z-index: 1;}
.form-control input,.form-control textarea,.form-control select { position: relative; z-index: 2; border-radius: var(--rounded-badge);}
/* Ensure the loading overlay is visible when shown */#loading-overlay .card { pointer-events: auto;}
/* Fix collapse toggle */.collapse input[type="checkbox"] { position: relative; z-index: 3;}
/* Ensure toast notifications are on top */#toast-container { z-index: 9999;}
/* Fix potential Alpine.js element issues */[x-data], [x-show], [x-ref] { position: relative;}
/* Ensure eye button for password toggle is clickable */.btn-ghost.btn-xs { z-index: 3;}
/* Theme toggle button animation */.theme-icon { transition: transform 0.3s ease;}
.btn-circle:hover .theme-icon { transform: rotate(180deg);}
/* Smooth theme transition */html { transition: background-color 0.3s ease, color 0.3s ease;}
/* Add enhanced theme transition effects */html[data-theme="light"] { background-color: oklch(var(--b1)); color: oklch(var(--bc));}
html[data-theme="dark"] { background-color: oklch(var(--b1)); color: oklch(var(--bc));}
/* Smooth transitions for theme changes */html, body { transition: background-color 0.3s ease, color 0.3s ease;}
/* Enhanced button hover states */.btn-primary:hover { background-color: oklch(var(--p) / 0.9); border-color: oklch(var(--p) / 0.9);}
.btn-secondary:hover { background-color: oklch(var(--s) / 0.9); border-color: oklch(var(--s) / 0.9);}
.btn-accent:hover { background-color: oklch(var(--a) / 0.9); border-color: oklch(var(--a) / 0.9);}
/* Card enhancements with theme colors */.card { background-color: oklch(var(--b1)); border: 1px solid oklch(var(--b3) / 0.2);}
.card:hover { border-color: oklch(var(--p) / 0.3); box-shadow: 0 4px 12px oklch(var(--bc) / 0.1);}
/* Input field enhancements */.input, .textarea, .select { background-color: oklch(var(--b1)); border-color: oklch(var(--bc) / 0.2); border-radius: var(--rounded-badge);}
.input:focus, .textarea:focus, .select:focus { border-color: oklch(var(--p)); background-color: oklch(var(--b1));}
/* Badge color enhancements */.badge-primary { background-color: oklch(var(--p)); color: oklch(var(--pc));}
.badge-secondary { background-color: oklch(var(--s)); color: oklch(var(--sc));}
.badge-accent { background-color: oklch(var(--a)); color: oklch(var(--ac));}
.badge-success { background-color: oklch(var(--su)); color: oklch(var(--suc));}
.badge-warning { background-color: oklch(var(--wa)); color: oklch(var(--wac));}
.badge-error { background-color: oklch(var(--er)); color: oklch(var(--erc));}
.badge-info { background-color: oklch(var(--in)); color: oklch(var(--inc));}
/* Alert color enhancements */.alert-success { background-color: oklch(var(--su) / 0.2); border-color: oklch(var(--su)); color: oklch(var(--suc));}
.alert-warning { background-color: oklch(var(--wa) / 0.2); border-color: oklch(var(--wa)); color: oklch(var(--wac));}
.alert-error { background-color: oklch(var(--er) / 0.2); border-color: oklch(var(--er)); color: oklch(var(--erc));}
.alert-info { background-color: oklch(var(--in) / 0.2); border-color: oklch(var(--in)); color: oklch(var(--inc));}
/* Light theme alert text color fixes for better readability */[data-theme="light"] .alert-success { background-color: oklch(var(--su) / 0.15); border-color: oklch(var(--su) / 0.5); color: oklch(25% 0.162 321.406); /* Darker text for better contrast */}
[data-theme="light"] .alert-warning { background-color: oklch(var(--wa) / 0.15); border-color: oklch(var(--wa) / 0.5); color: oklch(25% 0.159 52.023); /* Darker text for better contrast */}
[data-theme="light"] .alert-error { background-color: oklch(var(--er) / 0.15); border-color: oklch(var(--er) / 0.5); color: oklch(25% 0.208 28.717); /* Darker text for better contrast */}
[data-theme="light"] .alert-info { background-color: oklch(var(--in) / 0.15); border-color: oklch(var(--in) / 0.5); color: oklch(25% 0.094 217.284); /* Darker text for better contrast */}
/* Alert icon styling */.alert > :first-child { flex-shrink: 0;}
/* Ensure alert text is readable */.alert { font-weight: 500;}
/* Navbar enhancement */.navbar { background-color: oklch(var(--p)); color: oklch(var(--pc));}
/* Footer enhancement */.footer { background-color: oklch(var(--b2)); color: oklch(var(--bc));}
/* Link colors */.link { color: oklch(var(--p));}
.link:hover { color: oklch(var(--p) / 0.8);}
/* Code block colors */code { background-color: oklch(var(--b2)); color: oklch(var(--bc)); font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 0.875rem; padding: 0.125rem 0.25rem; border-radius: var(--rounded-badge);}
pre { background-color: oklch(var(--b2)); color: oklch(var(--bc)); font-family: 'Consolas', 'Monaco', 'Courier New', monospace; line-height: 1.5;}
/* Enhanced visual effects for new themes *//* CMYK theme light mode special effects */[data-theme="light"] .hero { background: linear-gradient(135deg, oklch(var(--p) / 0.9) 0%, oklch(var(--s) / 0.9) 50%, oklch(var(--a) / 0.9) 100% );}
/* Aqua theme dark mode special effects */[data-theme="dark"] .hero { background: linear-gradient(135deg, oklch(var(--p) / 0.8) 0%, oklch(var(--s) / 0.8) 50%, oklch(var(--a) / 0.8) 100% );}
/* Enhanced card styling with new border radius */.card { overflow: hidden;}
/* Modal and dialog styling */.modal-box { border-radius: var(--rounded-box);}
/* Toast notifications with new radius */.alert { border-radius: var(--rounded-btn);}
/* Enhanced button styles for CMYK/Aqua themes */[data-theme="light"] .btn-primary { box-shadow: 0 2px 8px oklch(var(--p) / 0.3);}
[data-theme="light"] .btn-primary:hover { box-shadow: 0 4px 12px oklch(var(--p) / 0.4);}
[data-theme="dark"] .btn-primary { box-shadow: 0 2px 8px oklch(var(--p) / 0.3);}
[data-theme="dark"] .btn-primary:hover { box-shadow: 0 4px 12px oklch(var(--p) / 0.4);}
/* Special glow effects for dark theme */[data-theme="dark"] .card:hover { box-shadow: 0 0 20px oklch(var(--p) / 0.2), 0 4px 12px oklch(var(--bc) / 0.1);}
[data-theme="dark"] .input:focus,[data-theme="dark"] .textarea:focus { box-shadow: 0 0 0 3px oklch(var(--p) / 0.2), 0 0 20px oklch(var(--p) / 0.1);}
/* Enhance badge styling with new themes */[data-theme="light"] .badge { border-radius: var(--rounded-badge); font-weight: 600;}
[data-theme="dark"] .badge { border-radius: var(--rounded-badge); font-weight: 500;}
/* Update divider styling for new themes */[data-theme="light"] .divider { color: oklch(var(--bc) / 0.3);}
[data-theme="dark"] .divider { color: oklch(var(--bc) / 0.3);}
/* Stat component enhancement */[data-theme="light"] .stats { border-radius: var(--rounded-box);}
[data-theme="dark"] .stats { border-radius: var(--rounded-box); background: oklch(var(--b1) / 0.5); backdrop-filter: blur(10px);} 12345678910111213141516171819202122232425262728293031323334353637383940414243import jsonfrom typing import Optionalfrom redis import StrictRedisfrom .config import get_settingsfrom .models import DeployStatus
_settings = get_settings()redis_client = StrictRedis.from_url( _settings.redis_url, decode_responses=True, # 连接池配置 max_connections=50, # 最大连接数 retry_on_timeout=True, # 超时重试 socket_timeout=15, # socket 超时 socket_connect_timeout=15, # 连接超时 health_check_interval=300, # 健康检查间隔)
class TaskStore: prefix = "task:"
@classmethod def _key(cls, task_id: str) -> str: return f"{cls.prefix}{task_id}"
@classmethod def save(cls, status: DeployStatus) -> None: redis_client.hset( cls._key(status.task_id), mapping={ "status": status.status, "detail": json.dumps(status.detail) if status.detail else "", }, ) redis_client.expire(cls._key(status.task_id), 24 * 3600)
@classmethod def load(cls, task_id: str) -> Optional[DeployStatus]: data = redis_client.hgetall(cls._key(task_id)) if not data: return None detail = json.loads(data.get("detail", "null")) if data.get("detail") else None return DeployStatus(task_id=task_id, status=data.get("status", "UNKNOWN"), detail=detail)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216<!DOCTYPE html><html lang="en" data-theme="light"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title data-i18n="nav.title">HF Space Deployer</title> <!-- Tailwind CSS + DaisyUI --> <link href="https://cdn.jsdelivr.net/npm/daisyui@4.6.0/dist/full.min.css" rel="stylesheet" type="text/css" /> <script src="https://cdn.tailwindcss.com"></script> <!-- Custom CSS --> <link href="/static/style.css" rel="stylesheet" type="text/css" /> <!-- HTMX --> <script src="https://unpkg.com/htmx.org@1.9.10"></script> <!-- Icons --> <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script> <!-- Alpine.js for reactive components --> <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script> <!-- i18n --> <script src="/static/i18n.js"></script> <style> .loading-spinner { animation: spin 2s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .fade-in { animation: fadeIn 0.5s ease-in-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } </style></head><body class="min-h-screen bg-base-100"> <!-- Navigation --> <div class="navbar bg-primary text-primary-content shadow-lg sticky top-0 z-50"> <div class="container mx-auto"> <div class="flex-1"> <a href="/" class="btn btn-ghost text-xl font-bold"> <i data-lucide="rocket" class="w-6 h-6 mr-2"></i> <span data-i18n="nav.title">HF Space Deployer</span> </a> </div> <div class="flex-none space-x-2"> <button class="btn btn-ghost btn-circle" onclick="toggleLanguage()" data-i18n-title="nav.language" title="Language" > <span class="text-lg font-bold lang-icon">EN</span> </button> <button class="btn btn-ghost btn-circle" onclick="toggleTheme()" data-i18n-title="nav.theme" title="Toggle Theme" > <i data-lucide="sun" class="w-5 h-5 theme-icon"></i> </button> </div> </div> </div>
<!-- Toast Container --> <div id="toast-container" class="fixed top-20 right-4 z-50 space-y-2"></div>
<!-- Main Content --> <main class="container mx-auto px-4 py-8 max-w-6xl"> {% block content %}{% endblock %} </main>
<!-- Footer --> <footer class="footer footer-center p-8 bg-base-200 text-base-content mt-16"> <div> <p class="font-bold text-lg" data-i18n="footer.title">HF Space Deployer</p> <p class="text-sm opacity-70" data-i18n="footer.desc">Quick deployment tool</p> </div> <div class="flex items-center space-x-4 text-sm"> <a href="https://github.com/kfcx/HFSpaceDeploy.git" target="_blank" class="link link-hover">GitHub</a> <span>•</span> <a href="https://huggingface.co" target="_blank" class="link link-hover">HuggingFace</a> </div> </footer>
<script> // Language icon update function updateLanguageIcon() { const langIcon = document.querySelector('.lang-icon'); langIcon.textContent = currentLang === 'en' ? 'EN' : '中'; } // Override toggleLanguage to update icon if (typeof window.originalToggleLanguage === 'undefined') { window.originalToggleLanguage = toggleLanguage; window.toggleLanguage = function() { window.originalToggleLanguage(); updateLanguageIcon(); }; } // Theme switcher - simplified for light/dark only function toggleTheme() { const currentTheme = document.documentElement.getAttribute('data-theme'); const newTheme = currentTheme === 'dark' ? 'light' : 'dark'; setTheme(newTheme); } function setTheme(theme) { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('theme', theme); // Update theme icon const themeIcon = document.querySelector('.theme-icon'); if (theme === 'dark') { themeIcon.setAttribute('data-lucide', 'moon'); } else { themeIcon.setAttribute('data-lucide', 'sun'); } lucide.createIcons(); } // Load saved theme (default to light) const savedTheme = localStorage.getItem('theme') || 'light'; setTheme(savedTheme); // Initialize Lucide icons lucide.createIcons(); // HTMX event listeners document.body.addEventListener('htmx:afterRequest', function(evt) { // Reinitialize icons after HTMX requests lucide.createIcons(); // Update translations for new content updatePageTranslations(); }); // Copy to clipboard function function copyToClipboard(text) { navigator.clipboard.writeText(text).then(function() { showToast(t('toast.copied'), 'success'); }).catch(function(err) { showToast(t('toast.copyFailed'), 'error'); }); } // Toast notification system function showToast(message, type = 'info') { const toastContainer = document.getElementById('toast-container'); const toast = document.createElement('div'); toast.className = `alert alert-${type} shadow-lg fade-in min-w-[300px]`; const icons = { 'success': 'check-circle', 'error': 'x-circle', 'warning': 'alert-triangle', 'info': 'info' }; toast.innerHTML = ` <i data-lucide="${icons[type]}" class="w-5 h-5"></i> <span>${message}</span> `; toastContainer.appendChild(toast); lucide.createIcons(); // Remove toast after 3 seconds setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translateY(-10px)'; setTimeout(() => toast.remove(), 300); }, 3000); } // HTMX extensions document.body.addEventListener('htmx:responseError', function(evt) { showToast(t('toast.requestFailed'), 'error'); }); // Global event listener for custom events document.addEventListener('show-toast', function(event) { const { message, type } = event.detail; showToast(message, type); }); // Initialize page functionality document.addEventListener('DOMContentLoaded', function() { // Initialize all icons if (typeof lucide !== 'undefined') { lucide.createIcons(); } // Update language icon updateLanguageIcon(); }); // Ensure Alpine.js is loaded before dependent components if (typeof Alpine !== 'undefined') { document.addEventListener('alpine:init', () => { console.log('Alpine.js initialized'); }); } </script></body></html> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430{% extends "base.html" %}
{% block title %}部署状态 - HuggingFace Space 部署器{% endblock %}
{% block content %}<div class="max-w-2xl mx-auto"> <!-- Header --> <div class="text-center mb-8"> <h1 class="text-3xl font-bold mb-4"> <i data-lucide="activity" class="w-8 h-8 inline mr-2"></i> 部署状态监控 </h1> <p class="text-base-content/70">任务 ID: <code class="bg-base-300 px-2 py-1 rounded">{{ task_id }}</code></p> </div>
<!-- Deployment Status Card --> <div class="card bg-base-100 shadow-2xl border border-base-300 fade-in max-w-4xl mx-auto"> <div class="card-body"> <h2 class="card-title text-2xl mb-6 flex items-center"> <i data-lucide="activity" class="w-6 h-6 mr-2"></i> <span data-i18n="status.title">Deployment Status</span> </h2> <!-- Task Info --> <div class="bg-base-200 rounded-lg p-4 mb-6"> <div class="flex items-center justify-between"> <span class="text-sm font-semibold" data-i18n="status.taskId">Task ID</span> <div class="flex items-center gap-2"> <code class="text-xs bg-base-300 px-2 py-1 rounded" id="task-id">{{ task_id }}</code> <button onclick="copyToClipboard('{{ task_id }}')" class="btn btn-ghost btn-xs" data-i18n-title="status.copy" title="Copy" > <i data-lucide="copy" class="w-3 h-3"></i> </button> </div> </div> </div> <!-- Status Container with fixed min-height to prevent jumping --> <div id="status-container" class="min-h-[400px] relative transition-all duration-300"> <!-- Initial loading state --> <div class="status-content absolute inset-0 flex items-center justify-center"> <div class="flex flex-col items-center justify-center py-8"> <div class="loading loading-spinner loading-lg text-primary mb-4"></div> <h3 class="text-xl font-semibold mb-2" data-i18n="status.initializing">Initializing...</h3> <p class="text-base-content/70" data-i18n="status.preparing">Preparing your Space...</p> </div> </div> </div> <!-- Auto-refresh indicator --> <div id="refresh-indicator" class="mt-6 text-center transition-opacity duration-300"> <p class="text-xs text-base-content/50"> <i data-lucide="refresh-cw" class="w-3 h-3 inline mr-1 animate-spin"></i> <span data-i18n="status.autoRefresh">Auto-refresh every 2s</span> </p> </div> <!-- Action Buttons --> <div class="divider mt-8"></div> <div class="flex gap-4 justify-center"> <a href="/" class="btn btn-ghost"> <i data-lucide="arrow-left" class="w-4 h-4 mr-2"></i> <span data-i18n="status.newDeploy">New Deploy</span> </a> <button onclick="window.location.reload()" class="btn btn-ghost" > <i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i> <span data-i18n="status.refresh">Refresh</span> </button> </div> </div> </div>
<!-- Help --> <div class="alert alert-info mt-8"> <i data-lucide="help-circle" class="w-5 h-5"></i> <div> <h3 class="font-bold">关于部署过程</h3> <div class="text-sm mt-2"> <p>• <strong>PENDING:</strong> 任务已创建,等待开始处理</p> <p>• <strong>IN_PROGRESS:</strong> 正在克隆代码并部署到 HuggingFace Spaces</p> <p>• <strong>SUCCESS:</strong> 部署成功,您的应用已上线</p> <p>• <strong>FAILED:</strong> 部署失败,请检查错误信息</p> </div> </div> </div></div>
<style> /* Smooth transitions for status updates */ .status-content { transition: opacity 0.3s ease-in-out; } .status-content.fade-out { opacity: 0; } .status-content.fade-in { opacity: 1; } /* Prevent layout shifts */ #status-container { display: flex; align-items: center; justify-content: center; } /* Progress steps animation */ .steps .step { transition: all 0.3s ease; }</style>
<script> // Deployment status monitoring const taskId = '{{ task_id }}'; let statusInterval = null; let retryCount = 0; const maxRetries = 3; let currentStatus = null; let lastUpdateTime = Date.now(); // Status templates const statusTemplates = { PENDING: () => ` <div class="flex flex-col items-center justify-center py-8"> <div class="loading loading-dots loading-lg text-info mb-4"></div> <h3 class="text-xl font-semibold mb-2">${t('status.queued')}</h3> <p class="text-base-content/70">${t('status.queued.desc')}</p> <div class="mt-6"> <span class="badge badge-info badge-lg"> <i data-lucide="clock" class="w-4 h-4 mr-2"></i> PENDING </span> </div> </div> `, IN_PROGRESS: () => ` <div class="flex flex-col items-center justify-center py-8"> <div class="loading loading-spinner loading-lg text-primary mb-4"></div> <h3 class="text-xl font-semibold mb-2">${t('status.progress')}</h3> <p class="text-base-content/70">${t('status.progress.desc')}</p> <div class="mt-6"> <span class="badge badge-primary badge-lg"> <i data-lucide="loader-2" class="w-4 h-4 mr-2 loading-spinner"></i> IN PROGRESS </span> </div> <div class="mt-8 w-full max-w-md"> <ul class="steps steps-vertical lg:steps-horizontal w-full"> <li class="step step-primary" data-step="1">Initialize</li> <li class="step step-primary" data-step="2">Clone</li> <li class="step step-primary" data-step="3">Build</li> <li class="step" data-step="4">Deploy</li> </ul> </div> </div> `, SUCCESS: (detail) => ` <div class="flex flex-col items-center justify-center py-8"> <div class="mb-4"> <div class="w-20 h-20 bg-success/20 rounded-full flex items-center justify-center"> <i data-lucide="check-circle" class="w-12 h-12 text-success"></i> </div> </div> <h3 class="text-2xl font-bold mb-2 text-success">${t('status.success')}</h3> <p class="text-base-content/70 mb-6">${t('status.success.desc')}</p> <div class="mt-4"> <span class="badge badge-success badge-lg"> <i data-lucide="check" class="w-4 h-4 mr-2"></i> SUCCESS </span> </div> ${detail && detail.space_url ? ` <div class="mt-8 p-6 bg-success/10 border border-success/20 rounded-lg w-full max-w-lg"> <div class="text-center"> <p class="text-sm text-base-content/70 mb-2">${t('status.url')}</p> <div class="flex items-center justify-center gap-2 bg-base-100 p-3 rounded-lg"> <a href="${detail.space_url}" target="_blank" class="link link-primary text-lg font-mono truncate max-w-sm" > ${detail.space_url} </a> <button onclick="copyToClipboard('${detail.space_url}')" class="btn btn-ghost btn-sm" title="${t('status.copy')}" > <i data-lucide="copy" class="w-4 h-4"></i> </button> </div> </div> <div class="mt-6 flex justify-center"> <a href="${detail.space_url}" target="_blank" class="btn btn-success" > <i data-lucide="external-link" class="w-4 h-4 mr-2"></i> <span>${t('status.visit')}</span> </a> </div> </div> ` : ''} </div> `, FAILED: (detail) => ` <div class="flex flex-col items-center justify-center py-8"> <div class="mb-4"> <div class="w-20 h-20 bg-error/20 rounded-full flex items-center justify-center"> <i data-lucide="x-circle" class="w-12 h-12 text-error"></i> </div> </div> <h3 class="text-2xl font-bold mb-2 text-error">${t('status.failed')}</h3> <p class="text-base-content/70 mb-6">${t('status.failed.desc')}</p> <div class="mt-4"> <span class="badge badge-error badge-lg"> <i data-lucide="x" class="w-4 h-4 mr-2"></i> FAILED </span> </div> ${detail && detail.error ? ` <div class="mt-8 p-6 bg-error/10 border border-error/20 rounded-lg w-full max-w-lg"> <div class="flex items-start gap-3"> <i data-lucide="alert-triangle" class="w-5 h-5 text-error mt-0.5"></i> <div class="flex-1"> <p class="font-semibold text-error mb-2">${t('status.error')}</p> <pre class="text-sm bg-base-100 p-3 rounded overflow-x-auto whitespace-pre-wrap">${detail.error}</pre> </div> </div> <div class="mt-6"> <h4 class="font-semibold mb-2">${t('status.troubleshoot')}</h4> <ul class="text-sm space-y-1 text-base-content/70"> <li>• ${t('req.dockerfile')}</li> <li>• ${t('req.token')}</li> <li>• Verify repository URL is accessible</li> <li>• Check Space name is unique</li> </ul> </div> </div> ` : ''} </div> ` }; // Smooth update function function smoothUpdate(container, newContent) { const currentContent = container.querySelector('.status-content'); if (!currentContent) { container.innerHTML = `<div class="status-content">${newContent}</div>`; return; } // Create new content element const newElement = document.createElement('div'); newElement.className = 'status-content absolute inset-0 flex items-center justify-center fade-out'; newElement.innerHTML = newContent; // Add new content container.appendChild(newElement); // Fade out old content and fade in new content currentContent.classList.add('fade-out'); setTimeout(() => { newElement.classList.remove('fade-out'); newElement.classList.add('fade-in'); setTimeout(() => { currentContent.remove(); newElement.classList.remove('absolute'); }, 300); }, 50); } // Fetch status from API async function fetchStatus() { try { const response = await fetch(`/deploy/status/${taskId}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); // Only update if status changed or enough time has passed if (data.status !== currentStatus || Date.now() - lastUpdateTime > 10000) { updateStatus(data); currentStatus = data.status; lastUpdateTime = Date.now(); } retryCount = 0; // Reset retry count on successful fetch } catch (error) { console.error('Failed to fetch status:', error); retryCount++; if (retryCount >= maxRetries) { stopStatusPolling(); showError('Failed to fetch deployment status. Please refresh the page.'); } } } // Update status display function updateStatus(data) { const container = document.getElementById('status-container'); const template = statusTemplates[data.status]; if (template) { smoothUpdate(container, template(data.detail)); // Re-initialize icons after transition setTimeout(() => { if (typeof lucide !== 'undefined') { lucide.createIcons(); } // Update translations if (typeof updatePageTranslations !== 'undefined') { updatePageTranslations(); } }, 350); // Stop polling if final state if (data.status === 'SUCCESS' || data.status === 'FAILED') { stopStatusPolling(); // Show toast notification if (data.status === 'SUCCESS') { showToast(t('toast.deploySuccess'), 'success'); } else { showToast(t('toast.deployFailed'), 'error'); } } } } // Show error message function showError(message) { const container = document.getElementById('status-container'); const errorContent = ` <div class="flex flex-col items-center justify-center py-8"> <div class="mb-4"> <div class="w-20 h-20 bg-error/20 rounded-full flex items-center justify-center"> <i data-lucide="alert-triangle" class="w-12 h-12 text-error"></i> </div> </div> <h3 class="text-xl font-bold mb-2 text-error">Connection Error</h3> <p class="text-base-content/70">${message}</p> </div> `; smoothUpdate(container, errorContent); setTimeout(() => { if (typeof lucide !== 'undefined') { lucide.createIcons(); } }, 350); } // Start status polling function startStatusPolling() { // Initial fetch fetchStatus(); // Set up interval statusInterval = setInterval(fetchStatus, 2000); } // Stop status polling function stopStatusPolling() { if (statusInterval) { clearInterval(statusInterval); statusInterval = null; } // Fade out refresh indicator const indicator = document.getElementById('refresh-indicator'); if (indicator) { indicator.style.opacity = '0'; setTimeout(() => { indicator.style.display = 'none'; }, 300); } } // Initialize on page load document.addEventListener('DOMContentLoaded', function() { startStatusPolling(); // Re-initialize icons setTimeout(() => { if (typeof lucide !== 'undefined') { lucide.createIcons(); } }, 100); }); // Clean up on page unload window.addEventListener('beforeunload', function() { stopStatusPolling(); });</script>{% endblock %} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817{% extends "base.html" %}
{% block title %}Deploy to HuggingFace Spaces{% endblock %}
{% block content %}<!-- Hero Section --><div class="hero bg-gradient-to-br from-primary via-secondary to-accent text-primary-content rounded-2xl mb-10 shadow-2xl"> <div class="hero-content text-center py-20"> <div class="max-w-2xl"> <h1 class="text-6xl font-bold mb-6 flex items-center justify-center"> <i data-lucide="rocket" class="w-16 h-16 mr-4 animate-pulse"></i> <span data-i18n="hero.title">One-Click Deploy</span> </h1> <p class="text-xl opacity-90 mb-8" data-i18n="hero.subtitle"> Deploy to HuggingFace Spaces instantly </p> <div class="stats shadow-lg bg-base-100/20 backdrop-blur"> <div class="stat"> <div class="stat-figure text-secondary"> <i data-lucide="zap" class="w-8 h-8"></i> </div> <div class="stat-title text-primary-content/80" data-i18n="hero.deployTime">Deploy Time</div> <div class="stat-value" data-i18n="hero.minutes">2-5min</div> </div> <div class="stat"> <div class="stat-figure text-secondary"> <i data-lucide="server" class="w-8 h-8"></i> </div> <div class="stat-title text-primary-content/80" data-i18n="hero.freeHosting">Free Hosting</div> <div class="stat-value" data-i18n="hero.percentage">100%</div> </div> </div> </div> </div></div>
<!-- Features Grid --><div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12"> <div class="card bg-base-200 shadow-xl hover:shadow-2xl transition-shadow"> <div class="card-body items-center text-center"> <div class="w-16 h-16 bg-warning/20 rounded-full flex items-center justify-center mb-4"> <i data-lucide="zap" class="w-8 h-8 text-warning"></i> </div> <h2 class="card-title" data-i18n="feature.fast.title">Lightning Fast</h2> <p data-i18n="feature.fast.desc">Deploy from Git in minutes</p> </div> </div> <div class="card bg-base-200 shadow-xl hover:shadow-2xl transition-shadow"> <div class="card-body items-center text-center"> <div class="w-16 h-16 bg-success/20 rounded-full flex items-center justify-center mb-4"> <i data-lucide="shield-check" class="w-8 h-8 text-success"></i> </div> <h2 class="card-title" data-i18n="feature.secure.title">Secure</h2> <p data-i18n="feature.secure.desc">Full control with your token</p> </div> </div> <div class="card bg-base-200 shadow-xl hover:shadow-2xl transition-shadow"> <div class="card-body items-center text-center"> <div class="w-16 h-16 bg-info/20 rounded-full flex items-center justify-center mb-4"> <i data-lucide="activity" class="w-8 h-8 text-info"></i> </div> <h2 class="card-title" data-i18n="feature.monitor.title">Real-time</h2> <p data-i18n="feature.monitor.desc">Live deployment status</p> </div> </div></div>
<!-- Deploy Form --><div class="card bg-base-100 shadow-2xl border border-base-300"> <div class="card-body"> <div class="flex items-center justify-between mb-8"> <h2 class="card-title text-3xl flex items-center"> <i data-lucide="settings" class="w-8 h-8 mr-3"></i> <span data-i18n="form.title">Configuration</span> </h2> <div class="flex gap-2"> <button type="button" onclick="showImportModal()" class="btn btn-ghost btn-sm" data-i18n-title="config.import" title="Import Configuration" > <i data-lucide="upload" class="w-4 h-4 mr-2"></i> <span data-i18n="config.import">Import</span> </button> <button type="button" onclick="showExportModal()" class="btn btn-ghost btn-sm" data-i18n-title="config.export" title="Export Configuration" > <i data-lucide="download" class="w-4 h-4 mr-2"></i> <span data-i18n="config.export">Export</span> </button> </div> </div> <form id="deploy-form" action="/web/deploy" method="POST" class="space-y-6" x-data="{ showAdvanced: false }" > <div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <!-- Left Column --> <div class="space-y-6"> <!-- HuggingFace Token --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold text-lg"> <i data-lucide="key" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.token">HF Token</span> </span> <span class="label-text-alt"> <a href="https://huggingface.co/settings/tokens" target="_blank" class="link link-primary" data-i18n="form.token.get"> Get Token </a> </span> </label> <div class="relative"> <input type="password" name="hf_token" data-i18n-placeholder="form.token.placeholder" placeholder="hf_..." class="input input-bordered input-primary w-full pr-24" required x-ref="tokenInput" > <div class="absolute right-2 top-1/2 -translate-y-1/2 flex gap-1" style="z-index: 10;"> <button type="button" class="btn btn-ghost btn-xs p-1" @click="$refs.tokenInput.type = $refs.tokenInput.type === 'password' ? 'text' : 'password'" data-i18n-title="form.token.toggle" title="Toggle visibility" > <i data-lucide="eye" class="w-4 h-4"></i> </button> <button type="button" class="btn btn-ghost btn-xs p-1" onclick="clearCachedToken()" data-i18n-title="form.token.clear" title="Clear cached token" id="clear-token-btn" style="display: none;" > <i data-lucide="trash-2" class="w-4 h-4"></i> </button> </div> </div> <label class="label"> <span class="label-text-alt text-warning"> <i data-lucide="alert-circle" class="w-3 h-3 inline"></i> <span data-i18n="form.token.hint">Write permission required</span> </span> </label> </div>
<!-- Git Repository URL --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold text-lg"> <i data-lucide="git-branch" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.repo">Git Repository</span> </span> </label> <input type="url" name="git_repo_url" data-i18n-placeholder="form.repo.placeholder" placeholder="https://github.com/user/repo.git" class="input input-bordered input-primary w-full" required > <label class="label"> <span class="label-text-alt" data-i18n="form.repo.hint">GitHub, GitLab, etc.</span> </label> </div> </div>
<!-- Right Column --> <div class="space-y-6"> <!-- Space Name --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold text-lg"> <i data-lucide="tag" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.space">Space Name</span> </span> </label> <input type="text" name="space_name" data-i18n-placeholder="form.space.placeholder" placeholder="my-app" class="input input-bordered input-primary w-full" pattern="[a-zA-Z0-9_\-]+" required > <label class="label"> <span class="label-text-alt" data-i18n="form.space.hint">Letters, numbers, hyphens only</span> </label> </div>
<!-- Description --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold text-lg"> <i data-lucide="file-text" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.desc">Description</span> </span> </label> <textarea name="description" data-i18n-placeholder="form.desc.placeholder" placeholder="Brief description..." class="textarea textarea-bordered textarea-primary h-24" ></textarea> </div> </div> </div>
<!-- Advanced Settings --> <div class="divider"></div> <div class="collapse collapse-plus bg-base-200 rounded-lg"> <input type="checkbox" x-model="showAdvanced" /> <div class="collapse-title text-lg font-medium flex items-center"> <i data-lucide="sliders" class="w-5 h-5 mr-2"></i> <span data-i18n="form.advanced">Advanced</span> </div> <div class="collapse-content"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 pt-4"> <!-- Deploy Path --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold"> <i data-lucide="folder-open" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.deployPath">Deploy Path</span> </span> </label> <input type="text" name="deploy_path" value="/" data-i18n-placeholder="form.deployPath.placeholder" placeholder="/" class="input input-bordered w-full" pattern="^\.?\/?([\w\-\.\/]*)?$" > <label class="label"> <span class="label-text-alt" data-i18n="form.deployPath.hint">Subdirectory to deploy (default: root)</span> </label> </div> <!-- Port --> <div class="form-control"> <label class="label"> <span class="label-text font-semibold"> <i data-lucide="wifi" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.port">Port</span> </span> </label> <input type="number" name="space_port" value="7860" min="1" max="65535" class="input input-bordered w-full" > </div>
<!-- Privacy --> <div class="form-control"> <label class="label cursor-pointer"> <span class="label-text font-semibold"> <i data-lucide="lock" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.private">Private Space</span> </span> <input type="checkbox" name="private" class="toggle toggle-primary" /> </label> </div>
<!-- Environment Variables --> <div class="form-control lg:col-span-2"> <label class="label"> <span class="label-text font-semibold"> <i data-lucide="terminal" class="w-4 h-4 inline mr-2"></i> <span data-i18n="form.env">Environment Variables</span> </span> </label> <textarea name="env_vars_text" data-i18n-placeholder="form.env.placeholder" placeholder="KEY=value" class="textarea textarea-bordered h-32 font-mono text-sm" ></textarea> <label class="label"> <span class="label-text-alt" data-i18n="form.env.hint">One per line</span> </label> </div> </div> </div> </div>
<!-- Submit Button --> <div class="form-control mt-8"> <button type="submit" class="btn btn-primary btn-lg w-full gap-3"> <i data-lucide="rocket" class="w-6 h-6"></i> <span data-i18n="form.submit">Deploy</span> </button> </div> </form> </div></div>
<!-- Loading Overlay --><div id="loading-overlay" class="fixed inset-0 bg-base-100/80 backdrop-blur-sm z-50 flex items-center justify-center" style="display: none;"> <div class="card bg-base-100 shadow-2xl"> <div class="card-body"> <div class="flex flex-col items-center space-y-4"> <div class="loading loading-spinner loading-lg text-primary"></div> <h3 class="text-xl font-semibold" data-i18n="loading.title">Deploying...</h3> <p class="text-base-content/70" data-i18n="loading.desc">Please wait...</p> </div> </div> </div></div>
<!-- Instructions --><div class="mt-12 grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="card bg-info/10 border border-info/20"> <div class="card-body"> <h3 class="card-title text-info"> <i data-lucide="info" class="w-5 h-5"></i> <span data-i18n="req.title">Requirements</span> </h3> <ul class="space-y-2 text-sm"> <li class="flex items-start"> <i data-lucide="check" class="w-4 h-4 mr-2 text-info mt-0.5"></i> <span data-i18n="req.dockerfile">Repository must contain Dockerfile</span> </li> <li class="flex items-start"> <i data-lucide="check" class="w-4 h-4 mr-2 text-info mt-0.5"></i> <span data-i18n="req.token">Token needs write permissions</span> </li> <li class="flex items-start"> <i data-lucide="check" class="w-4 h-4 mr-2 text-info mt-0.5"></i> <span data-i18n="req.time">Deployment takes 2-5 minutes</span> </li> <li class="flex items-start"> <i data-lucide="check" class="w-4 h-4 mr-2 text-info mt-0.5"></i> <span data-i18n="req.docker">Supports Dockerized apps</span> </li> </ul> </div> </div> <div class="card bg-warning/10 border border-warning/20"> <div class="card-body"> <h3 class="card-title text-warning"> <i data-lucide="lightbulb" class="w-5 h-5"></i> <span data-i18n="tips.title">Tips</span> </h3> <ul class="space-y-2 text-sm"> <li class="flex items-start"> <i data-lucide="arrow-right" class="w-4 h-4 mr-2 text-warning mt-0.5"></i> <span data-i18n="tips.test">Test Dockerfile locally</span> </li> <li class="flex items-start"> <i data-lucide="arrow-right" class="w-4 h-4 mr-2 text-warning mt-0.5"></i> <span data-i18n="tips.env">Use env vars for secrets</span> </li> <li class="flex items-start"> <i data-lucide="arrow-right" class="w-4 h-4 mr-2 text-warning mt-0.5"></i> <span data-i18n="tips.size">Keep image size small</span> </li> <li class="flex items-start"> <i data-lucide="arrow-right" class="w-4 h-4 mr-2 text-warning mt-0.5"></i> <span data-i18n="tips.limits">Check HF resource limits</span> </li> </ul> </div> </div></div>
<!-- Import Configuration Modal --><dialog id="import-modal" class="modal"> <div class="modal-box max-w-2xl"> <h3 class="font-bold text-lg mb-4"> <i data-lucide="upload" class="w-5 h-5 inline mr-2"></i> <span data-i18n="config.import.title">Import Configuration</span> </h3> <div class="space-y-4"> <div class="alert alert-info"> <i data-lucide="info" class="w-4 h-4"></i> <span data-i18n="config.import.info">Paste your configuration JSON or share configuration URL</span> </div> <div class="form-control"> <label class="label"> <span class="label-text" data-i18n="config.import.label">Configuration JSON</span> </label> <textarea id="import-config-text" class="textarea textarea-bordered h-48 font-mono text-sm" data-i18n-placeholder="config.import.placeholder" placeholder='{"space_name": "my-app", "git_repo_url": "https://github.com/..."}' ></textarea> </div> <div class="modal-action"> <button type="button" onclick="importConfig()" class="btn btn-primary"> <i data-lucide="check" class="w-4 h-4 mr-2"></i> <span data-i18n="config.import.apply">Apply Configuration</span> </button> <form method="dialog"> <button class="btn btn-ghost" data-i18n="config.cancel">Cancel</button> </form> </div> </div> </div> <form method="dialog" class="modal-backdrop"> <button>close</button> </form></dialog>
<!-- Export Configuration Modal --><dialog id="export-modal" class="modal"> <div class="modal-box max-w-2xl"> <h3 class="font-bold text-lg mb-4"> <i data-lucide="download" class="w-5 h-5 inline mr-2"></i> <span data-i18n="config.export.title">Export Configuration</span> </h3> <div class="space-y-4"> <div class="alert alert-success"> <i data-lucide="check-circle" class="w-4 h-4"></i> <span data-i18n="config.export.info">Configuration exported successfully</span> </div> <div class="form-control"> <label class="label"> <span class="label-text" data-i18n="config.export.label">Configuration JSON</span> <button type="button" onclick="copyExportConfig()" class="btn btn-ghost btn-xs" > <i data-lucide="copy" class="w-4 h-4 mr-1"></i> <span data-i18n="config.copy">Copy</span> </button> </label> <textarea id="export-config-text" class="textarea textarea-bordered h-48 font-mono text-sm" readonly ></textarea> </div> <div class="form-control"> <label class="label"> <span class="label-text" data-i18n="config.export.url">Share URL</span> <button type="button" onclick="copyShareUrl()" class="btn btn-ghost btn-xs" > <i data-lucide="copy" class="w-4 h-4 mr-1"></i> <span data-i18n="config.copy">Copy</span> </button> </label> <input id="share-url" type="text" class="input input-bordered font-mono text-sm" readonly > </div> <div class="modal-action"> <button type="button" onclick="saveConfigAsFile()" class="btn btn-primary"> <i data-lucide="save" class="w-4 h-4 mr-2"></i> <span data-i18n="config.export.save">Save as File</span> </button> <form method="dialog"> <button class="btn btn-ghost" data-i18n="config.close">Close</button> </form> </div> </div> </div> <form method="dialog" class="modal-backdrop"> <button>close</button> </form></dialog>
<script> // Token cache management const TOKEN_CACHE_KEY = 'hf_deploy_token'; // Load cached token on page load function loadCachedToken() { try { const cachedToken = localStorage.getItem(TOKEN_CACHE_KEY); if (cachedToken) { const tokenInput = document.querySelector('input[name="hf_token"]'); if (tokenInput) { tokenInput.value = cachedToken; // Show clear button const clearBtn = document.getElementById('clear-token-btn'); if (clearBtn) { clearBtn.style.display = 'block'; } } } } catch (error) { console.error('Error loading cached token:', error); } } // Save token to cache function saveTokenToCache(token) { try { if (token && token.startsWith('hf_')) { localStorage.setItem(TOKEN_CACHE_KEY, token); } } catch (error) { console.error('Error saving token to cache:', error); } } // Clear cached token function clearCachedToken() { try { localStorage.removeItem(TOKEN_CACHE_KEY); const tokenInput = document.querySelector('input[name="hf_token"]'); if (tokenInput) { tokenInput.value = ''; tokenInput.focus(); } // Hide clear button const clearBtn = document.getElementById('clear-token-btn'); if (clearBtn) { clearBtn.style.display = 'none'; } showToast(t('form.token.cleared') || 'Token cache cleared', 'success'); } catch (error) { console.error('Error clearing cached token:', error); } } // Monitor token input changes function initTokenCacheHandler() { const tokenInput = document.querySelector('input[name="hf_token"]'); if (tokenInput) { let saveTimeout; // Show/hide clear button and auto-save token tokenInput.addEventListener('input', function() { const clearBtn = document.getElementById('clear-token-btn'); if (clearBtn) { clearBtn.style.display = this.value ? 'block' : 'none'; } // Clear previous timeout if (saveTimeout) { clearTimeout(saveTimeout); } // Auto-save valid token with debounce (500ms delay) const token = this.value.trim(); if (token && token.startsWith('hf_')) { saveTimeout = setTimeout(() => { saveTokenToCache(token); // Optional: show a subtle indicator that token was saved const originalBorder = this.style.borderColor; this.style.borderColor = 'var(--success)'; setTimeout(() => { this.style.borderColor = originalBorder; }, 1000); }, 500); } }); // Also save on blur (when user leaves the field) tokenInput.addEventListener('blur', function() { const token = this.value.trim(); if (token && token.startsWith('hf_')) { saveTokenToCache(token); } }); } } // Configuration management const CONFIG_FIELDS = { git_repo_url: 'input[name="git_repo_url"]', space_name: 'input[name="space_name"]', description: 'textarea[name="description"]', deploy_path: 'input[name="deploy_path"]', space_port: 'input[name="space_port"]', private: 'input[name="private"]', env_vars_text: 'textarea[name="env_vars_text"]' }; // Check for config in URL on page load document.addEventListener('DOMContentLoaded', function() { checkUrlConfig(); // Load cached token loadCachedToken(); initTokenCacheHandler(); // Re-initialize icons after DOM updates setTimeout(() => { if (typeof lucide !== 'undefined') { lucide.createIcons(); } }, 100); }); // Listen for hash changes (e.g., when user navigates to a URL with config) window.addEventListener('hashchange', function() { checkUrlConfig(); }); // Check URL for config parameter function checkUrlConfig() { // Check fragment instead of query parameters const hash = window.location.hash; if (hash && hash.startsWith('#config=')) { try { // Extract config from fragment const configParam = hash.substring(8); // Remove '#config=' // Decode base64 and parse JSON const configJson = atob(configParam); const config = JSON.parse(configJson); applyConfiguration(config); // Show success toast showToast(t('config.import.success'), 'success'); // Remove config from URL to clean up window.history.replaceState({}, document.title, window.location.pathname); } catch (error) { console.error('Failed to load config from URL:', error); showToast(t('config.import.error'), 'error'); } } } // Show import modal function showImportModal() { document.getElementById('import-modal').showModal(); // Re-initialize icons in modal setTimeout(() => lucide.createIcons(), 100); } // Show export modal function showExportModal() { const config = extractConfiguration(); const configJson = JSON.stringify(config, null, 2); // Set export text document.getElementById('export-config-text').value = configJson; // Generate share URL using fragment instead of query parameter const encoded = btoa(configJson); const shareUrl = `${window.location.origin}${window.location.pathname}#config=${encoded}`; document.getElementById('share-url').value = shareUrl; document.getElementById('export-modal').showModal(); // Re-initialize icons in modal setTimeout(() => lucide.createIcons(), 100); } // Extract current form configuration function extractConfiguration() { const config = {}; for (const [field, selector] of Object.entries(CONFIG_FIELDS)) { const element = document.querySelector(selector); if (element) { if (element.type === 'checkbox') { config[field] = element.checked; } else { config[field] = element.value; } } } return config; } // Apply configuration to form function applyConfiguration(config) { for (const [field, selector] of Object.entries(CONFIG_FIELDS)) { const element = document.querySelector(selector); if (element && config.hasOwnProperty(field)) { if (element.type === 'checkbox') { element.checked = config[field]; } else { element.value = config[field]; } // Trigger change event for any listeners element.dispatchEvent(new Event('change', { bubbles: true })); } } // Expand advanced settings if any advanced field is set if (config.deploy_path || config.space_port !== 7860 || config.private || config.env_vars_text) { const advancedToggle = document.querySelector('.collapse input[type="checkbox"]'); if (advancedToggle) { advancedToggle.checked = true; } } } // Import configuration from modal function importConfig() { const configText = document.getElementById('import-config-text').value.trim(); if (!configText) { showToast(t('config.import.empty'), 'warning'); return; } try { const config = JSON.parse(configText); applyConfiguration(config); // Close modal document.getElementById('import-modal').close(); // Show success toast showToast(t('config.import.success'), 'success'); } catch (error) { console.error('Invalid configuration JSON:', error); showToast(t('config.import.invalid'), 'error'); } } // Copy export configuration function copyExportConfig() { const configText = document.getElementById('export-config-text'); configText.select(); navigator.clipboard.writeText(configText.value).then(() => { showToast(t('config.copied'), 'success'); }); } // Copy share URL function copyShareUrl() { const shareUrl = document.getElementById('share-url'); shareUrl.select(); navigator.clipboard.writeText(shareUrl.value).then(() => { showToast(t('config.url.copied'), 'success'); }); } // Save configuration as file function saveConfigAsFile() { const config = extractConfiguration(); const configJson = JSON.stringify(config, null, 2); // Create blob and download const blob = new Blob([configJson], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `hf-deploy-config-${config.space_name || 'config'}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showToast(t('config.export.saved'), 'success'); } // Form validation and enhancement document.getElementById('deploy-form').addEventListener('submit', function(e) { const submitBtn = e.target.querySelector('button[type="submit"]'); submitBtn.disabled = true; // Show loading overlay document.getElementById('loading-overlay').style.display = 'flex'; }); // Initialize all interactive elements after page load document.addEventListener('DOMContentLoaded', function() { // Re-initialize Lucide icons if (typeof lucide !== 'undefined') { lucide.createIcons(); } // Make sure HTMX is initialized if (typeof htmx !== 'undefined') { htmx.process(document.body); } // Initialize eye toggle button for password visibility setTimeout(() => { lucide.createIcons(); }, 100); });</script>{% endblock %} 123456import os, stat
def _chmod_and_retry(func, path, exc): os.chmod(path, stat.S_IWRITE) func(path)1234567891011121314151617#!/usr/bin/env python3"""HuggingFace Space DeployerA web application for deploying code to HuggingFace Spaces with one click."""
import uvicorn
if __name__ == "__main__": uvicorn.run( "app.routes:app", host="0.0.0.0", port=7860, reload=False, log_level="info" )1234567891011fastapi>=0.104.0uvicorn[standard]>=0.24.0jinja2>=3.1.0python-multipart>=0.0.6python-dotenv>=1.0.0huggingface-hub>=0.19.0aiofiles>=23.0.0redispydanticpydantic_settingsgitpython>=3.1.301234567891011#!/bin/sh
# 以后台模式启动 Redis Server,禁用持久化# 注意:以 appuser 身份运行,确保它有权限在默认位置或 /tmp 中创建必要文件redis-server --daemonize yes --loglevel warning --save "" --appendonly no --pidfile /tmp/redis.pid
# 等待 Redis 启动 (可选,但有时有帮助)sleep 2
# 在前台启动 Python 应用 (这个命令会保持容器运行)exec python main.py.env.templateAdded+2
.gitignoreAdded+9
DockerfileAdded+38
LICENSEAdded+674
app/auth.pyAdded+15
app/config.pyAdded+21
app/deploy.pyAdded+111
app/exceptions.pyAdded+18
app/models.pyAdded+19
app/routes.pyAdded+104
app/static/i18n.jsAdded+307
app/static/style.cssAdded+737
app/store.pyAdded+43
app/templates/base.htmlAdded+216
app/templates/deploy_status.htmlAdded+430
app/templates/index.htmlAdded+817
app/utils.pyAdded+6
images/img0.pngAdded

images/img1.pngAdded

images/img2.pngAdded

main.pyAdded+17
requirements.txtAdded+11
start.shAdded+11