Spaces:
Running on Zero
Running on Zero
Private r6 CPU and ZeroGPU ticket bridge with TiGa UI
Browse filesFiles changed (12)
- DATA_POLICY.md+11-3
- README.md+2-2
- RELEASE_MANIFEST.json+13-7
- app.py+98-24
- app_release.pyAdded+33
- client.js+15-1
- gpu_tickets.pyAdded+39
- requirements.txt+1
- vendor/gradio-client/LICENSEAdded+201
- vendor/gradio-client/dist/index.min.jsAdded+2115
- vendor/gradio-client/package.jsonAdded+53
- worker.py+15-3
3 unmodified lines4567891020 unmodified lines31323334353 unmodified linesFiles are processed only for the requested job, not collected for our owntraining, analytics or public examples. Inputs remain in the browser until Run.This local test uses native CPU; the hosted GPU path is not yet integrated.Each job uses temporary files removed before a successful result is published.The application result store is memory-only. No public file URL is created.20 unmodified linesagain can retry a local save without another server retrieval. Discard browserresult clears the app's reference; closing or refreshing the page loses it.No bucket support, network sandbox or provider-wide ZDR guarantee is offered.The development service is single-process and loopback-only. Public deploymentand its framework/proxy behavior must be tested separately before release.3 unmodified lines45678910111213141516171820 unmodified lines39404142433 unmodified linesFiles are processed only for the requested job, not collected for our owntraining, analytics or public examples. Inputs remain in the browser until Run.The interface supports native CPU and, on a ZeroGPU deployment, an explicitlyselected GPU job. CPU requests do not acquire a GPU lease.GPU inputs await dispatch in application memory for at most 120 seconds. Thequeue receives a random one-use ticket, not the uploaded track or network bytes.Inputs are released from the pending store on dispatch, expiry or shutdown.The framework may retain ticket and result metadata in its transient queue/sessionbuffers; result metadata includes the temporary job access key. Framework fileuploads and run history are disabled. These restrictions are not secure RAM erasure.Each job uses temporary files removed before a successful result is published.The application result store is memory-only. No public file URL is created.20 unmodified linesagain can retry a local save without another server retrieval. Discard browserresult clears the app's reference; closing or refreshing the page loses it.No bucket support, network sandbox or provider-wide ZDR guarantee is offered.The service uses one result-owning process. Public deployment and itsframework/proxy behavior must be tested separately before release.
5 unmodified lines678910111213145 unmodified linesapp_file: app.py---Private CPU integration candidate. Custom FastAPI interface on port 7860.Simulator: https://github.com/Zorro909/driving_sim_rsHosting adaptation and UI: TiGa https://github.com/seeker-cyber-maker/driving_sim_rsGPU is deliberately unavailable in this candidate. No bundled tracks or networks.One server process; no persistent storage. See DATA_POLICY.md for retention limits.Not yet verified in the hosted Linux runtime; do not publish as a stable release.5 unmodified lines678910111213145 unmodified linesapp_file: app.py---Private CPU/ZeroGPU integration candidate. Custom interface with Gradio Server on port 7860.Simulator: https://github.com/Zorro909/driving_sim_rsHosting adaptation and UI: TiGa https://github.com/seeker-cyber-maker/driving_sim_rsCPU is the default; GPU requests explicitly use ZeroGPU. No automatic fallback. No bundled tracks or networks.One server process; no persistent storage. See DATA_POLICY.md for retention limits.Not yet verified in the hosted Linux runtime; do not publish as a stable release.
123456789101112131415161718192021{"backend": "cpu","files": {"DATA_POLICY.md": "99844eda4df9f68be4b06ce7671a18474bd2a860ff20b30a221163698bfaef6d","GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304","IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d","LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8","README.md": "8711574749eb4cc53da0253c40692868b337adb63ce045f2c881840982a032a8","app.py": "40cef7e65bbcf9798eaa1374a2c7be4bb45a5d4e70e981a1eeb8b0b2f2a00c35","assets/formula_template.json": "80f745df82bb7be45af52785fd582460bcddc63c5a4e1d8375d85b3122db4c6b","bin/altd-sim": "2f2f2144ae14b0ef599ca8510f95712da00243c6875881491d384b394e7499f7","bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a","client.js": "b2a1c68bf50aae0acfeccb7ee0947e9aceb0d90c5c92d241f8b42fbdaec445f9","delivery.py": "4f5a4e45df92e5cbfdef6eb449ede9ba26217fe24da376fafddae5cbbb73847a","index.html": "caeafcd208a638cd8c4235ca282b5b6451b81eb0e363fcfbb2ee02ed021a4db0","requirements.txt": "dbdedd8a6f30e16dc41bc3e210c1a936f679655420075f8f89bdd40bdd03f91b","server.py": "6375fb9f0a6ed39be0d7ce3cbe5c4c820e412e91417f424ad10a1b5f6f94062f","worker.py": "3370c812e1a48b7b7f09deaca769bb1a5c7ec30ca776dc97e484181e6bcec7c3"},"hosted_verified": false,"upstream_revision": "d8ab74c25df70b6a86ed101080e33d5fb785ea6f"123456789101112131415161718192021222324252627{"backend": "cpu+zerogpu","files": {"DATA_POLICY.md": "79710230144f8682507a70487821cd32867795d68e6fae48d1b1f99dece36ad6","GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304","IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d","LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8","README.md": "48b536eb04507f65e4ea4101e30d34368f26719f75a2a294b75523f7c0225c37","app.py": "77c5b760c7c74bdd9c143165f80321f9d8a6407d7d60c2d2035cf25704f3c071","app_release.py": "40cef7e65bbcf9798eaa1374a2c7be4bb45a5d4e70e981a1eeb8b0b2f2a00c35","assets/formula_template.json": "80f745df82bb7be45af52785fd582460bcddc63c5a4e1d8375d85b3122db4c6b","bin/altd-sim": "2f2f2144ae14b0ef599ca8510f95712da00243c6875881491d384b394e7499f7","bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a","bin/libaltd_gpu.so": "279d6353b4c691686d6aeeae6abfd4a82b959e9b604f079a6c45f9823b48a87a","client.js": "d0a338ff461ef5115019e0362e33a12a15569f135dc4e9573daa74045b31de72","delivery.py": "4f5a4e45df92e5cbfdef6eb449ede9ba26217fe24da376fafddae5cbbb73847a","gpu_tickets.py": "9e2cf757ddc46ca30b49cd6de07e5d84f328a858240afaad2e72453d24803f5a","index.html": "caeafcd208a638cd8c4235ca282b5b6451b81eb0e363fcfbb2ee02ed021a4db0","requirements.txt": "34d25326bd356675e0c198df31b5f949bfd3b952479f50818eb0a2ac7ee7b7f6","server.py": "6375fb9f0a6ed39be0d7ce3cbe5c4c820e412e91417f424ad10a1b5f6f94062f","vendor/gradio-client/LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","vendor/gradio-client/dist/index.min.js": "fdd776db8633354f118fe2908c980592283968737e6b91dc3aa86d648da5c3fd","vendor/gradio-client/package.json": "96c5b9e6d3587fb7bd8e5bb28775ece222de1043045afc4e6389c88db137ad0e","worker.py": "421b2d92880cc9e501050dcf402440cf3c683943e722e1439b6a504ef52eead0"},"hosted_verified": false,"upstream_revision": "d8ab74c25df70b6a86ed101080e33d5fb785ea6f"
123456789101112131415161718192021222324252627282930313233"""HF CPU release entrypoint. One process owns all ephemeral results."""import hashlibimport jsonfrom pathlib import Pathfrom server import create_appfrom worker import run_nativeROOT=Path(__file__).resolve().parentdef verify_package(root=ROOT):manifest=json.loads((root/'RELEASE_MANIFEST.json').read_text())for name,expected in manifest['files'].items():path=(root/name).resolve()if not path.is_relative_to(root.resolve()) or not path.is_file():raise RuntimeError('Invalid release member')if hashlib.sha256(path.read_bytes()).hexdigest()!=expected:raise RuntimeError('Release integrity check failed: '+name)return manifestdef cpu_worker(track,network):return run_native(track,network,binary=ROOT/'bin/altd-sim',importer=ROOT/'bin/extract_saved_track',scene_template=ROOT/'assets/formula_template.json',with_report=True)def main():verify_package()for name in ('altd-sim','extract_saved_track'):(ROOT/'bin'/name).chmod(0o755)import uvicornuvicorn.run(create_app(worker=cpu_worker),host='0.0.0.0',port=7860,workers=1,access_log=False)if __name__=='__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Undeployed ZeroGPU integration candidate. Never enable on CPU-only hosting.Browser must invoke /gpu_train with @gradio/client for caller quota propagation.The queue carries only an opaque ticket; result bytes stay in the existing store."""import asyncioimport base64from contextlib import asynccontextmanagerimport jsonimport threadingimport osos.environ['GRADIO_ANALYTICS_ENABLED']='False'import gradio as grimport spacesfrom fastapi import HTTPException,Requestfrom fastapi.responses import FileResponse,JSONResponsefrom app_release import ROOT,cpu_worker,verify_packagefrom gpu_tickets import InputTicketsfrom server import create_appfrom worker import run_native,track_input,network_inputdef build_app(cuda_call):base=create_app(worker=cpu_worker)tickets=InputTickets()admission=threading.BoundedSemaphore(1)@asynccontextmanagerasync def lifespan(app):async def expire():while True:await asyncio.sleep(1)tickets.expire()async with base.router.lifespan_context(base):task=asyncio.create_task(expire())try:yieldfinally:task.cancel()try:await taskexcept asyncio.CancelledError:passtickets.clear()app=gr.Server(lifespan=lifespan,docs_url=None,redoc_url=None,openapi_url=None)@app.middleware('http')async def no_framework_file_storage(request,call_next):# This UI sends bounded bytes through prepare, never Gradio file uploads.path=request.url.pathif path.startswith(('/gradio_api/upload','/gradio_api/file=','/gradio_api/stream/','/gradio_api/run/','/gradio_api/runs')):return JSONResponse({'detail':'File storage and run history are disabled'},status_code=404)return await call_next(request)@app.get('/api/capabilities')def capabilities():return {'cpu':True,'gpu':True,'default':'cpu','gpu_transport':'gradio-ticket'}@app.get('/gradio-client.js')def javascript_client():return FileResponse(ROOT/'vendor/gradio-client/dist/index.min.js',media_type='text/javascript')@app.post('/api/gpu/prepare')async def prepare(request:Request):data=bytearray()async for chunk in request.stream():if len(data)+len(chunk)>3*1024*1024:raise HTTPException(413,'Request too large')data.extend(chunk)try:body=json.loads(data)track=base64.b64decode(body['track'],validate=True)network=base64.b64decode(body['network'],validate=True)track_input(track);network_input(network)ticket=tickets.put(track,network,body.get('automatic',True))return {'ticket':ticket,'expires_in_seconds':120}except RuntimeError:raise HTTPException(429,'GPU input capacity reached') from Noneexcept Exception:raise HTTPException(400,'Invalid GPU input') from Nonefinally:data.clear()@app.api(name='gpu_train',concurrency_limit=1,concurrency_id='gpu',api_visibility='undocumented')def gpu_train(ticket:str)->dict:if not admission.acquire(blocking=False):raise ValueError('GPU worker busy')try:track,network,automatic=tickets.take(ticket)payload,report=cuda_call(track,network)return {**base.state.results.publish(payload,automatic),'backend':'gpu','report':report}finally:admission.release()# Existing download/status/ACK/delete and CPU routes use the same result store.for route in base.router.routes:if getattr(route,'path',None)!='/api/capabilities':app.router.routes.append(route)for middleware in base.user_middleware:app.add_middleware(middleware.cls,*middleware.args,**middleware.kwargs)return appdef main():verify_package()for name in ('altd-sim','extract_saved_track'):(ROOT/'bin'/name).chmod(0o755)@spaces.GPU(duration=90)def cuda(track,network):return run_native(track,network,binary=ROOT/'bin/altd-sim',importer=ROOT/'bin/extract_saved_track',scene_template=ROOT/'assets/formula_template.json',gpu_library=ROOT/'bin/libaltd_gpu.so',with_report=True)build_app(cuda).launch(server_name='0.0.0.0',server_port=7860,run_history=False,enable_monitoring=False,show_error=False)if __name__=='__main__':main()
123456789101112131415161718192021222324252627282930313233"""HF CPU release entrypoint. One process owns all ephemeral results."""import hashlibimport jsonfrom pathlib import Pathfrom server import create_appfrom worker import run_native
ROOT=Path(__file__).resolve().parent
def verify_package(root=ROOT): manifest=json.loads((root/'RELEASE_MANIFEST.json').read_text()) for name,expected in manifest['files'].items(): path=(root/name).resolve() if not path.is_relative_to(root.resolve()) or not path.is_file(): raise RuntimeError('Invalid release member') if hashlib.sha256(path.read_bytes()).hexdigest()!=expected: raise RuntimeError('Release integrity check failed: '+name) return manifest
def cpu_worker(track,network): return run_native(track,network,binary=ROOT/'bin/altd-sim', importer=ROOT/'bin/extract_saved_track', scene_template=ROOT/'assets/formula_template.json',with_report=True)
def main(): verify_package() for name in ('altd-sim','extract_saved_track'): (ROOT/'bin'/name).chmod(0o755) import uvicorn uvicorn.run(create_app(worker=cpu_worker),host='0.0.0.0',port=7860, workers=1,access_log=False)
if __name__=='__main__': main()3 unmodified lines45678934 unmodified lines4445464748495058 unmodified lines1091101111121131143 unmodified lineslet busy = false;let localResult = null;let capabilitiesReady = false;const say = text => { $('status').textContent = text; };function buttons() {$('run').disabled = busy || !!job || !capabilitiesReady;34 unmodified linesbusy=true; buttons(); say('Processing the bounded test…');try {const body={track:await encoded($('track').files[0]),network:await encoded($('network').files[0]),automatic:$('automatic').checked,backend:$('backend').value};job=await (await request('/api/process',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})).json();clearInterval(progress);$('runState').textContent='COMPLETE — candidate ready to download';$('runState').style.color='#62dfb1';58 unmodified linestry {const capabilities=await (await request('/api/capabilities',{signal:controller.signal})).json();if(capabilities.cpu!==true)throw new Error('CPU unavailable');$('gpuOption').disabled=!capabilities.gpu;$('backendNote').textContent=capabilities.gpu?'CPU uses no GPU allowance. GPU requires available allowance. No automatic switching.':'CPU available. GPU is not connected on this deployment; no GPU allowance is needed for CPU.';capabilitiesReady=true; buttons();3 unmodified lines456789101134 unmodified lines46474849505152535455565758596061626358 unmodified lines1221231241251261271283 unmodified lineslet busy = false;let localResult = null;let capabilitiesReady = false;let gpuTransport = null;let gradioClient = null;const say = text => { $('status').textContent = text; };function buttons() {$('run').disabled = busy || !!job || !capabilitiesReady;34 unmodified linesbusy=true; buttons(); say('Processing the bounded test…');try {const body={track:await encoded($('track').files[0]),network:await encoded($('network').files[0]),automatic:$('automatic').checked,backend:$('backend').value};if(body.backend==='gpu' && gpuTransport==='gradio-ticket'){// Official client preserves the caller's ZeroGPU quota context.if(!gradioClient){const {Client}=await import('/gradio-client.js');gradioClient=await Client.connect(location.origin);}const prepared=await (await request('/api/gpu/prepare',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})).json();const result=await gradioClient.predict('/gpu_train',[prepared.ticket]);job=result.data[0];}else{job=await (await request('/api/process',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})).json();}clearInterval(progress);$('runState').textContent='COMPLETE — candidate ready to download';$('runState').style.color='#62dfb1';58 unmodified linestry {const capabilities=await (await request('/api/capabilities',{signal:controller.signal})).json();if(capabilities.cpu!==true)throw new Error('CPU unavailable');gpuTransport=capabilities.gpu_transport??null;$('gpuOption').disabled=!capabilities.gpu;$('backendNote').textContent=capabilities.gpu?'CPU uses no GPU allowance. GPU requires available allowance. No automatic switching.':'CPU available. GPU is not connected on this deployment; no GPU allowance is needed for CPU.';capabilitiesReady=true; buttons();
123456789101112131415161718192021222324252627282930313233343536373839"""One-use, short-lived in-memory inputs for a queued GPU lease.
Only opaque tickets enter the Gradio queue, never track/network bytes. Thisstore is not persistent and must be cleared by the owning application's lifespan."""import secretsimport threadingimport time
class InputTickets: def __init__(self,clock=time.monotonic): self.clock=clock self.lock=threading.RLock() self.pending={}
def expire(self): with self.lock: for ticket,item in list(self.pending.items()): if self.clock()>=item[0]:del self.pending[ticket]
def put(self,track,network,automatic): if not isinstance(track,bytes) or not isinstance(network,bytes):raise ValueError('Expected bytes') if not track or not network or max(len(track),len(network))>1024*1024:raise ValueError('Input size') if type(automatic) is not bool:raise ValueError('Automatic mode') with self.lock: self.expire() if self.pending:raise RuntimeError('GPU input capacity reached') ticket=secrets.token_urlsafe(32) self.pending[ticket]=(self.clock()+120,track,network,automatic) return ticket
def take(self,ticket): with self.lock: self.expire() if ticket not in self.pending:raise ValueError('GPU input unavailable') return self.pending.pop(ticket)[1:]
def clear(self): with self.lock:self.pending.clear()12fastapi==0.141.1uvicorn==0.52.1123fastapi==0.141.1uvicorn==0.52.1spaces==0.51.1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115//#region \0rolldown/runtime.jsvar e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => { if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, { get: ((e) => i[e]).bind(null, d), enumerable: !(s = n(i, d)) || s.enumerable }); return e;}, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", { value: n, enumerable: !0}) : a, n)), l = "host", u = "queue/data", d = "queue/join", f = "upload", p = "login", m = "config", ee = "info", h = "runtime", g = "sleeptime", _ = "heartbeat", te = "component_server", ne = "reset", re = "cancel", ie = "app_id", ae = "This application is currently busy. Please try again. ", v = "Connection errored out. ", y = "Could not resolve app config. ", b = "Could not get space status. ", oe = "Could not get API info. ", x = "Space metadata could not be loaded. ", se = "Invalid URL. A full URL path is required.", S = "Not authorized to access this space. ", C = "Invalid credentials. Could not login. ", w = "Login credentials are required to access this space.", ce = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", T = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, le = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", ue = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", de = "File system access is only available in Node.js environments", fe = "Root URL not found in client config", pe = "Error uploading file";//#endregion//#region src/helpers/init_helpers.tsasync function me(e, t, n) { try { return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: { Authorization: `Bearer ${t}`, ...n ? { Cookie: n } : {} } })).json()).token || !1; } catch { return !1; }}function he(e) { e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."));}function E(e) { let t = {}; return e.forEach(({ api_name: e, id: n }) => { e && (t[e] = n); }), t;}function ge(e, t, n = !1) { let r = new URL(t), i = new URL(e, r), a = i.hostname.endsWith(".colab-user-runtimes.internal") || i.hostname.endsWith(".codatalab-user-runtimes.internal"); return n || a ? new URL(new URL(e, r).pathname, r).toString().replace(/\/$/, "") : i.hostname === r.hostname ? (i.protocol = r.protocol, i.host = r.host, i.toString().replace(/\/$/, "")) : e;}async function D(e, t = !0) { let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}; if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") { if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") { let t = new URL(I(e, m)); this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); let r = await O(await this.fetch(t, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !!this.options.auth); r.root = e || r.root, window.gradio_config = { ...r, current_page: window.gradio_config.current_page }; } let r = { ...window.gradio_config }; return r.root = ge(r.root, location.href, r.is_colab), r; } else if (e) { let t = new URL(I(e, m)); this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); let r = await O(await this.fetch(t, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !!this.options.auth); return r.root ||= e, r; } throw Error(y);}async function O(e, t) { if (e?.status === 401 && !t) { let t = null; try { t = await e.json(); } catch { throw Error(ce); } let n = t?.detail?.auth_message; throw Error(n || "Login credentials are required to access this space."); } else if (e?.status === 401 && t) throw Error(C); if (e?.status === 200) { let t = await e.json(); return t.dependencies?.forEach((e, t) => { e.id === void 0 && (e.id = t); }), t; } else if (e?.status === 401) throw Error(S); throw Error(`${y}(received status ${e?.status} when fetching the app config)`);}async function k() { let { http_protocol: e, host: t } = await F(this.app_reference, this.options.token); try { if (this.options.auth) { let n = await A(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials); n && this.set_cookies(n); } } catch (e) { throw Error(e.message); }}async function A(e, t, n, r, i, a) { let o = new FormData(); o.append("username", n?.[0]), o.append("password", n?.[1]); let s = {}; i && (s.Authorization = `Bearer ${i}`); let c = await r(`${e}//${t}/${p}`, { headers: s, method: "POST", body: o, credentials: a ?? "same-origin" }); if (c.status === 200) return c.headers.get("set-cookie"); throw c.status === 401 ? Error(C) : Error(x);}function j(e) { if (e.startsWith("http")) { let { protocol: t, host: n, pathname: r } = new URL(e); return { ws_protocol: t === "https:" ? "wss" : "ws", http_protocol: t, host: n + (r === "/" ? "" : r) }; } return { ws_protocol: "wss", http_protocol: "https:", host: new URL(e).host };}var M = (e) => { let t = []; return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => { let [n, r] = e.split(";")[0].split("="); n && r && t.push(`${n.trim()}=${r.trim()}`); }), t;}, N = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, P = /.*hf\.space\/{0,1}.*$/;async function F(e, t) { let n = {}; t && (n.Authorization = `Bearer ${t}`); let r = e.trim().replace(/\/$/, ""); if (N.test(r)) { let e; try { e = await fetch(`https://huggingface.co/api/spaces/${r}/${l}`, { headers: n }); } catch { throw Error(x); } if (e.status === 401 || e.status === 404) throw Error(T(r, e.status)); let t; try { t = (await e.json()).host; } catch { throw Error(x); } if (!t) throw Error(x); return { space_id: r, ...j(t) }; } if (P.test(r)) { let { ws_protocol: e, http_protocol: t, host: n } = j(r); return { space_id: n.split("/")[0].replace(".hf.space", ""), ws_protocol: e, http_protocol: t, host: n }; } return { space_id: !1, ...j(r) };}var I = (...e) => { try { return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString())); } catch { throw Error(se); }};function _e(e, t, n) { let r = { named_endpoints: {}, unnamed_endpoints: {} }; return Object.keys(e).forEach((i) => { (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => { let o = a?.parameters ?? [], s = a?.returns ?? [], c = t.dependencies.find((t) => t.api_name === e || t.api_name === e.replace("/", ""))?.id || n[e.replace("/", "")] || -1, l = c === -1 ? void 0 : t.dependencies.find((e) => e.id == c), u = c === -1 ? { generator: !1, cancel: !1 } : l?.types; if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) { let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type); try { e.forEach((e, t) => { e === "state" && o.splice(t, 0, { component: "state", example: null, parameter_default: null, parameter_has_default: !0, parameter_name: null, hidden: !0 }); }); } catch (e) { console.error(e); } } let d = (e, t, n, r) => ({ ...e, description: ve(e?.type, n), type: L(e?.type, t, n, r) || "" }); r[i][e] = { parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")), returns: s.map((e) => d(e, e?.component, e?.serializer, "return")), type: u, ...a?.oauth_token ? { oauth_token: a.oauth_token } : {} }; })); }), r;}function L(e, t, n, r) { if (t === "Api") return e.type; switch (e?.type) { case "string": return "string"; case "boolean": return "boolean"; case "number": return "number"; } if (n === "JSONSerializable" || n === "StringSerializable") return "any"; if (n === "ListStringSerializable") return "string[]"; if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string"; if (n === "FileSerializable") return e?.type === "array" ? r === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : r === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}"; if (n === "GallerySerializable") return r === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]";}function ve(e, t) { return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description;}function ye(e, t) { switch (e.msg) { case "send_data": return { type: "data" }; case "send_hash": return { type: "hash" }; case "queue_full": return { type: "update", status: { queue: !0, message: ae, stage: "error", code: e.code, success: e.success } }; case "heartbeat": return { type: "heartbeat" }; case "unexpected_error": return { type: "unexpected_error", status: { queue: !0, message: e.message, session_not_found: e.session_not_found, stage: "error", success: !1 } }; case "broken_connection": return { type: "broken_connection", status: { queue: !0, message: e.message, stage: "error", success: !1 } }; case "estimation": return { type: "update", status: { queue: !0, stage: t || "pending", code: e.code, size: e.queue_size, position: e.rank, eta: e.rank_eta, success: e.success } }; case "progress": return { type: "update", status: { queue: !0, stage: "pending", code: e.code, progress_data: e.progress_data, success: e.success } }; case "log": return { type: "log", data: e }; case "process_generating": return { type: "generating", status: { queue: !0, message: e.success ? null : e.output.error, stage: e.success ? "generating" : "error", code: e.code, progress_data: e.progress_data, eta: e.average_duration, changed_state_ids: e.success ? e.output.changed_state_ids : void 0 }, data: e.success ? e.output : null }; case "process_streaming": return { type: "streaming", status: { queue: !0, message: e.output.error, stage: "streaming", time_limit: e.time_limit, code: e.code, progress_data: e.progress_data, changed_state_ids: e.output.changed_state_ids, eta: e.eta }, data: e.output }; case "process_completed": return "error" in e.output ? { type: "update", status: { queue: !0, title: e.output.title ?? "Error", message: e.output.error ?? "An error occurred", visible: e.output.visible, duration: e.output.duration, stage: "error", code: e.code, success: e.success } } : { type: "complete", status: { queue: !0, message: e.success ? void 0 : e.output.error, stage: e.success ? "complete" : "error", code: e.code, progress_data: e.progress_data, changed_state_ids: e.success ? e.output.changed_state_ids : void 0, used_cache: e.used_cache, cache_duration: e.cache_duration, avg_time: e.avg_time }, data: e.success ? e.output : null }; case "process_starts": return { type: "update", status: { queue: !0, stage: "pending", code: e.code, size: e.rank, position: 0, success: e.success, eta: e.eta }, original_msg: "process_starts" }; } return { type: "none", status: { stage: "error", queue: !0 } };}var be = (e = [], t) => { let n = t ? t.parameters : []; if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e; let r = [], i = Object.keys(e); return n.forEach((t, n) => { if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name]; else if (t.parameter_has_default) r[n] = t.parameter_default; else throw Error(`No value provided for required parameter: ${t.parameter_name}`); }), i.forEach((e) => { if (!n.some((t) => t.parameter_name === e)) throw Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`); }), r.forEach((e, t) => { if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`); }), r;};//#endregion//#region src/utils/view_api.tsasync function xe() { if (this.api_info) return this.api_info; let { token: e } = this.options, { config: t } = this, n = {}; if (e && (n.Authorization = `Bearer ${e}`), t) try { let e, r; if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info; else { let i = new URL(I(t.root, this.api_prefix, ee)); if (this.page !== null && i.searchParams.set("page", this.page), e = await this.fetch(i, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !e.ok) throw Error(v); r = await e.json(); } return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), _e(r, t, this.api_map); } catch (e) { throw Error("Could not get API info. " + e.message); }}//#endregion//#region src/utils/upload_files.tsasync function Se(e, t, n) { let r = {}; this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`); let i = 1e3, a = [], o; for (let s = 0; s < t.length; s += i) { let c = t.slice(s, s + i), l = new FormData(); c.forEach((e) => { l.append("files", e); }); try { let t = n ? `${e}${this.api_prefix}/${f}?upload_id=${n}` : `${e}${this.api_prefix}/${f}`; o = await this.fetch(t, { method: "POST", body: l, headers: r, credentials: this.options.credentials ?? "same-origin" }); } catch (e) { throw Error(v + e.message); } if (!o.ok) { let e = await o.text(); return { error: `HTTP ${o.status}: ${e}` }; } let u = await o.json(); u && a.push(...u); } return { files: a };}var R = { si: { radix: 1e3, unit: [ "b", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb" ] }, iec: { radix: 1024, unit: [ "b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib" ] }, jedec: { radix: 1024, unit: [ "b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb" ] }};function Ce(e, t = 1, n = "jedec") { e = Math.abs(e); let { radix: r, unit: i } = R[n] || R.jedec, a = 0; for (; e >= r;) e /= r, ++a; return `${e.toFixed(t)} ${i[a]}`;}//#endregion//#region src/upload.tsasync function z(e, t, n, r) { let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity)); if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${Ce(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`); return await Promise.all(await this.upload_files(t, i, n).then(async (n) => { if (n.error) throw Error(n.error); return n.files ? n.files.map((n, r) => { let i = n.split("/").map((e) => encodeURIComponent(e)).join("/"); return new V({ ...e[r], path: n, url: `${t}${this.api_prefix}/file=${i}` }); }) : []; }));}async function B(e, t) { return e.map((e) => new V({ path: e.name, orig_name: e.name, blob: e, size: e.size, mime_type: e.type, is_stream: t }));}var V = class { path; url; orig_name; size; blob; is_stream; mime_type; alt_text; b64; meta = { _type: "gradio.FileData" }; constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) { this.path = e, this.url = t, this.orig_name = n, this.size = r, this.blob = t ? void 0 : i, this.is_stream = a, this.mime_type = o, this.alt_text = s, this.b64 = c; }}, H = class { type; command; meta; fileData; constructor(e, t) { this.type = "command", this.command = e, this.meta = t; }}, we = typeof process < "u" && process.versions && process.versions.node;function Te(e, t, n) { for (; n.length > 1;) { let t = n.shift(); if (typeof t == "string" || typeof t == "number") e = e[t]; else throw Error("Invalid key type"); } let r = n.shift(); if (typeof r == "string" || typeof r == "number") e[r] = t; else throw Error("Invalid key type");}async function U(e, t = void 0, n = [], r = !1, i = void 0) { if (Array.isArray(e)) { let a = []; return await Promise.all(e.map(async (o, s) => { let c = n.slice(); c.push(String(s)); let l = await U(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i); a = a.concat(l); })), a; } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{ path: n, blob: e instanceof Blob ? e : new Blob([e]), type: t }]; else if (typeof e == "object" && e) { let t = []; for (let r of Object.keys(e)) { let a = [...n, r], o = e[r]; t = t.concat(await U(o, void 0, a, !1, i)); } return t; } return [];}function Ee(e, t) { let n = t?.dependencies?.find((t) => t.id == e)?.queue; return n == null ? !t.enable_queue : !n;}function De(e, t) { return new Promise((n, r) => { let i = new MessageChannel(); i.port1.onmessage = (({ data: e }) => { i.port1.close(), n(e); }), window.parent.postMessage(e, t, [i.port2]); });}function Oe(e) { if (typeof e == "string") { if (e.startsWith("http://") || e.startsWith("https://")) return { path: e, url: e, orig_name: e.split("/").pop() ?? "unknown", meta: { _type: "gradio.FileData" } }; if (we) return new H("upload_file", { path: e, name: e, orig_path: e }); } else if (typeof File < "u" && e instanceof File) return e; else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]); else if (e instanceof Blob) return e; throw Error("Invalid input: must be a URL, File, Blob, or Buffer object.");}function W(e, t, n, r, i = !1) { if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input."); if (r === "output" && i) return e; let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs; for (let t = 0; t < s.length; t++) { let r = s[t]; if (n.find((e) => e.id === r)?.type === "state") { if (i) if (e.length === s.length) { let t = e[o]; a.push(t), o++; } else a.push(null); else { o++; continue; } continue; } else { let t = e[o]; a.push(t), o++; } } return a;}var ke = [ "/file=", "/file/", "/stream/", "/proxy="];function Ae(e, t, n, r) { if (!r || typeof e != "object" || !e) return; let i = r, a = new URL(t), o = a.pathname.replace(/\/+$/, ""), s = n ? `/${n.replace(/^\/+|\/+$/g, "")}` : "", c = new Set([`${o}${s}`, s]); s || (c.add(`${o}/gradio_api`), c.add("/gradio_api")); function l(e) { if (typeof e != "object" || !e) return; let t = e; if (t.meta?._type === "gradio.FileData" && typeof t.url == "string") { let e = new URL(t.url, `${a.toString().replace(/\/$/, "")}/`), n = [...c].some((t) => ke.some((n) => e.pathname.startsWith(`${t}${n}`))); (e.protocol === "http:" || e.protocol === "https:") && e.origin === a.origin && n && (e.searchParams.set("__sign", i), t.url = e.toString()); } for (let e of Object.values(t)) l(e); } l(e);}function je(e, t) { for (let n of e.components || []) Ae(n.props?.value, e.root, e.api_prefix || "", t);}//#endregion//#region __vite-browser-externalvar Me = /* @__PURE__ */ o(((e, t) => { t.exports = {};}));//#endregion//#region src/utils/handle_blob.tsasync function Ne(e, t, n) { let r = this; await Pe(r, t); let i = await U(t, void 0, [], !0, n); return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => { if (!n) return { path: t, type: i }; let a = await r.upload_files(e, [n]); return { path: t, file_url: a.files && a.files[0], type: i, name: typeof File < "u" && n instanceof File ? n?.name : void 0 }; }))).forEach(({ path: e, file_url: n, type: r, name: i }) => { r === "Gallery" ? Te(t, n, e) : n && Te(t, new V({ path: n, orig_name: i }), e); }), t;}async function Pe(e, t) { if (!(e.config?.root || e.config?.root_url)) throw Error(fe); await Fe(e, t);}async function Fe(e, t, n = []) { for (let r in t) t[r] instanceof H ? await Ie(e, t, r) : typeof t[r] == "object" && t[r] !== null && await Fe(e, t[r], [...n, r]);}async function Ie(e, t, n) { let r = t[n], i = e.config?.root || e.config?.root_url; if (!i) throw Error(fe); try { let a, o; if (typeof process < "u" && process.versions && process.versions.node) { let e = await Promise.resolve().then(() => /* @__PURE__ */ c(Me(), 1)); o = (await Promise.resolve().then(() => /* @__PURE__ */ c(Me(), 1))).resolve(process.cwd(), r.meta.path), a = await e.readFile(o); } else throw Error(de); let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0]; u && (t[n] = new V({ path: u, orig_name: r.meta.name || "" })); } catch (e) { console.error(pe, e); }}//#endregion//#region src/utils/post_data.tsasync function Le(e, t, n) { let r = { "Content-Type": "application/json" }; this.options.token && (r.Authorization = `Bearer ${this.options.token}`); try { var i = await this.fetch(e, { method: "POST", body: JSON.stringify(t), headers: { ...r, ...n }, credentials: this.options.credentials ?? "same-origin" }); } catch { return [{ error: v }, 500]; } let a, o; try { a = await i.json(), o = i.status; } catch (e) { a = { error: `Could not parse server response: ${e}` }, o = 500; } return [a, o];}//#endregion//#region src/utils/predict.tsasync function Re(e, t = {}) { let n = !1, r = !1; if (!this.config) throw Error("Could not resolve app config"); if (typeof e == "number") this.config.dependencies.find((t) => t.id == e); else { let t = e.replace(/^\//, ""); this.config.dependencies.find((e) => e.id == this.api_map[t]); } let i = this.submit(e, t, null, null, !0), a; for await (let e of i) { if (e.type === "data" && (n = !0, a = e, r)) return a; if (e.type === "status") { if (e.stage === "error") { let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction."); throw Object.assign(r, n), r; } if (e.stage === "complete" && (r = !0, n)) return a; } } return a;}//#endregion//#region src/helpers/spaces.tsasync function G(e, t, n) { let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a; try { if (i = await fetch(r), a = i.status, a !== 200) throw Error(); i = await i.json(); } catch { n({ status: "error", load_status: "error", message: b, detail: "NOT_FOUND" }); return; } if (!i || a !== 200) return; let { runtime: { stage: o }, id: s } = i; switch (o) { case "STOPPED": case "SLEEPING": n({ status: "sleeping", load_status: "pending", message: "Space is asleep. Waking it up...", detail: o }), setTimeout(() => { G(e, t, n); }, 1e3); break; case "PAUSED": n({ status: "paused", load_status: "error", message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", detail: o, discussions_enabled: await Ve(s) }); break; case "RUNNING": case "RUNNING_BUILDING": n({ status: "running", load_status: "complete", message: "Space is running.", detail: o }); break; case "BUILDING": n({ status: "building", load_status: "pending", message: "Space is building...", detail: o }), setTimeout(() => { G(e, t, n); }, 1e3); break; case "APP_STARTING": n({ status: "starting", load_status: "pending", message: "Space is starting...", detail: o }), setTimeout(() => { G(e, t, n); }, 1e3); break; default: n({ status: "space_error", load_status: "error", message: "This space is experiencing an issue.", detail: o, discussions_enabled: await Ve(s) }); break; }}var ze = async (e, t) => { let n = 0; return new Promise((r) => { G(e, N.test(e) ? "space_name" : "subdomain", (i) => { t(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (n < 12 ? (n++, setTimeout(() => { ze(e, t).then(r); }, 5e3)) : r()); }); });}, Be = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;async function Ve(e) { try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message"); return !(!t.ok || n && Be.test(n)); } catch { return !1; }}async function He(e, t) { let n = {}; t && (n.Authorization = `Bearer ${t}`); try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/${h}`, { headers: n }); if (t.status !== 200) throw Error("Space hardware could not be obtained."); let { hardware: r } = await t.json(); return r.current; } catch (e) { throw Error(e.message); }}async function Ue(e, t, n) { let r = {}; n && (r.Authorization = `Bearer ${n}`); let i = { seconds: t }; try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/${g}`, { method: "POST", headers: { "Content-Type": "application/json", ...r }, body: JSON.stringify(i) }); if (t.status !== 200) throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."); return await t.json(); } catch (e) { throw Error(e.message); }}var We = [ "cpu-basic", "cpu-upgrade", "cpu-xl", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a10g-largex2", "a10g-largex4", "a100-large", "zero-a10g", "h100", "h100x8"];//#endregion//#region src/utils/duplicate.tsasync function Ge(e, t) { he(t); let { token: n, private: r, hardware: i, timeout: a, auth: o } = t; if (i && !We.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${We.map((e) => `"${e}"`).join(",")}.`); let { http_protocol: s, host: c } = await F(e, n), l = null; if (o) { let e = await A(s, c, o, fetch, void 0, t.credentials); e && (l = M(e)); } let u = { Authorization: `Bearer ${n}`, "Content-Type": "application/json", ...l ? { Cookie: l.join("; ") } : {} }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` }; r && (p.private = !0); let m; try { i || (m = await He(e, n)); } catch (e) { throw Error(x + e.message); } p.hardware = i || m || "cpu-basic"; try { let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, { method: "POST", headers: u, body: JSON.stringify(p) }); if (r.status === 409) try { return await $.connect(`${d}/${f}`, t); } catch (e) { throw console.error("Failed to connect Client instance:", e), e; } else if (r.status !== 200) throw Error(r.statusText); let i = await r.json(); return await Ue(`${d}/${f}`, a || 300, n), await $.connect(Ke(i.url), t); } catch (e) { throw Error(e); }}function Ke(e) { let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/); if (t) return t[1];}//#endregion//#region src/helpers/zerogpu.tsvar qe = "supports-zerogpu-headers", Je = !1;function Ye() { return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function";}function Xe(e) { return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null;}function Ze() { if (!Ye() || Je) return; window.addEventListener("message", (e) => { e.data === qe && (window.supports_zerogpu_headers = !0); }), Je = !0; let e = Xe(window.location.hostname); e && window.parent !== window && window.parent.postMessage(qe, e);}//#endregion//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/deps/jsr.io/@std/streams/0.221.0/text_line_stream.jsvar Qe = class extends TransformStream { #e = ""; constructor(e = { allowCR: !1 }) { super({ transform: (t, n) => { for (t = this.#e + t;;) { let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1; if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) { n.enqueue(t.slice(0, i)), t = t.slice(i + 1); continue; } if (r === -1) break; let a = t[r - 1] === "\r" ? r - 1 : r; n.enqueue(t.slice(0, a)), t = t.slice(r + 1); } this.#e = t; }, flush: (t) => { if (this.#e === "") return; let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e; t.enqueue(n); } }); }};//#endregion//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.jsfunction $e(e) { let t = new TextDecoderStream(), n = new Qe({ allowCR: !0 }); return e.pipeThrough(t).pipeThrough(n);}function et(e) { let t = /[:]\s*/.exec(e), n = t && t.index; if (n) return [e.substring(0, n), e.substring(n + t[0].length)];}function tt(e, t, n) { e.get(t) || e.set(t, n);}//#endregion//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.jsasync function* nt(e, t) { if (!e.body) return; let n = $e(e.body), r, i = n.getReader(), a; for (;;) { if (t && t.aborted) return i.cancel(); if (r = await i.read(), r.done) return; if (!r.value) { a && (yield a), a = void 0; continue; } let [e, n] = et(r.value) || []; e === "data" ? (a ||= {}, a[e] = a[e] ? a[e] + "\n" + n : n) : e === "event" ? (a ||= {}, a[e] = n) : e === "id" ? (a ||= {}, a[e] = String(+n) === n ? +n : n) : e === "retry" && (a ||= {}, a[e] = +n || void 0); }}async function rt(e, t) { let n = new Request(e, t); tt(n.headers, "Accept", "text/event-stream"), tt(n.headers, "Content-Type", "application/json"); let r = await fetch(n); if (!r.ok) throw r; return nt(r, n.signal);}//#endregion//#region src/utils/stream.tsasync function it() { let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this; if (!i) throw Error("Could not resolve app config"); r.open = !0; let s = null, c = new URLSearchParams({ session_hash: this.session_hash }).toString(), l = new URL(`${i.root}${this.api_prefix}/${u}?${c}`); if (a && l.searchParams.set("__sign", a), s = this.stream(l), !s) { console.warn("Cannot connect to SSE endpoint: " + l.toString()); return; } s.onmessage = async function(a) { let s = JSON.parse(a.data); if (s.msg === "close_stream") { at(r, o.abort_controller); return; } let c = s.event_id; if (!c) await Promise.all(Object.keys(e).map((t) => e[t](s))); else if (e[c] && i) { s.msg === "process_completed" && [ "sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3" ].includes(i.protocol) && t.delete(c); let n = e[c]; typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, s) : n(s); } else n[c] || (n[c] = []), n[c].push(s); }, s.onerror = async function(t) { console.error(t), await Promise.all(Object.keys(e).map((t) => e[t]({ msg: "broken_connection", message: v }))); };}function at(e, t) { e && (e.open = !1, t?.abort());}function ot(e, t, n) { e[t] ? n.data.forEach((r, i) => { let a = st(i < e[t].length ? e[t][i] : null, r); e[t][i] = a, n.data[i] = a; }) : (e[t] = [], n.data.forEach((n, r) => { e[t][r] = n; }));}function st(e, t) { return t.forEach(([t, n, r]) => { e = ct(e, n, t, r); }), e;}function ct(e, t, n, r) { if (t.length === 0) { if (n === "replace") return r; if (n === "append") return e + r; throw Error(`Unsupported action: ${n}`); } let i = e; for (let e = 0; e < t.length - 1; e++) i = i[t[e]]; let a = t[t.length - 1]; switch (n) { case "replace": i[a] = r; break; case "append": i[a] += r; break; case "add": Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r; break; case "delete": Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a]; break; default: throw Error(`Unknown action: ${n}`); } return e;}function lt(e, t = {}) { let n = { close: () => { console.warn("Method not implemented."); }, onerror: null, onmessage: null, onopen: null, readyState: 0, url: e.toString(), withCredentials: !1, CONNECTING: 0, OPEN: 1, CLOSED: 2, addEventListener: () => { throw Error("Method not implemented."); }, dispatchEvent: () => { throw Error("Method not implemented."); }, removeEventListener: () => { throw Error("Method not implemented."); } }; return rt(e, t).then(async (e) => { n.readyState = n.OPEN; try { for await (let t of e) n.onmessage && n.onmessage(t); n.readyState = n.CLOSED; } catch (e) { n.onerror && n.onerror(e), n.readyState = n.CLOSED; } }).catch((e) => { console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED; }), n;}//#endregion//#region src/utils/run_history.tsvar K = "gradio:run-history:", q = `${K}v2:`, ut = `${K}replay:v2:`, dt = `${K}destination:v1:`, ft = 100, pt = 8;function J(e, t) { try { return e(); } catch (e) { return console.warn("Could not update the run history.", e), t; }}function mt(e, t = "/gradio_api") { return `${e.replace(/\/+$/, "")}${t}/runs`;}function Y(e) { if (typeof window > "u") return null; let t = e?.app_id; if (t == null || t === "") return null; try { return window.localStorage ? `${q}${t}${e?.username ? `:user:${encodeURIComponent(e.username)}` : ""}` : null; } catch { return null; }}function ht(e) { let t = Y(e); return t ? t.replace(q, ut) : null;}function gt(e) { let t = Y(e); return t ? t.replace(q, dt) : null;}function _t(e) { let t = gt(e); if (!t) return { type: "browser" }; try { let e = JSON.parse(window.localStorage.getItem(t) || "null"); return typeof e?.bucket_id == "string" ? e.type === "bucket" ? { type: "bucket", bucket_id: e.bucket_id } : { type: "browser", bucket_id: e.bucket_id } : { type: "browser" }; } catch { return { type: "browser" }; }}function vt(e, t) { let n = gt(e); n && (t.type === "browser" && !t.bucket_id ? window.localStorage.removeItem(n) : window.localStorage.setItem(n, JSON.stringify(t)), Et());}function yt(e) { try { let t = JSON.parse(window.localStorage.getItem(e) || "[]"); return Array.isArray(t) && t.length && Date.parse(t[0]?.started_at) || 0; } catch { return 0; }}function bt(e) { let t = Object.keys(window.localStorage).filter((e) => e.startsWith(K)), n = [...t.filter((e) => !e.startsWith(q) && !e.startsWith(ut) && !e.startsWith(dt)), ...t.filter((t) => t.startsWith(q) && t !== e).sort((e, t) => yt(t) - yt(e)).slice(pt - 1)]; for (let e of n) try { window.localStorage.removeItem(e), window.sessionStorage.removeItem(e.replace(q, ut)); } catch {}}function xt() { return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;}function X(e) { let t = /* @__PURE__ */ new WeakSet(); try { return JSON.parse(JSON.stringify(e, (e, n) => { if (typeof n == "bigint") return n.toString(); if (typeof n == "object" && n) { if (t.has(n)) return "[Circular]"; t.add(n); } return n; })); } catch { return "[Unserializable value]"; }}function Z(e) { let t = Y(e); if (!t) return []; try { let e = JSON.parse(window.localStorage.getItem(t) || "[]"); return Array.isArray(e) ? e : []; } catch { return []; }}function St(e, t) { let n = Y(e); if (!n) return; let r = t.slice(0, ft), i = !1; for (; r.length > 0;) try { window.localStorage.setItem(n, JSON.stringify(r)); return; } catch { if (!i) { i = !0, bt(n); continue; } r = r.slice(0, -1); } try { window.localStorage.removeItem(n); } catch {}}function Ct(e) { let t = Y(e); if (t) { try { window.localStorage.removeItem(t); } catch {} Et(); }}function wt(e, t) { St(e, Z(e).filter((e) => e.id !== t)), Et();}var Tt = "gradio:run-history-change";function Et() { if (!(typeof window > "u")) try { window.dispatchEvent(new Event(Tt)); } catch {}}function Dt(e) { return typeof window > "u" ? () => {} : (window.addEventListener(Tt, e), window.addEventListener("storage", e), () => { window.removeEventListener(Tt, e), window.removeEventListener("storage", e); });}function Ot(e, t) { let n = ht(e); if (n) try { window.sessionStorage.setItem(n, JSON.stringify(t)); } catch {}}function kt(e) { let t = ht(e); if (!t) return null; try { let e = window.sessionStorage.getItem(t); return window.sessionStorage.removeItem(t), e ? JSON.parse(e) : null; } catch { return null; }}function At(e, t) { let n = e.dependencies.find((e) => e.id === t.fn_index || typeof e.api_name == "string" && `/${e.api_name.replace(/^\//, "")}` === t.api_name); if (!n) return !1; let r = Array.isArray(t.inputs) ? t.inputs : Object.values(t.inputs ?? {}), i = Array.isArray(t.outputs) ? t.outputs : t.outputs === null || t.outputs === void 0 ? [] : [t.outputs], a = (t, n) => { for (let [r, i] of t.entries()) { let t = e.components.find((e) => e.id === i); !t || r >= n.length || t.type !== "state" && (t.props.value = n[r]); } }; return a(n.inputs, r), a(n.outputs, i), !0;}function jt(e) { let t = kt(e); return t ? At(e, t) : !1;}function Mt(e) { if (_t(e).type === "bucket") return null; let t = Y(e); if (!t) return null; bt(t); let n = { id: xt(), endpoint: e.endpoint, api_name: e.api_name, fn_index: e.fn_index, page: `${window.location.pathname}${window.location.search}`, inputs: X(e.inputs), outputs: null, ...e.input_components ? { input_components: X(e.input_components) } : {}, ...e.output_components ? { output_components: X(e.output_components) } : {}, status: "running", started_at: (/* @__PURE__ */ new Date()).toISOString() }; return St(e, [n, ...Z(e)]), Et(), n.id;}function Nt(e, t, n) { if (!t) return; let r = Z(e), i = r.find((e) => e.id === t); i && (i.inputs = X(n), St(e, r));}function Pt(e, t, n) { if (!t) return; let r = Z(e), i = r.find((e) => e.id === t); if (!i) return; let a = !1; if (n.type === "data") i.outputs = X(n.data), Q.set(t, i.outputs); else if (n.type === "status" && n.original_msg === "process_starts") Lt(i, n.time); else if (n.type === "status" && (n.stage === "generating" || n.stage === "streaming")) i.streamed = !0; else if (n.type === "status" && n.stage === "complete") i.status = "completed", Rt(i, n), a = !0; else if (n.type === "status" && n.stage === "error") i.status = "failed", i.error = typeof n.message == "string" ? n.message : JSON.stringify(n.message || "Unknown error"), Rt(i, n), a = !0; else return; if (a) Q.has(t) && (i.outputs = Q.get(t)), Q.delete(t), It.delete(t); else if (i.streamed) { if (Date.now() - (It.get(t) ?? 0) < Ft) return; It.set(t, Date.now()), Q.delete(t); } St(e, r);}var Ft = 500, It = /* @__PURE__ */ new Map(), Q = /* @__PURE__ */ new Map();function Lt(e, t) { if (e.process_started_at) return; let n = t || /* @__PURE__ */ new Date(); e.process_started_at = n.toISOString(), e.queued_ms = Math.max(0, n.getTime() - Date.parse(e.started_at));}function Rt(e, t) { let n = t.time || /* @__PURE__ */ new Date(); e.completed_at = n.toISOString(), e.duration_ms = (!e.streamed && typeof t.cache_duration == "number" && t.cache_duration >= 0 ? t.cache_duration * 1e3 : null) ?? Math.max(0, n.getTime() - Date.parse(e.process_started_at || e.started_at));}function zt(e) { return J(() => Z(e), []);}function Bt(e) { return J(() => _t(e), { type: "browser" });}function Vt(e, t) { J(() => vt(e, t), void 0);}function Ht(e) { J(() => Ct(e), void 0);}function Ut(e, t) { J(() => wt(e, t), void 0);}function Wt(e, t) { J(() => Ot(e, t), void 0);}function Gt(e) { return J(() => kt(e), null);}function Kt(e) { return J(() => jt(e), !1);}function qt(e) { return J(() => Mt(e), null);}function Jt(e, t, n) { J(() => Nt(e, t, n), void 0);}function Yt(e, t, n) { J(() => Pt(e, t, n), void 0);}function Xt(e) { return J(() => Dt(() => J(e, void 0)), () => {});}//#endregion//#region src/utils/submit.tsfunction Zt(e, t = {}, n, r, i, a) { try { let { token: o } = this.options, { fetch: s, app_reference: c, config: l, session_hash: f, api_info: p, api_map: m, stream_status: ee, pending_stream_messages: h, pending_diff_streams: g, event_callbacks: _, unclosed_events: te, post_data: ie, options: y, api_prefix: b } = this, oe = a || { "x-gradio-user": "api" }, x = this; if (!p) throw Error(le); if (!l) throw Error("Could not resolve app config"); let se = l.root, { fn_index: S, endpoint_info: C, dependency: w } = $t(p, e, m, l), ce = be(t, C), T = l.protocol ?? "ws"; if (T === "ws") throw Error(ue); let de = typeof w.api_name == "string" ? `/${w.api_name}` : e, fe = typeof w.api_name == "string" ? `/${w.api_name}` : `Function ${S}`, pe = (e) => { let t = l.components.find((t) => t.id === e); return t ? { type: t.type, component_class_id: t.component_class_id, props: t.props } : null; }, me = w.api_visibility === "public", he = l.run_history !== !1 && this.options.record_history !== !1, E = { app_id: l.app_id, username: l.username }, ge = Bt(E), D = { ...oe, ...he && ge.type === "bucket" ? { "x-gradio-history-bucket": ge.bucket_id } : {} }, O = !he || !me ? null : qt({ ...E, endpoint: de, api_name: fe, fn_index: S, inputs: W(ce, w, l.components, "input", !0), input_components: w.inputs.map(pe), output_components: w.outputs.map(pe) }), k, A = "", j = typeof e == "number" ? "/predict" : e, M, N = null, P = !1, F = {}, I = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", _e = y?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {}; function L(e) { Yt(E, O, e), (e.type === "data" || e.type === "render") && Ae(e.data, se, b, x.jwt), (i || _e[e.type]) && Te(e); } async function ve() { let e = {}, t = {}; e = { event_id: N }, t = { event_id: N, session_hash: f, fn_index: S }; try { if (!l) throw Error("Could not resolve app config"); "event_id" in t && await s(`${l.root}${b}/${re}`, { headers: { "Content-Type": "application/json" }, method: "POST", body: JSON.stringify(t) }), await s(`${l.root}${b}/${ne}`, { headers: { "Content-Type": "application/json" }, method: "POST", body: JSON.stringify(e) }); } catch { console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."); } } let xe = async (e) => { await this._resolve_heartbeat(e); }; async function Se(e) { if (!l) return; let t = e.render_id; l.components = [...l.components.filter((e) => e.props.rendered_in !== t), ...e.components], l.dependencies = [...l.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies]; let n = l.components.some((e) => e.type === "state"), r = l.dependencies.some((e) => e.targets.some((e) => e[1] === "unload")); l.connect_heartbeat = n || r, await xe(l), L({ type: "render", data: e, endpoint: j, fn_index: S }); } let R = this.handle_blob(l.root, ce, C).then(async (e) => { let t = W(e, w, l.components, "input", !0); if (Jt(E, O, t || []), M = { data: t || [], event_data: n, fn_index: S, trigger_id: r, ...y.oauth_token && C?.oauth_token ? { oauth_token: y.oauth_token } : {} }, Ee(S, l)) L({ type: "status", endpoint: j, stage: "pending", queue: !1, fn_index: S, time: /* @__PURE__ */ new Date() }), ie(`${l.root}${b}/run${j.startsWith("/") ? j : `/${j}`}${I ? "?" + I : ""}`, { ...M, session_hash: f }, D).then(async ([e, t]) => { let i = e.data; if (t == 200) L({ type: "data", endpoint: j, fn_index: S, data: W(i, w, l.components, "output", y.with_null_state), time: /* @__PURE__ */ new Date(), event_data: n, trigger_id: r }), e.render_config && await Se(e.render_config), L({ type: "status", endpoint: j, fn_index: S, stage: "complete", eta: e.average_duration, queue: !1, time: /* @__PURE__ */ new Date() }); else { let t = e?.error === v; L({ type: "status", stage: "error", endpoint: j, fn_index: S, message: e.error, broken: t, queue: !1, time: /* @__PURE__ */ new Date() }); } }).catch((e) => { L({ type: "status", stage: "error", message: e.message, endpoint: j, fn_index: S, queue: !1, time: /* @__PURE__ */ new Date() }); }); else if (T == "sse") { L({ type: "status", stage: "pending", queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date() }); var i = new URLSearchParams({ fn_index: S.toString(), session_hash: f }).toString(); let e = new URL(`${l.root}${b}/${u}?${I ? I + "&" : ""}${i}`); if (this.jwt && e.searchParams.set("__sign", this.jwt), k = this.stream(e), !k) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString())); k.onmessage = async function(e) { let { type: t, status: i, data: a } = ye(JSON.parse(e.data), F[S]); if (t === "update" && i && !P) L({ type: "status", endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date(), ...i }), i.stage === "error" && (k?.close(), V()); else if (t === "data") { let [e, t] = await ie(`${l.root}${b}/queue/data`, { ...M, session_hash: f, event_id: N }, D); t !== 200 && (L({ type: "status", stage: "error", message: v, queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date() }), k?.close(), V()); } else t === "complete" ? P = i : t === "log" ? L({ type: "log", title: a.title, log: a.log, level: a.level, endpoint: j, duration: a.duration, visible: a.visible, fn_index: S }) : (t === "generating" || t === "streaming") && L({ type: "status", time: /* @__PURE__ */ new Date(), ...i, stage: i?.stage, queue: !0, endpoint: j, fn_index: S }); a && (L({ type: "data", time: /* @__PURE__ */ new Date(), data: W(a.data, w, l.components, "output", y.with_null_state), endpoint: j, fn_index: S, event_data: n, trigger_id: r }), P && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...P, stage: i?.stage, queue: !0, endpoint: j, fn_index: S }), k?.close(), V())); }; } else if (T == "sse_v1" || T == "sse_v2" || T == "sse_v2.1" || T == "sse_v3") { L({ type: "status", stage: "pending", queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date() }); let e = ""; typeof window < "u" && typeof document < "u" && (e = window?.location?.hostname); let t = Xe(e); return (typeof window < "u" && typeof document < "u" && window.parent != window && t && window.supports_zerogpu_headers ? De("zerogpu-headers", t) : Promise.resolve(null)).then((e) => { let t = { ...D, ...e || {} }; return ie(`${l.root}${b}/${d}?${I}`, { ...M, session_hash: f }, t); }).then(async ([e, t]) => { if (e.event_id && (A = e.event_id), t === 503) L({ type: "status", stage: "error", message: ae, queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date(), visible: !0 }), V(); else if (t === 422) L({ type: "status", stage: "error", message: e.detail, queue: !0, endpoint: j, fn_index: S, code: "validation_error", time: /* @__PURE__ */ new Date(), visible: !0 }), V(); else if (t !== 200) { let t = e?.error === v; L({ type: "status", stage: "error", broken: t, message: t ? v : e.detail || e.error, queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date(), visible: !0 }), V(); } else { N = e.event_id, A = N; let t = async function(e) { try { let { type: t, status: n, data: r, original_msg: i } = ye(e, F[S]); if (t == "heartbeat") return; if (t === "update" && n && !P) L({ type: "status", endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date(), original_msg: i, ...n }); else if (t === "complete") P = n; else if (t == "unexpected_error" || t == "broken_connection") { console.error("Unexpected error", n?.message); let e = t === "broken_connection"; L({ type: "status", stage: "error", message: n?.message || "An Unexpected Error Occurred!", queue: !0, endpoint: j, broken: e, session_not_found: n?.session_not_found, fn_index: S, time: /* @__PURE__ */ new Date() }); } else if (t === "log") { L({ type: "log", title: r.title, log: r.log, level: r.level, endpoint: j, duration: r.duration, visible: r.visible, fn_index: S }); return; } else (t === "generating" || t === "streaming") && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...n, stage: n?.stage, queue: !0, endpoint: j, fn_index: S }), r && w.connection !== "stream" && [ "sse_v2", "sse_v2.1", "sse_v3" ].includes(T) && ot(g, N, r)); r && (L({ type: "data", time: /* @__PURE__ */ new Date(), data: W(r.data, w, l.components, "output", y.with_null_state), endpoint: j, fn_index: S }), r.render_config && await Se(r.render_config), P && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...P, stage: n?.stage, queue: !0, endpoint: j, fn_index: S }), V())), (n?.stage === "complete" || n?.stage === "error") && (_[N] && delete _[N], N in g && delete g[N], V()); } catch (e) { console.error("Unexpected client exception", e), L({ type: "status", stage: "error", message: "An Unexpected Error Occurred!", queue: !0, endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date() }), [ "sse_v2", "sse_v2.1", "sse_v3" ].includes(T) && (at(ee, x.abort_controller), ee.open = !1, V()); } }; N in h && (h[N].forEach((e) => t(e)), delete h[N]), _[N] = t, te.add(N), ee.open || await this.open_stream(); } }); } }); R.catch((e) => { L({ type: "status", stage: "error", message: e instanceof Error ? e.message : String(e), queue: !Ee(S, l), endpoint: j, fn_index: S, time: /* @__PURE__ */ new Date() }), V(); }); let Ce = !1, z = [], B = []; function V() { for (Ce = !0; B.length > 0;) B.shift()({ value: void 0, done: !0 }); } function H(e) { B.length > 0 ? B.shift()(e) : z.push(e); } function we(e) { H(Qt(e)), V(); } function Te(e) { H({ value: e, done: !1 }); } function U() { return z.length > 0 ? Promise.resolve(z.shift()) : Ce ? Promise.resolve({ value: void 0, done: !0 }) : new Promise((e) => B.push(e)); } let Oe = (e, t) => { R.then(() => { A && this.post_data(`${l.root}${b}/stream/${A}${e}`, t); }, () => {}); }, ke = { [Symbol.asyncIterator]: () => ke, next: U, throw: async (e) => (we(e), U()), return: async () => (V(), { value: void 0, done: !0 }), cancel: ve, send_chunk: (e) => { Oe("", { ...e, session_hash: this.session_hash }); }, close_stream: () => { V(), Oe("/close", {}); }, event_id: () => A, wait_for_id: async () => (await R, N) }; return ke; } catch (e) { throw console.error("Submit function encountered an error:", e), e; }}function Qt(e) { return { then: (t, n) => n(e) };}function $t(e, t, n, r) { let i, a, o; if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t); else { let s = t.replace(/^\//, ""); i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]); } if (typeof i != "number" || !o) { let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", "); throw Error(`No endpoint matching ${JSON.stringify(t)} was found. ` + (e ? `Valid named endpoints are: ${e}. ` : "This app exposes no named endpoints. ") + "An fn_index (number) of an existing dependency can also be used."); } return { fn_index: i, endpoint_info: a, dependency: o };}//#endregion//#region src/client.tsvar $ = class { app_reference; options; deep_link = null; page = null; config; api_prefix = ""; api_info; api_map = {}; session_hash = Math.random().toString(36).substring(2); jwt = !1; last_status = {}; cookies = null; stream_status = { open: !1 }; closed = !1; pending_stream_messages = {}; pending_diff_streams = {}; event_callbacks = {}; unclosed_events = /* @__PURE__ */ new Set(); heartbeat_event = null; abort_controller = null; stream_instance = null; current_payload; get_url_config(e = null) { if (!this.config) throw Error(y); e === null && (e = window.location.href); let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i; return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i); } get_page_config(e) { if (!this.config) throw Error(y); let t = this.config; return e in t.page || (e = ""), { ...t, current_page: e, layout: t.page[e].layout, components: t.components.filter((n) => t.page[e].components.includes(n.id)), dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id)) }; } fetch(e, t) { let n = new Headers(t?.headers || {}); return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { n.append(t, e); }), fetch(e, { ...t, headers: n }); } stream(e) { let t = new Headers(); return this && this.cookies && t.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, n) => { t.append(n, e); }), this && this.options.token && t.append("Authorization", `Bearer ${this.options.token}`), this.abort_controller = new AbortController(), this.stream_instance = lt(e.toString(), { credentials: this.options.credentials ?? "same-origin", headers: t, signal: this.abort_controller.signal }), this.stream_instance; } view_api; upload_files; upload; handle_blob; post_data; submit; predict; open_stream; resolve_config; resolve_cookies; constructor(e, t = { events: ["data"] }) { this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, this.page = t.query_params?.page ?? null, t.events ||= ["data"], he(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = xe.bind(this), this.upload_files = Se.bind(this), this.handle_blob = Ne.bind(this), this.post_data = Le.bind(this), this.submit = Zt.bind(this), this.predict = Re.bind(this), this.open_stream = it.bind(this), this.resolve_config = D.bind(this), this.resolve_cookies = k.bind(this), this.upload = z.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this); } async init() { Ze(), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then((e) => e?.config && this._resolve_heartbeat(e.config)); try { this.api_info = await this.view_api(); } catch (e) { console.error(e.message); } this.api_map = E(this.config?.dependencies || []); } async _resolve_heartbeat(e) { if (this.config = e, this.api_prefix = e.api_prefix || "", e.space_id && this.options.token && (this.jwt = await me(e.space_id, this.options.token, this.cookies)), je(this.config, this.jwt), this.config && this.config.connect_heartbeat) { let e = new URL(`${this.config.root}${this.api_prefix}/${_}/${this.session_hash}`); this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_event ||= this.stream(e); } } static async connect(e, t = { events: ["data"] }) { let n = new this(e, t); return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n; } async reconnect() { let e = new URL(`${this.config.root}${this.api_prefix}/${ie}`), t; try { let n = await this.fetch(e); if (!n.ok) throw Error(); t = (await n.json()).app_id; } catch { return "broken"; } return t === this.config.app_id ? "connected" : "changed"; } close() { this.closed = !0, at(this.stream_status, this.abort_controller); } async refresh() { if (!this.config) throw Error(y); let e = await this.resolve_config(this.config.root, !1); if (!e) throw Error(y); this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = E(e.dependencies || []), je(this.config, this.jwt); try { this.api_info = await this.view_api(); } catch (e) { console.error(oe + e.message); } return this.get_url_config(); } set_current_payload(e) { this.current_payload = e; } static async duplicate(e, t = { events: ["data"] }) { return Ge(e, t); } async _resolve_config() { let { http_protocol: e, host: t, space_id: n } = await F(this.app_reference, this.options.token), { status_callback: r } = this.options; n && r && await ze(n, r); let i; try { let n = `${e}//${t}`; if (i = await this.resolve_config(n), !i) throw Error(y); return this.config_success(i); } catch (e) { if (n && r) G(n, N.test(n) ? "space_name" : "subdomain", this.handle_space_success); else throw r && r({ status: "error", message: "Could not load this space.", load_status: "error", detail: "NOT_FOUND" }), e instanceof Error ? e : Error(String(e)); } } async config_success(e) { if (this.config = e, this.api_prefix = e.api_prefix || "", e.run_history === !1 && Ht({ app_id: e.app_id, username: e.username }), this.config.auth_required) return this.prepare_return_obj(); try { this.api_info = await this.view_api(); } catch (e) { console.error(oe + e.message); } return this.prepare_return_obj(); } async handle_space_success(e) { if (!this) throw Error(y); let { status_callback: t } = this.options; if (t && t(e), e.status === "running") try { if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(y); return await this.config_success(this.config); } catch (e) { throw t && t({ status: "error", message: "Could not load this space.", load_status: "error", detail: "NOT_FOUND" }), e; } } async component_server(e, t, n) { if (!this.config) throw Error(y); let r = {}, { token: i } = this.options, { session_hash: a } = this; i && (r.Authorization = `Bearer ${this.options.token}`); let o, s = this.config.components.find((t) => t.id === e); o = s?.props?.root_url ? s.props.root_url : this.config.root; let c; if (typeof n == "object" && n && "binary" in n) { let r = n; c = new FormData(); for (let e in r.data) e !== "binary" && c.append(e, r.data[e]); c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a); } else c = JSON.stringify({ data: n, component_id: e, fn_name: t, session_hash: a }), r["Content-Type"] = "application/json"; i && (r.Authorization = `Bearer ${i}`); try { let e = await this.fetch(`${o}${this.api_prefix}/${te}/`, { method: "POST", body: c, headers: r, credentials: this.options.credentials ?? "same-origin" }); if (!e.ok) throw Error("Could not connect to component server: " + e.statusText); let t = await e.json(); return Ae(t, this.config.root, this.config.api_prefix || "", this.jwt), t; } catch (e) { console.warn(e); } } set_cookies(e) { this.cookies = M(e).join("; "); } prepare_return_obj() { return { config: this.config, predict: this.predict, submit: this.submit, view_api: this.view_api, component_server: this.component_server }; }};async function en(e, t = { events: ["data"] }) { return await $.connect(e, t);}async function tn(e, t) { return await $.duplicate(e, t);}//#endregion//#region src/utils/bucket_sync.tsvar nn = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-][a-zA-Z0-9_./-]*$/;function rn(e) { return nn.test(e) ? !e.split("/").some((e) => e === "" || e === "." || e === "..") : !1;}function an(e, t, n) { let r = n ? `?${new URLSearchParams(n)}` : "", i = e.replace(/\/+$/, ""); return i ? `${i}/gradio_api/run-history/${t}${r}` : typeof document < "u" && document.baseURI ? new URL(`gradio_api/run-history/${t}${r}`, document.baseURI).toString() : `gradio_api/run-history/${t}${r}`;}async function on(e) { try { let t = await e.json(); return typeof t?.detail == "string" ? t.detail : `${e.status}`; } catch { return `${e.status}`; }}async function sn(e, t, n, r) { try { let i = await fetch(e, { credentials: "include", ...t }); return i.ok ? { ok: !0, status: i.status, data: r(await i.json()) } : { ok: !1, status: i.status, data: n, detail: await on(i) }; } catch (e) { return { ok: !1, status: 0, data: n, detail: String(e) }; }}async function cn(e, t) { return rn(t) ? sn(an(e, "connect"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bucket_id: t }) }, null, () => null) : { ok: !1, status: 422, data: null, detail: "invalid bucket id" };}async function ln(e) { return sn(an(e, "buckets"), {}, [], (e) => Array.isArray(e?.buckets) ? e.buckets : []);}async function un(e, t) { return sn(an(e, "records", { bucket: t }), {}, [], (e) => Array.isArray(e?.records) ? e.records : []);}function dn(e, t, n, r, i) { return an(e, `records/${encodeURIComponent(n)}/${encodeURIComponent(r)}/assets/${encodeURIComponent(i)}`, { bucket: t });}//#endregionexport { $ as Client, V as FileData, w as MISSING_CREDENTIALS_MSG, Kt as apply_run_history_replay, dn as asset_url, Ht as clear_run_history, en as client, cn as connect_bucket, Gt as consume_run_history_replay, Ut as delete_run_history, tn as duplicate, Oe as handle_file, rn as is_valid_bucket_id, un as list_bucket_records, ln as list_user_buckets, Xt as on_run_history_change, Re as predict, B as prepare_files, zt as read_run_history, Bt as read_run_history_storage, mt as run_history_url, Vt as set_run_history_storage, Wt as stage_run_history_replay, Zt as submit, z as upload, Se as upload_files };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "name": "@gradio/client", "version": "2.7.1", "description": "Gradio API client", "type": "module", "main": "dist/index.cjs", "module": "dist/index.js", "types": "dist/index.d.ts", "author": "", "license": "ISC", "exports": { ".": { "gradio": "./src/index.ts", "types": "./dist/index.d.ts", "browser": "./dist/browser.js", "import": "./dist/index.js", "require": "./dist/index.cjs", "default": "./dist/index.js" }, "./package.json": "./package.json", "./browser.js": "./dist/browser.js", "./dist/index.min.js": "./dist/index.min.js" }, "dependencies": { "fetch-event-stream": "^0.1.5" }, "devDependencies": { "msw": "^2.11.3", "typescript": "^5.9.3" }, "engines": { "node": ">=18.0.0" }, "main_changeset": true, "repository": { "type": "git", "url": "git+https://github.com/gradio-app/gradio.git", "directory": "client/js" }, "scripts": { "bundle": "vite build --ssr", "bundle:browser": "BROWSER_BUILD=true vite build", "bundle:cdn": "BROWSER_BUILD=true CDN_BUILD=true vite build", "generate_types": "tsc", "clean": "rm -rf dist", "build": "pnpm clean && pnpm bundle && pnpm bundle:browser && pnpm bundle:cdn && pnpm generate_types && pnpm verify_dist", "verify_dist": "node scripts/verify_dist.mjs", "test": "pnpm test:browser && pnpm test:node", "test:browser": "vitest run -c vite.config.ts", "test:node": "NODE_NO_WARNINGS=1 TEST_MODE=node vitest run -c vite.config.ts", "preview:browser": "vite dev --mode=preview" }}69 unmodified lines707172737475763 unmodified lines8081828384858619 unmodified lines1061071081091101118 unmodified lines12012112212312412512669 unmodified lineselif type(start['Type']) is not int: raise ValueError('StartTileConnection.Type must be an integer')return valuedef run_native(track_bytes,network_bytes,*,binary=None,importer=None,scene_template=None,with_report=False):started=time.perf_counter()track=track_input(track_bytes); template=network_input(network_bytes)# Deployment paths are supplied by trusted application configuration, never uploads.3 unmodified linesif not all(p.is_file() for p in (binary,importer,scene_template)):raise RuntimeError('Native tools or scene template unavailable')# No inherited provider tokens, credential paths, or caller-chosen commands.env={'PATH':'/usr/bin:/bin','LANG':'C','RUST_BACKTRACE':'0'}with tempfile.TemporaryDirectory(prefix='tiga-native-') as directory:work=Path(directory)env.update(HOME=directory,TMPDIR=directory)19 unmodified lines'--population','4','--generations','1','--ticks','60','--seed','42','--batch-count','2','--out-dir',str(out),'--mutation-start','.01','--mutation-end','.01','--schedule','linear','--save-final-candidate']subprocess.run(command,cwd=work,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=25,check=True)candidate=out/'candidate.json'if candidate.stat().st_size>1024*1024: raise ValueError('Output too large')8 unmodified lines'best_score':last.get('best_score'),'mean_score':last.get('mean_score'),'best_lap_seconds':last.get('best_lap_s'),'lapped_cars':last.get('lapped_cars'),'simulated_ticks':last.get('simulated_ticks'),'requested_ticks':60,'candidate_validated':True}# The context has removed input/intermediate files before result publication.return (result,report) if with_report else result69 unmodified lines7071727374757677787980818283848586873 unmodified lines9192939495969719 unmodified lines1171181191201211221238 unmodified lines13213313413513613713869 unmodified lineselif type(start['Type']) is not int: raise ValueError('StartTileConnection.Type must be an integer')return valuedef native_environment(gpu_library=None):env={'PATH':'/usr/bin:/bin','LANG':'C','RUST_BACKTRACE':'0'}if gpu_library is not None:library=Path(gpu_library).resolve()if not library.is_file(): raise RuntimeError('CUDA library unavailable')# Device/loader plumbing from an active lease, never provider credentials.for key in ('LD_LIBRARY_PATH','LD_PRELOAD','CUDA_VISIBLE_DEVICES','NVIDIA_VISIBLE_DEVICES'):if key in os.environ: env[key]=os.environ[key]env['ALTD_GPU_LIB']=str(library)return envdef run_native(track_bytes,network_bytes,*,binary=None,importer=None,scene_template=None,with_report=False,gpu_library=None):started=time.perf_counter()track=track_input(track_bytes); template=network_input(network_bytes)# Deployment paths are supplied by trusted application configuration, never uploads.3 unmodified linesif not all(p.is_file() for p in (binary,importer,scene_template)):raise RuntimeError('Native tools or scene template unavailable')# No inherited provider tokens, credential paths, or caller-chosen commands.env=native_environment(gpu_library)with tempfile.TemporaryDirectory(prefix='tiga-native-') as directory:work=Path(directory)env.update(HOME=directory,TMPDIR=directory)19 unmodified lines'--population','4','--generations','1','--ticks','60','--seed','42','--batch-count','2','--out-dir',str(out),'--mutation-start','.01','--mutation-end','.01','--schedule','linear','--save-final-candidate']if gpu_library is not None: command.append('--gpu')subprocess.run(command,cwd=work,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=25,check=True)candidate=out/'candidate.json'if candidate.stat().st_size>1024*1024: raise ValueError('Output too large')8 unmodified lines'best_score':last.get('best_score'),'mean_score':last.get('mean_score'),'best_lap_seconds':last.get('best_lap_s'),'lapped_cars':last.get('lapped_cars'),'simulated_ticks':last.get('simulated_ticks'),'requested_ticks':60,'candidate_validated':True,'execution_backend':'cuda' if gpu_library is not None else 'cpu'}# The context has removed input/intermediate files before result publication.return (result,report) if with_report else result
DATA_POLICY.md+11-3
README.md+2-2
RELEASE_MANIFEST.json+13-7
app.py+98-24
app_release.pyAdded+33
client.js+15-1
gpu_tickets.pyAdded+39
requirements.txt+1
vendor/gradio-client/LICENSEAdded+201
vendor/gradio-client/dist/index.min.jsAdded+2115
vendor/gradio-client/package.jsonAdded+53
worker.py+15-3