diff --git a/.gitattributes b/.gitattributes index 0addc7f7dfef7de7b400d21a5697fb40c56b3f29..d911685c4e8bb8f8146463bb178f0139d482d144 100644 --- a/.gitattributes +++ b/.gitattributes @@ -278,3 +278,4 @@ evalkit_tf437/lib/python3.10/site-packages/yarl/_quoting_c.cpython-310-x86_64-li evalkit_tf437/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text evalkit_tf437/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text evalkit_tf437/lib/python3.10/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Index.DMrntMgy.js.br filter=lfs diff=lfs merge=lfs -text +evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so b/evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..415217dc0c03f1dc3686caa0b8e5d581fccd3323 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b924e5a01637def5d586a728eaa6d935f185c4f146499cfe7dfec308f1334ec +size 149184 diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3db2cb2cf9205006733541e5353032844ebea9e6 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/package.json @@ -0,0 +1,34 @@ +{ + "name": "@gradio/accordion", + "version": "0.4.1", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "main_changeset": true, + "dependencies": { + "@gradio/atoms": "workspace:^", + "@gradio/column": "workspace:^", + "@gradio/statustracker": "workspace:^", + "@gradio/utils": "workspace:^" + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "exports": { + ".": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/accordion" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/shared/Accordion.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/shared/Accordion.svelte new file mode 100644 index 0000000000000000000000000000000000000000..621c6845c0dd9d9656d122464fd5011a65c205ab --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/accordion/shared/Accordion.svelte @@ -0,0 +1,35 @@ + + + +
+ +
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/CHANGELOG.md b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d91a98b95c5d6528e2c890304337ffd489d4b230 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/CHANGELOG.md @@ -0,0 +1,770 @@ +# @gradio/client + +## 1.6.0 + +### Features + +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Disable liking user message in chatbot by default but make it configurable +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Open audio/image input stream only when queue is ready +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Send Streaming data over Websocket if possible. Also support base64 output format for images. +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Streaming inputs for 5.0 +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - fix SSR apps on spaces +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Ssr part 2 +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - prefix api routes + +### Fixes + + +- [#8843](https://github.com/gradio-app/gradio/pull/8843) [`6f95286`](https://github.com/gradio-app/gradio/commit/6f95286337459efbccb95c9cfac63355669df9ee) - Trigger state change event on iterators + +## 1.6.0-beta.4 + +### Features + +- [#9483](https://github.com/gradio-app/gradio/pull/9483) [`8dc7c12`](https://github.com/gradio-app/gradio/commit/8dc7c12389311b60efcde1b9d3e3668a34d2dc00) - Send Streaming data over Websocket if possible. Also support base64 output format for images. Thanks @freddyaboulton! + +## 1.6.0-beta.3 + +### Features + +- [#9412](https://github.com/gradio-app/gradio/pull/9412) [`c2c2fd9`](https://github.com/gradio-app/gradio/commit/c2c2fd989348f826566773c07c0e0bda200199ff) - fix SSR apps on spaces. Thanks @pngwn! + +## 1.6.0-beta.2 + +### Features + +- [#9323](https://github.com/gradio-app/gradio/pull/9323) [`06babda`](https://github.com/gradio-app/gradio/commit/06babda0395fd3fbd323c1c3cb33704ecfd6deb0) - Disable liking user message in chatbot by default but make it configurable. Thanks @freddyaboulton! +- [#9339](https://github.com/gradio-app/gradio/pull/9339) [`4c8c6f2`](https://github.com/gradio-app/gradio/commit/4c8c6f2fe603081941c5fdc43f48a0632b9f31ad) - Ssr part 2. Thanks @pngwn! + +### Fixes + +- [#9299](https://github.com/gradio-app/gradio/pull/9299) [`aa35b07`](https://github.com/gradio-app/gradio/commit/aa35b0788e613fdd45446d267513e6f94fa208ea) - Trigger state change event on iterators. Thanks @freddyaboulton! + +## 1.6.0-beta.1 + +### Features + +- [#9200](https://github.com/gradio-app/gradio/pull/9200) [`2e179d3`](https://github.com/gradio-app/gradio/commit/2e179d35be6ed60a5a6bfc7303178d63e41781ad) - prefix api routes. Thanks @pngwn! + +## 1.6.0-beta.0 + +### Features + +- [#9149](https://github.com/gradio-app/gradio/pull/9149) [`3d7a9b8`](https://github.com/gradio-app/gradio/commit/3d7a9b81f6fef06187eca832471dc1692eb493a0) - Open audio/image input stream only when queue is ready. Thanks @freddyaboulton! +- [#8941](https://github.com/gradio-app/gradio/pull/8941) [`97a7bf6`](https://github.com/gradio-app/gradio/commit/97a7bf66a79179d1b91a3199d68e5c11216ca500) - Streaming inputs for 5.0. Thanks @freddyaboulton! + +## 1.5.2 + +### Fixes + +- [#9163](https://github.com/gradio-app/gradio/pull/9163) [`2b6cbf2`](https://github.com/gradio-app/gradio/commit/2b6cbf25908e42cf027324e54ef2cc0baad11a91) - fix exports and generate types. Thanks @pngwn! + +## 1.5.1 + +### Features + +- [#9118](https://github.com/gradio-app/gradio/pull/9118) [`e1c404d`](https://github.com/gradio-app/gradio/commit/e1c404da1143fb52b659d03e028bdba1badf443d) - setup npm-previews of all packages. Thanks @pngwn! + +## 1.5.0 + +### Features + +- [#8965](https://github.com/gradio-app/gradio/pull/8965) [`d30432e`](https://github.com/gradio-app/gradio/commit/d30432e9c6d4cc1e5cfd989a1a3ae4aba7e21290) - harden CI. Thanks @pngwn! + +### Fixes + +- [#8847](https://github.com/gradio-app/gradio/pull/8847) [`4d8a473`](https://github.com/gradio-app/gradio/commit/4d8a473632e388a312aee5c705b3c1f79853441b) - fix: wrong named param check for js client. Thanks @freddyaboulton! + +## 1.4.0 + +### Features + +- [#8816](https://github.com/gradio-app/gradio/pull/8816) [`9ee6839`](https://github.com/gradio-app/gradio/commit/9ee6839f94d23d685a800ed3a275206e0b0e48f6) - Change optionality of the `data` param in `submit` + `predict`. Thanks @hannahblair! + +### Fixes + +- [#8820](https://github.com/gradio-app/gradio/pull/8820) [`5050b36`](https://github.com/gradio-app/gradio/commit/5050b36221e75a18d8a5d4f74a725e70768a4c4a) - fix: wrong named param check for js client. Thanks @JacobLinCool! + +## 1.3.0 + +### Fixes + +- [#8699](https://github.com/gradio-app/gradio/pull/8699) [`012da05`](https://github.com/gradio-app/gradio/commit/012da05287846d94beb0ecdc28d7fbc48c4248ff) - Ensure JS client `status_callback` functionality works and improve status messages. Thanks @hannahblair! +- [#8505](https://github.com/gradio-app/gradio/pull/8505) [`2943d6d`](https://github.com/gradio-app/gradio/commit/2943d6d68847314885dc6c5c0247083116017ca0) - Add Timer component. Thanks @aliabid94! +- [#8715](https://github.com/gradio-app/gradio/pull/8715) [`a6b3c6c`](https://github.com/gradio-app/gradio/commit/a6b3c6ce4e1d06253860c72740024a9138e3a93a) - Ensure `@gradio/client`'s `submit` iterator releases as expected. Thanks @pngwn! +- [#8716](https://github.com/gradio-app/gradio/pull/8716) [`e834d30`](https://github.com/gradio-app/gradio/commit/e834d302e44f7a54565129bf2c11acf4e882a59b) - ensure `@gradio/client` always returns the correct data. Thanks @pngwn! +- [#8714](https://github.com/gradio-app/gradio/pull/8714) [`1b5b5b0`](https://github.com/gradio-app/gradio/commit/1b5b5b0b43e69ee84f3baad2aae59ffc9c4d995a) - Bind `fetch` and `stream` in JS client. Thanks @hannahblair! +- [#8720](https://github.com/gradio-app/gradio/pull/8720) [`936c713`](https://github.com/gradio-app/gradio/commit/936c7137a99ef59efdf75bae5dd27eea2ac1f577) - Documents auth in the guides, in the view API page, and also types the Blocks.config object. Thanks @abidlabs! + +## 1.2.1 + +### Features + +- [#8649](https://github.com/gradio-app/gradio/pull/8649) [`4b6c8b1`](https://github.com/gradio-app/gradio/commit/4b6c8b1c004cee67345a7f103ba2dc8e90b82e6c) - ensure `File` objects are handled in JS client `handle_file`. Thanks @hannahblair! + +## 1.2.0 + +### Features + +- [#8489](https://github.com/gradio-app/gradio/pull/8489) [`c2a0d05`](https://github.com/gradio-app/gradio/commit/c2a0d056d679d90631d9ccd944dadd67e7e03b7f) - Control Display of Error, Info, Warning. Thanks @freddyaboulton! +- [#8571](https://github.com/gradio-app/gradio/pull/8571) [`a77877f`](https://github.com/gradio-app/gradio/commit/a77877f62df7c610fcfac7b3b00e186a087c8ec6) - First time loading performance optimization. Thanks @baojianting! +- [#8600](https://github.com/gradio-app/gradio/pull/8600) [`7289c4b`](https://github.com/gradio-app/gradio/commit/7289c4b036d8a78c48f8c9e66ba998e6730e80d2) - Add credentials: include and Cookie header to prevent 401 error. Thanks @yinkiu602! +- [#8522](https://github.com/gradio-app/gradio/pull/8522) [`bdaa678`](https://github.com/gradio-app/gradio/commit/bdaa678d0c0a22250b41104f32e9121f98dc7437) - add handle_file docs. Thanks @pngwn! + +### Fixes + +- [#8521](https://github.com/gradio-app/gradio/pull/8521) [`900cf25`](https://github.com/gradio-app/gradio/commit/900cf25256a5b0563860097d69aac28b6afbfd8b) - Ensure frontend functions work when they don't return a value. Thanks @pngwn! +- [#8548](https://github.com/gradio-app/gradio/pull/8548) [`7fc0f51`](https://github.com/gradio-app/gradio/commit/7fc0f5149bb8d31f3d01b4151b478070499751ee) - Fix reload mode by implementing `close` on the client. Thanks @freddyaboulton! + +## 1.1.1 + +### Features + +- [#8499](https://github.com/gradio-app/gradio/pull/8499) [`c5f6e77`](https://github.com/gradio-app/gradio/commit/c5f6e7722a197d4706419ade14276ddecf3196f8) - Cache break themes on change. Thanks @aliabid94! + +## 1.1.0 + +### Features + +- [#8483](https://github.com/gradio-app/gradio/pull/8483) [`e2271e2`](https://github.com/gradio-app/gradio/commit/e2271e207d98074bf39b02ae3c5443b2f097627d) - documentation for @gradio/client. Thanks @pngwn! +- [#8485](https://github.com/gradio-app/gradio/pull/8485) [`f8ebace`](https://github.com/gradio-app/gradio/commit/f8ebaceccef60a112603d290d10072ef4e938a6a) - Ensure all status are reported internally when calling `predict`. Thanks @pngwn! + +## 1.0.0 + +### Highlights + +#### Clients 1.0 Launch! ([#8468](https://github.com/gradio-app/gradio/pull/8468) [`7cc0a0c`](https://github.com/gradio-app/gradio/commit/7cc0a0c1abea585c3f50ffb1ff78d2b08ddbdd92)) + +We're excited to unveil the first major release of the Gradio clients. +We've made it even easier to turn any Gradio application into a production endpoint thanks to the clients' **ergonomic**, **transparent**, and **portable** design. + +#### Ergonomic API 💆 + +**Stream From a Gradio app in 5 lines** + +Use the `submit` method to get a job you can iterate over: + +```python +from gradio_client import Client + +client = Client("gradio/llm_stream") + +for result in client.submit("What's the best UI framework in Python?"): + print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("gradio/llm_stream") +const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"}) + +for await (const msg of job) console.log(msg.data) +``` + +**Use the same keyword arguments as the app** + + +```python +from gradio_client import Client + +client = Client("http://127.0.0.1:7860/") +result = client.predict( + message="Hello!!", + system_prompt="You are helpful AI.", + tokens=10, + api_name="/chat" +) +print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("http://127.0.0.1:7860/"); +const result = await client.predict("/chat", { + message: "Hello!!", + system_prompt: "Hello!!", + tokens: 10, +}); + +console.log(result.data); +``` + +**Better Error Messages** + +If something goes wrong in the upstream app, the client will raise the same exception as the app provided that `show_error=True` in the original app's `launch()` function, or it's a `gr.Error` exception. + +#### Transparent Design 🪟 + +Anything you can do in the UI, you can do with the client: +* 🔒 Authentication +* 🛑 Job Cancelling +* ℹ️ Access Queue Position and API +* 📕 View the API information + +Here's an example showing how to display the queue position of a pending job: + +```python +from gradio_client import Client + +client = Client("gradio/diffusion_model") + +job = client.submit("A cute cat") +while not job.done(): + status = job.status() + print(f"Current in position {status.rank} out of {status.queue_size}") +``` + +#### Portable Design ⛺️ + +The client can run from pretty much any python and javascript environment (node, deno, the browser, Service Workers). + +Here's an example using the client from a Flask server using gevent: + +```python +from gevent import monkey +monkey.patch_all() + +from gradio_client import Client +from flask import Flask, send_file +import time + +app = Flask(__name__) + +imageclient = Client("gradio/diffusion_model") + +@app.route("/gen") +def gen(): + result = imageclient.predict( + "A cute cat", + api_name="/predict" + ) + return send_file(result) + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5000) +``` + +#### 1.0 Migration Guide and Breaking Changes + +**Python** +- The `serialize` argument of the `Client` class was removed. Has no effect. +- The `upload_files` argument of the `Client` was removed. +- All filepaths must be wrapped in the `handle_file` method. Example: +```python +from gradio_client import Client, handle_file + +client = Client("gradio/image_captioner") +client.predict(handle_file("cute_cat.jpg")) +``` +- The `output_dir` argument was removed. It is not specified in the `download_files` argument. + + +**Javascript** +The client has been redesigned entirely. It was refactored from a function into a class. An instance can now be constructed by awaiting the `connect` method. + +```js +const app = await Client.connect("gradio/whisper") +``` +The app variable has the same methods as the python class (`submit`, `predict`, `view_api`, `duplicate`). + + + +#### Additional Changes + +- [#8243](https://github.com/gradio-app/gradio/pull/8243) - Set orig_name in python client file uploads. +- [#8264](https://github.com/gradio-app/gradio/pull/8264) - Make exceptions in the Client more specific. +- [#8247](https://github.com/gradio-app/gradio/pull/8247) - Fix api recorder. +- [#8276](https://github.com/gradio-app/gradio/pull/8276) - Fix bug where client could not connect to apps that had self signed certificates. +- [#8245](https://github.com/gradio-app/gradio/pull/8245) - Cancel server progress from the python client. +- [#8200](https://github.com/gradio-app/gradio/pull/8200) - Support custom components in gr.load +- [#8182](https://github.com/gradio-app/gradio/pull/8182) - Convert sse calls in client from async to sync. +- [#7732](https://github.com/gradio-app/gradio/pull/7732) - Adds support for kwargs and default arguments in the python client, and improves how parameter information is displayed in the "view API" page. +- [#7888](https://github.com/gradio-app/gradio/pull/7888) - Cache view_api info in server and python client. +- [#7575](https://github.com/gradio-app/gradio/pull/7575) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. +- [#8401](https://github.com/gradio-app/gradio/pull/8401) - Add CDN installation to JS docs. +- [#8299](https://github.com/gradio-app/gradio/pull/8299) - Allow JS Client to work with authenticated spaces 🍪. +- [#8408](https://github.com/gradio-app/gradio/pull/8408) - Connect heartbeat if state created in render. Also fix config cleanup bug #8407. +- [#8258](https://github.com/gradio-app/gradio/pull/8258) - Improve URL handling in JS Client. +- [#8322](https://github.com/gradio-app/gradio/pull/8322) - ensure the client correctly handles all binary data. +- [#8296](https://github.com/gradio-app/gradio/pull/8296) - always create a jwt when connecting to a space if a hf_token is present. +- [#8285](https://github.com/gradio-app/gradio/pull/8285) - use the correct query param to pass the jwt to the heartbeat event. +- [#8272](https://github.com/gradio-app/gradio/pull/8272) - ensure client works for private spaces. +- [#8197](https://github.com/gradio-app/gradio/pull/8197) - Add support for passing keyword args to `data` in JS client. +- [#8252](https://github.com/gradio-app/gradio/pull/8252) - Client node fix. +- [#8209](https://github.com/gradio-app/gradio/pull/8209) - Rename `eventSource_Factory` and `fetch_implementation`. +- [#8109](https://github.com/gradio-app/gradio/pull/8109) - Implement JS Client tests. +- [#8211](https://github.com/gradio-app/gradio/pull/8211) - remove redundant event source logic. +- [#8179](https://github.com/gradio-app/gradio/pull/8179) - rework upload to be a class method + pass client into each component. +- [#8181](https://github.com/gradio-app/gradio/pull/8181) - Ensure connectivity to private HF spaces with SSE protocol. +- [#8169](https://github.com/gradio-app/gradio/pull/8169) - Only connect to heartbeat if needed. +- [#8118](https://github.com/gradio-app/gradio/pull/8118) - Add eventsource polyfill for Node.js and browser environments. +- [#7646](https://github.com/gradio-app/gradio/pull/7646) - Refactor JS Client. +- [#7974](https://github.com/gradio-app/gradio/pull/7974) - Fix heartbeat in the js client to be Lite compatible. +- [#7926](https://github.com/gradio-app/gradio/pull/7926) - Fixes streaming event race condition. + + Thanks @freddyaboulton! + +### Features + +- [#8370](https://github.com/gradio-app/gradio/pull/8370) [`48eeea4`](https://github.com/gradio-app/gradio/commit/48eeea4eaab7e24168688e3c3fbafb30e4e78d51) - Refactor Cancelling Logic To Use /cancel. Thanks @freddyaboulton! + +### Fixes + +- [#8477](https://github.com/gradio-app/gradio/pull/8477) [`d5a9604`](https://github.com/gradio-app/gradio/commit/d5a960493017a4890685af61d78ce7d3b3b12e6b) - Fix js client bundle. Thanks @pngwn! +- [#8451](https://github.com/gradio-app/gradio/pull/8451) [`9d2d605`](https://github.com/gradio-app/gradio/commit/9d2d6051caed5c8749a26a6fa7480a5ae6e6c4f3) - Change client submit API to be an AsyncIterable and support more platforms. Thanks @pngwn! +- [#8462](https://github.com/gradio-app/gradio/pull/8462) [`6447dfa`](https://github.com/gradio-app/gradio/commit/6447dface4d46db1c69460e8325a1928d0476a46) - Improve file handling in JS Client. Thanks @hannahblair! +- [#8439](https://github.com/gradio-app/gradio/pull/8439) [`63d36fb`](https://github.com/gradio-app/gradio/commit/63d36fbbf4bf6dc909be9a0ffc7b6bf6621d83e8) - Handle gradio apps using `state` in the JS Client. Thanks @hannahblair! + +## 0.20.1 + +### Features + +- [#8415](https://github.com/gradio-app/gradio/pull/8415) [`227de35`](https://github.com/gradio-app/gradio/commit/227de352982b3dcdf9384eaa28b7e9cf09afb6e8) - Fix spaces load error. Thanks @aliabid94! + +## 0.20.0 + +### Features + +- [#8401](https://github.com/gradio-app/gradio/pull/8401) [`d078621`](https://github.com/gradio-app/gradio/commit/d078621928136c09ca902d2f37594ed887c67d2e) - Add CDN installation to JS docs. Thanks @hannahblair! +- [#8243](https://github.com/gradio-app/gradio/pull/8243) [`55f664f`](https://github.com/gradio-app/gradio/commit/55f664f2979a49acc29a73cde16c6ebdfcc91db2) - Add event listener support to render blocks. Thanks @aliabid94! +- [#8398](https://github.com/gradio-app/gradio/pull/8398) [`945ac83`](https://github.com/gradio-app/gradio/commit/945ac837e779b120790814ea6f6f81bd2712f5f8) - Improve rendering. Thanks @aliabid94! +- [#8299](https://github.com/gradio-app/gradio/pull/8299) [`ab65360`](https://github.com/gradio-app/gradio/commit/ab653608045ff9462db7ad9fe63e1c60bf20e773) - Allow JS Client to work with authenticated spaces 🍪. Thanks @hannahblair! + +### Fixes + +- [#8408](https://github.com/gradio-app/gradio/pull/8408) [`e86dd01`](https://github.com/gradio-app/gradio/commit/e86dd01b6e8f7bab3d3c25b84f2ad33129138af4) - Connect heartbeat if state created in render. Also fix config cleanup bug #8407. Thanks @freddyaboulton! +- [#8258](https://github.com/gradio-app/gradio/pull/8258) [`1f8e5c4`](https://github.com/gradio-app/gradio/commit/1f8e5c44e054b943052d8f24d044696ddfd01a54) - Improve URL handling in JS Client. Thanks @hannahblair! + +## 0.19.4 + +### Fixes + +- [#8322](https://github.com/gradio-app/gradio/pull/8322) [`47012a0`](https://github.com/gradio-app/gradio/commit/47012a0c4e3e8a80fcae620aaf08b16ceb343cde) - ensure the client correctly handles all binary data. Thanks @Saghen! + +## 0.19.3 + +### Features + +- [#8229](https://github.com/gradio-app/gradio/pull/8229) [`7c81897`](https://github.com/gradio-app/gradio/commit/7c81897076ddcd0bb05e0e4ffec35bb9a986d330) - chore(deps): update dependency esbuild to ^0.21.0. Thanks @renovate! + +### Fixes + +- [#8296](https://github.com/gradio-app/gradio/pull/8296) [`929d216`](https://github.com/gradio-app/gradio/commit/929d216d49aa05614bc83f0761cf7b1cd803d8fe) - always create a jwt when connecting to a space if a hf_token is present. Thanks @pngwn! + +## 0.19.2 + +### Fixes + +- [#8285](https://github.com/gradio-app/gradio/pull/8285) [`7d9d8ea`](https://github.com/gradio-app/gradio/commit/7d9d8eab50d36cbecbb84c6a0f3cc1bca7215604) - use the correct query param to pass the jwt to the heartbeat event. Thanks @pngwn! + +## 0.19.1 + +### Fixes + +- [#8272](https://github.com/gradio-app/gradio/pull/8272) [`fbf4edd`](https://github.com/gradio-app/gradio/commit/fbf4edde7c896cdf4c903463e44c31ed96111b3c) - ensure client works for private spaces. Thanks @pngwn! + +## 0.19.0 + +### Features + +- [#8110](https://github.com/gradio-app/gradio/pull/8110) [`5436031`](https://github.com/gradio-app/gradio/commit/5436031f92c1596282eb64e1e74d555f279e9697) - Render decorator 2. Thanks @aliabid94! +- [#8197](https://github.com/gradio-app/gradio/pull/8197) [`e09b4e8`](https://github.com/gradio-app/gradio/commit/e09b4e8216b970bc1b142a0f08e7d190b954eb35) - Add support for passing keyword args to `data` in JS client. Thanks @hannahblair! + +### Fixes + +- [#8252](https://github.com/gradio-app/gradio/pull/8252) [`22df61a`](https://github.com/gradio-app/gradio/commit/22df61a26adf8023f6dd49c051979990e8d3879a) - Client node fix. Thanks @pngwn! + +## 0.18.0 + +### Features + +- [#8121](https://github.com/gradio-app/gradio/pull/8121) [`f5b710c`](https://github.com/gradio-app/gradio/commit/f5b710c919b0ce604ea955f0d5f4faa91095ca4a) - chore(deps): update dependency eslint to v9. Thanks @renovate! +- [#8209](https://github.com/gradio-app/gradio/pull/8209) [`b9afe93`](https://github.com/gradio-app/gradio/commit/b9afe93915401df5bd6737c89395c2477acfa585) - Rename `eventSource_Factory` and `fetch_implementation`. Thanks @hannahblair! +- [#8109](https://github.com/gradio-app/gradio/pull/8109) [`bed2f82`](https://github.com/gradio-app/gradio/commit/bed2f82e2297b50f7b59423a3de05af0b9910724) - Implement JS Client tests. Thanks @hannahblair! +- [#8211](https://github.com/gradio-app/gradio/pull/8211) [`91b5cd6`](https://github.com/gradio-app/gradio/commit/91b5cd6132fb8903c92f70fce0800324836a1fc3) - remove redundant event source logic. Thanks @hannahblair! + +### Fixes + +- [#8179](https://github.com/gradio-app/gradio/pull/8179) [`6a218b4`](https://github.com/gradio-app/gradio/commit/6a218b4148095aaa0c58d8c20973ba01c8764fc2) - rework upload to be a class method + pass client into each component. Thanks @pngwn! +- [#8181](https://github.com/gradio-app/gradio/pull/8181) [`cf52ca6`](https://github.com/gradio-app/gradio/commit/cf52ca6a51320ece97f009a177792840b5fbc785) - Ensure connectivity to private HF spaces with SSE protocol. Thanks @hannahblair! +- [#8169](https://github.com/gradio-app/gradio/pull/8169) [`3a6f1a5`](https://github.com/gradio-app/gradio/commit/3a6f1a50b263e0a733f609a08019fc4d05480e1a) - Only connect to heartbeat if needed. Thanks @freddyaboulton! +- [#8118](https://github.com/gradio-app/gradio/pull/8118) [`7aca673`](https://github.com/gradio-app/gradio/commit/7aca673b38a087533524b2fd8dd3a03e0e4bacfe) - Add eventsource polyfill for Node.js and browser environments. Thanks @hannahblair! + +## 0.17.0 + +### Highlights + +#### Setting File Upload Limits ([#7909](https://github.com/gradio-app/gradio/pull/7909) [`2afca65`](https://github.com/gradio-app/gradio/commit/2afca6541912b37dc84f447c7ad4af21607d7c72)) + +We have added a `max_file_size` size parameter to `launch()` that limits to size of files uploaded to the server. This limit applies to each individual file. This parameter can be specified as a string or an integer (corresponding to the size in bytes). + +The following code snippet sets a max file size of 5 megabytes. + +```python +import gradio as gr + +demo = gr.Interface(lambda x: x, "image", "image") + +demo.launch(max_file_size="5mb") +# or +demo.launch(max_file_size=5 * gr.FileSize.MB) +``` + +![max_file_size_upload](https://github.com/gradio-app/gradio/assets/41651716/7547330c-a082-4901-a291-3f150a197e45) + + +#### Error states can now be cleared + +When a component encounters an error, the error state shown in the UI can now be cleared by clicking on the `x` icon in the top right of the component. This applies to all types of errors, whether it's raised in the UI or the server. + +![error_modal_calculator](https://github.com/gradio-app/gradio/assets/41651716/16cb071c-accd-45a6-9c18-0dea27d4bd98) + + Thanks @freddyaboulton! + +### Features + +- [#8056](https://github.com/gradio-app/gradio/pull/8056) [`2e469a5`](https://github.com/gradio-app/gradio/commit/2e469a5f99e52a5011a010f46e47dde7bb0c7140) - Using keys to preserve values between reloads. Thanks @aliabid94! +- [#7646](https://github.com/gradio-app/gradio/pull/7646) [`450b8cc`](https://github.com/gradio-app/gradio/commit/450b8cc898f130f15caa3742f65c17b9f7a8f398) - Refactor JS Client. Thanks @hannahblair! +- [#8061](https://github.com/gradio-app/gradio/pull/8061) [`17e83c9`](https://github.com/gradio-app/gradio/commit/17e83c958ebb35b3e122ca486067d1bd5ce33a22) - Docs Reorg and Intro Page. Thanks @aliabd! + +### Fixes + +- [#8066](https://github.com/gradio-app/gradio/pull/8066) [`624f9b9`](https://github.com/gradio-app/gradio/commit/624f9b9477f74a581a6c14119234f9efdfcda398) - make gradio dev tools a local dependency rather than bundling. Thanks @pngwn! + +## 0.16.0 + +### Features + +- [#7845](https://github.com/gradio-app/gradio/pull/7845) [`dbb7373`](https://github.com/gradio-app/gradio/commit/dbb7373dde69d4ed2741942b5a1898f8620cec24) - ensure `ImageEditor` events work as expected. Thanks @pngwn! + +### Fixes + +- [#7974](https://github.com/gradio-app/gradio/pull/7974) [`79e0aa8`](https://github.com/gradio-app/gradio/commit/79e0aa81c94e755faa6e85d76ac5d5a666313e6a) - Fix heartbeat in the js client to be Lite compatible. Thanks @whitphx! + +## 0.15.1 + +### Fixes + +- [#7926](https://github.com/gradio-app/gradio/pull/7926) [`9666854`](https://github.com/gradio-app/gradio/commit/966685479078f59430b3bced7e6068eb8157c003) - Fixes streaming event race condition. Thanks @aliabid94! + +## 0.15.0 + +### Highlights + +#### Automatically delete state after user has disconnected from the webpage ([#7829](https://github.com/gradio-app/gradio/pull/7829) [`6a4bf7a`](https://github.com/gradio-app/gradio/commit/6a4bf7abe29059dbdc6a342e0366fdaa2e4120ee)) + +Gradio now automatically deletes `gr.State` variables stored in the server's RAM when users close their browser tab. +The deletion will happen 60 minutes after the server detected a disconnect from the user's browser. +If the user connects again in that timeframe, their state will not be deleted. + +Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay). +You can think of the `unload` event as the opposite of the `load` event. + + +```python +with gr.Blocks() as demo: + gr.Markdown( +"""# State Cleanup Demo +🖼️ Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload. +""") + with gr.Row(): + with gr.Column(scale=1): + with gr.Row(): + img = gr.Image(label="Generated Image", height=300, width=300) + with gr.Row(): + gen = gr.Button(value="Generate") + with gr.Row(): + history = gr.Gallery(label="Previous Generations", height=500, columns=10) + state = gr.State(value=[], delete_callback=lambda v: print("STATE DELETED")) + + demo.load(generate_random_img, [state], [img, state, history]) + gen.click(generate_random_img, [state], [img, state, history]) + demo.unload(delete_directory) + + +demo.launch(auth=lambda user,pwd: True, + auth_message="Enter any username and password to continue") +``` + + Thanks @freddyaboulton! + +## 0.14.0 + +### Features + +- [#7691](https://github.com/gradio-app/gradio/pull/7691) [`84f81fe`](https://github.com/gradio-app/gradio/commit/84f81fec9287b041203a141bbf2852720f7d199c) - Closing stream from the backend. Thanks @aliabid94! + +### Fixes + +- [#7564](https://github.com/gradio-app/gradio/pull/7564) [`5d1e8da`](https://github.com/gradio-app/gradio/commit/5d1e8dae5ac23f605c3b5f41dbe18751dff380a0) - batch UI updates on a per frame basis. Thanks @pngwn! + +## 0.13.0 + +### Fixes + +- [#7575](https://github.com/gradio-app/gradio/pull/7575) [`d0688b3`](https://github.com/gradio-app/gradio/commit/d0688b3c25feabb4fc7dfa0ab86086b3af7eb337) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. Thanks @abidlabs! + +## 0.12.2 + +### Features + +- [#7528](https://github.com/gradio-app/gradio/pull/7528) [`eda33b3`](https://github.com/gradio-app/gradio/commit/eda33b3763897a542acf298e523fa493dc655aee) - Refactors `get_fetchable_url_or_file()` to remove it from the frontend. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#7340](https://github.com/gradio-app/gradio/pull/7340) [`4b0d589`](https://github.com/gradio-app/gradio/commit/4b0d58933057432758a54169a360eb352903d6b4) - chore(deps): update all non-major dependencies. Thanks [@renovate](https://github.com/apps/renovate)! + +## 0.12.1 + +### Fixes + +- [#7411](https://github.com/gradio-app/gradio/pull/7411) [`32b317f`](https://github.com/gradio-app/gradio/commit/32b317f24e3d43f26684bb9f3964f31efd0ea556) - Set `root` correctly for Gradio apps that are deployed behind reverse proxies. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.12.0 + +### Features + +- [#7183](https://github.com/gradio-app/gradio/pull/7183) [`49d9c48`](https://github.com/gradio-app/gradio/commit/49d9c48537aa706bf72628e3640389470138bdc6) - [WIP] Refactor file normalization to be in the backend and remove it from the frontend of each component. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.11.0 + +### Features + +- [#7102](https://github.com/gradio-app/gradio/pull/7102) [`68a54a7`](https://github.com/gradio-app/gradio/commit/68a54a7a310d8d7072fdae930bf1cfdf12c45a7f) - Improve chatbot streaming performance with diffs. Thanks [@aliabid94](https://github.com/aliabid94)!/n Note that this PR changes the API format for generator functions, which would be a breaking change for any clients reading the EventStream directly + +## 0.10.1 + +### Fixes + +- [#7055](https://github.com/gradio-app/gradio/pull/7055) [`3c3cf86`](https://github.com/gradio-app/gradio/commit/3c3cf8618a8cad1ef66a7f96664923d2c9f5e0e2) - Fix UI freeze on rapid generators. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.10.0 + +### Features + +- [#6931](https://github.com/gradio-app/gradio/pull/6931) [`6c863af`](https://github.com/gradio-app/gradio/commit/6c863af92fa9ceb5c638857eb22cc5ddb718d549) - Fix functional tests. Thanks [@aliabid94](https://github.com/aliabid94)! +- [#6820](https://github.com/gradio-app/gradio/pull/6820) [`649cd4d`](https://github.com/gradio-app/gradio/commit/649cd4d68041d11fcbe31f8efa455345ac49fc74) - Use `EventSource_factory` in `open_stream()` for Wasm. Thanks [@whitphx](https://github.com/whitphx)! + +## 0.9.4 + +### Fixes + +- [#6863](https://github.com/gradio-app/gradio/pull/6863) [`d406855`](https://github.com/gradio-app/gradio/commit/d4068557953746662235d595ec435c42ceb24414) - Fix JS Client when app is running behind a proxy. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.9.3 + +### Features + +- [#6814](https://github.com/gradio-app/gradio/pull/6814) [`828fb9e`](https://github.com/gradio-app/gradio/commit/828fb9e6ce15b6ea08318675a2361117596a1b5d) - Refactor queue so that there are separate queues for each concurrency id. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.9.2 + +### Features + +- [#6798](https://github.com/gradio-app/gradio/pull/6798) [`245d58e`](https://github.com/gradio-app/gradio/commit/245d58eff788e8d44a59d37a2d9b26d0f08a62b4) - Improve how server/js client handle unexpected errors. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.9.1 + +### Fixes + +- [#6693](https://github.com/gradio-app/gradio/pull/6693) [`34f9431`](https://github.com/gradio-app/gradio/commit/34f943101bf7dd6b8a8974a6131c1ed7c4a0dac0) - Python client properly handles hearbeat and log messages. Also handles responses longer than 65k. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.9.0 + +### Features + +- [#6398](https://github.com/gradio-app/gradio/pull/6398) [`67ddd40`](https://github.com/gradio-app/gradio/commit/67ddd40b4b70d3a37cb1637c33620f8d197dbee0) - Lite v4. Thanks [@whitphx](https://github.com/whitphx)! + +### Fixes + +- [#6556](https://github.com/gradio-app/gradio/pull/6556) [`d76bcaa`](https://github.com/gradio-app/gradio/commit/d76bcaaaf0734aaf49a680f94ea9d4d22a602e70) - Fix api event drops. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.8.2 + +### Features + +- [#6511](https://github.com/gradio-app/gradio/pull/6511) [`71f1a1f99`](https://github.com/gradio-app/gradio/commit/71f1a1f9931489d465c2c1302a5c8d768a3cd23a) - Mark `FileData.orig_name` optional on the frontend aligning the type definition on the Python side. Thanks [@whitphx](https://github.com/whitphx)! + +## 0.8.1 + +### Fixes + +- [#6383](https://github.com/gradio-app/gradio/pull/6383) [`324867f63`](https://github.com/gradio-app/gradio/commit/324867f63c920113d89a565892aa596cf8b1e486) - Fix event target. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.8.0 + +### Features + +- [#6307](https://github.com/gradio-app/gradio/pull/6307) [`f1409f95e`](https://github.com/gradio-app/gradio/commit/f1409f95ed39c5565bed6a601e41f94e30196a57) - Provide status updates on file uploads. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.7.2 + +### Fixes + +- [#6327](https://github.com/gradio-app/gradio/pull/6327) [`bca6c2c80`](https://github.com/gradio-app/gradio/commit/bca6c2c80f7e5062427019de45c282238388af95) - Restore query parameters in request. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.7.1 + +### Features + +- [#6137](https://github.com/gradio-app/gradio/pull/6137) [`2ba14b284`](https://github.com/gradio-app/gradio/commit/2ba14b284f908aa13859f4337167a157075a68eb) - JS Param. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)! + +## 0.7.0 + +### Features + +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Image v4. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Swap websockets for SSE. Thanks [@pngwn](https://github.com/pngwn)! + +## 0.7.0-beta.1 + +### Features + +- [#6143](https://github.com/gradio-app/gradio/pull/6143) [`e4f7b4b40`](https://github.com/gradio-app/gradio/commit/e4f7b4b409323b01aa01b39e15ce6139e29aa073) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)! +- [#6094](https://github.com/gradio-app/gradio/pull/6094) [`c476bd5a5`](https://github.com/gradio-app/gradio/commit/c476bd5a5b70836163b9c69bf4bfe068b17fbe13) - Image v4. Thanks [@pngwn](https://github.com/pngwn)! +- [#6069](https://github.com/gradio-app/gradio/pull/6069) [`bf127e124`](https://github.com/gradio-app/gradio/commit/bf127e1241a41401e144874ea468dff8474eb505) - Swap websockets for SSE. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.7.0-beta.0 + +### Features + +- [#6016](https://github.com/gradio-app/gradio/pull/6016) [`83e947676`](https://github.com/gradio-app/gradio/commit/83e947676d327ca2ab6ae2a2d710c78961c771a0) - Format js in v4 branch. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +### Fixes + +- [#6046](https://github.com/gradio-app/gradio/pull/6046) [`dbb7de5e0`](https://github.com/gradio-app/gradio/commit/dbb7de5e02c53fee05889d696d764d212cb96c74) - fix tests. Thanks [@pngwn](https://github.com/pngwn)! + +## 0.6.0 + +### Features + +- [#5972](https://github.com/gradio-app/gradio/pull/5972) [`11a300791`](https://github.com/gradio-app/gradio/commit/11a3007916071f0791844b0a37f0fb4cec69cea3) - Lite: Support opening the entrypoint HTML page directly in browser via the `file:` protocol. Thanks [@whitphx](https://github.com/whitphx)! + +## 0.5.2 + +### Fixes + +- [#5840](https://github.com/gradio-app/gradio/pull/5840) [`4e62b8493`](https://github.com/gradio-app/gradio/commit/4e62b8493dfce50bafafe49f1a5deb929d822103) - Ensure websocket polyfill doesn't load if there is already a `global.Webocket` property set. Thanks [@Jay2theWhy](https://github.com/Jay2theWhy)! + +## 0.5.1 + +### Fixes + +- [#5816](https://github.com/gradio-app/gradio/pull/5816) [`796145e2c`](https://github.com/gradio-app/gradio/commit/796145e2c48c4087bec17f8ec0be4ceee47170cb) - Fix calls to the component server so that `gr.FileExplorer` works on Spaces. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.5.0 + +### Highlights + +#### new `FileExplorer` component ([#5672](https://github.com/gradio-app/gradio/pull/5672) [`e4a307ed6`](https://github.com/gradio-app/gradio/commit/e4a307ed6cde3bbdf4ff2f17655739addeec941e)) + +Thanks to a new capability that allows components to communicate directly with the server _without_ passing data via the value, we have created a new `FileExplorer` component. + +This component allows you to populate the explorer by passing a glob, but only provides the selected file(s) in your prediction function. + +Users can then navigate the virtual filesystem and select files which will be accessible in your predict function. This component will allow developers to build more complex spaces, with more flexible input options. + +![output](https://github.com/pngwn/MDsveX/assets/12937446/ef108f0b-0e84-4292-9984-9dc66b3e144d) + +For more information check the [`FileExplorer` documentation](https://gradio.app/docs/fileexplorer). + + Thanks [@aliabid94](https://github.com/aliabid94)! + +### Features + +- [#5787](https://github.com/gradio-app/gradio/pull/5787) [`caeee8bf7`](https://github.com/gradio-app/gradio/commit/caeee8bf7821fd5fe2f936ed82483bed00f613ec) - ensure the client does not depend on `window` when running in a node environment. Thanks [@gibiee](https://github.com/gibiee)! + +### Fixes + +- [#5776](https://github.com/gradio-app/gradio/pull/5776) [`c0fef4454`](https://github.com/gradio-app/gradio/commit/c0fef44541bfa61568bdcfcdfc7d7d79869ab1df) - Revert replica proxy logic and instead implement using the `root` variable. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.4.2 + +### Features + +- [#5124](https://github.com/gradio-app/gradio/pull/5124) [`6e56a0d9b`](https://github.com/gradio-app/gradio/commit/6e56a0d9b0c863e76c69e1183d9d40196922b4cd) - Lite: Websocket queueing. Thanks [@whitphx](https://github.com/whitphx)! + +## 0.4.1 + +### Fixes + +- [#5705](https://github.com/gradio-app/gradio/pull/5705) [`78e7cf516`](https://github.com/gradio-app/gradio/commit/78e7cf5163e8d205e8999428fce4c02dbdece25f) - ensure internal data has updated before dispatching `success` or `then` events. Thanks [@pngwn](https://github.com/pngwn)! + +## 0.4.0 + +### Features + +- [#5682](https://github.com/gradio-app/gradio/pull/5682) [`c57f1b75e`](https://github.com/gradio-app/gradio/commit/c57f1b75e272c76b0af4d6bd0c7f44743ff34f26) - Fix functional tests. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#5681](https://github.com/gradio-app/gradio/pull/5681) [`40de3d217`](https://github.com/gradio-app/gradio/commit/40de3d2178b61ebe424b6f6228f94c0c6f679bea) - add query parameters to the `gr.Request` object through the `query_params` attribute. Thanks [@DarhkVoyd](https://github.com/DarhkVoyd)! +- [#5653](https://github.com/gradio-app/gradio/pull/5653) [`ea0e00b20`](https://github.com/gradio-app/gradio/commit/ea0e00b207b4b90a10e9d054c4202d4e705a29ba) - Prevent Clients from accessing API endpoints that set `api_name=False`. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.3.1 + +### Fixes + +- [#5412](https://github.com/gradio-app/gradio/pull/5412) [`26fef8c7`](https://github.com/gradio-app/gradio/commit/26fef8c7f85a006c7e25cdbed1792df19c512d02) - Skip view_api request in js client when auth enabled. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.3.0 + +### Features + +- [#5267](https://github.com/gradio-app/gradio/pull/5267) [`119c8343`](https://github.com/gradio-app/gradio/commit/119c834331bfae60d4742c8f20e9cdecdd67e8c2) - Faster reload mode. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.2.1 + +### Features + +- [#5173](https://github.com/gradio-app/gradio/pull/5173) [`730f0c1d`](https://github.com/gradio-app/gradio/commit/730f0c1d54792eb11359e40c9f2326e8a6e39203) - Ensure gradio client works as expected for functions that return nothing. Thanks [@raymondtri](https://github.com/raymondtri)! + +## 0.2.0 + +### Features + +- [#5133](https://github.com/gradio-app/gradio/pull/5133) [`61129052`](https://github.com/gradio-app/gradio/commit/61129052ed1391a75c825c891d57fa0ad6c09fc8) - Update dependency esbuild to ^0.19.0. Thanks [@renovate](https://github.com/apps/renovate)! +- [#5035](https://github.com/gradio-app/gradio/pull/5035) [`8b4eb8ca`](https://github.com/gradio-app/gradio/commit/8b4eb8cac9ea07bde31b44e2006ca2b7b5f4de36) - JS Client: Fixes cannot read properties of null (reading 'is_file'). Thanks [@raymondtri](https://github.com/raymondtri)! + +### Fixes + +- [#5075](https://github.com/gradio-app/gradio/pull/5075) [`67265a58`](https://github.com/gradio-app/gradio/commit/67265a58027ef1f9e4c0eb849a532f72eaebde48) - Allow supporting >1000 files in `gr.File()` and `gr.UploadButton()`. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.1.4 + +### Patch Changes + +- [#4717](https://github.com/gradio-app/gradio/pull/4717) [`ab5d1ea0`](https://github.com/gradio-app/gradio/commit/ab5d1ea0de87ed888779b66fd2a705583bd29e02) Thanks [@whitphx](https://github.com/whitphx)! - Fix the package description + +## 0.1.3 + +### Patch Changes + +- [#4357](https://github.com/gradio-app/gradio/pull/4357) [`0dbd8f7f`](https://github.com/gradio-app/gradio/commit/0dbd8f7fee4b4877f783fa7bc493f98bbfc3d01d) Thanks [@pngwn](https://github.com/pngwn)! - Various internal refactors and cleanups. + +## 0.1.2 + +### Patch Changes + +- [#4273](https://github.com/gradio-app/gradio/pull/4273) [`1d0f0a9d`](https://github.com/gradio-app/gradio/commit/1d0f0a9db096552e67eb2197c932342587e9e61e) Thanks [@pngwn](https://github.com/pngwn)! - Ensure websocket error messages are correctly handled. + +- [#4315](https://github.com/gradio-app/gradio/pull/4315) [`b525b122`](https://github.com/gradio-app/gradio/commit/b525b122dd8569bbaf7e06db5b90d622d2e9073d) Thanks [@whitphx](https://github.com/whitphx)! - Refacor types. + +- [#4271](https://github.com/gradio-app/gradio/pull/4271) [`1151c525`](https://github.com/gradio-app/gradio/commit/1151c5253554cb87ebd4a44a8a470ac215ff782b) Thanks [@pngwn](https://github.com/pngwn)! - Ensure the full root path is always respected when making requests to a gradio app server. + +## 0.1.1 + +### Patch Changes + +- [#4201](https://github.com/gradio-app/gradio/pull/4201) [`da5b4ee1`](https://github.com/gradio-app/gradio/commit/da5b4ee11721175858ded96e5710225369097f74) Thanks [@pngwn](https://github.com/pngwn)! - Ensure semiver is bundled so CDN links work correctly. + +- [#4202](https://github.com/gradio-app/gradio/pull/4202) [`a26e9afd`](https://github.com/gradio-app/gradio/commit/a26e9afde319382993e6ddc77cc4e56337a31248) Thanks [@pngwn](https://github.com/pngwn)! - Ensure all URLs returned by the client are complete URLs with the correct host instead of an absolute path relative to a server. + +## 0.1.0 + +### Minor Changes + +- [#4185](https://github.com/gradio-app/gradio/pull/4185) [`67239ca9`](https://github.com/gradio-app/gradio/commit/67239ca9b2fe3796853fbf7bf865c9e4b383200d) Thanks [@pngwn](https://github.com/pngwn)! - Update client for initial release + +### Patch Changes + +- [#3692](https://github.com/gradio-app/gradio/pull/3692) [`48e8b113`](https://github.com/gradio-app/gradio/commit/48e8b113f4b55e461d9da4f153bf72aeb4adf0f1) Thanks [@pngwn](https://github.com/pngwn)! - Ensure client works in node, create ESM bundle and generate typescript declaration files. + +- [#3605](https://github.com/gradio-app/gradio/pull/3605) [`ae4277a9`](https://github.com/gradio-app/gradio/commit/ae4277a9a83d49bdadfe523b0739ba988128e73b) Thanks [@pngwn](https://github.com/pngwn)! - Update readme. \ No newline at end of file diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/client.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/client.ts new file mode 100644 index 0000000000000000000000000000000000000000..47058adb755229710e2e6fd91b5c09fb3f76a179 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/client.ts @@ -0,0 +1,525 @@ +import type { + ApiData, + ApiInfo, + ClientOptions, + Config, + DuplicateOptions, + EndpointInfo, + JsApiData, + PredictReturn, + SpaceStatus, + Status, + UploadResponse, + client_return, + SubmitIterable, + GradioEvent +} from "./types"; +import { view_api } from "./utils/view_api"; +import { upload_files } from "./utils/upload_files"; +import { upload, FileData } from "./upload"; +import { handle_blob } from "./utils/handle_blob"; +import { post_data } from "./utils/post_data"; +import { predict } from "./utils/predict"; +import { duplicate } from "./utils/duplicate"; +import { submit } from "./utils/submit"; +import { RE_SPACE_NAME, process_endpoint } from "./helpers/api_info"; +import { + map_names_to_ids, + resolve_cookies, + resolve_config, + get_jwt, + parse_and_set_cookies +} from "./helpers/init_helpers"; +import { check_and_wake_space, check_space_status } from "./helpers/spaces"; +import { open_stream, readable_stream, close_stream } from "./utils/stream"; +import { + API_INFO_ERROR_MSG, + CONFIG_ERROR_MSG, + HEARTBEAT_URL, + COMPONENT_SERVER_URL +} from "./constants"; + +export class Client { + app_reference: string; + options: ClientOptions; + + config: Config | undefined; + api_prefix = ""; + api_info: ApiInfo | undefined; + api_map: Record = {}; + session_hash: string = Math.random().toString(36).substring(2); + jwt: string | false = false; + last_status: Record = {}; + + private cookies: string | null = null; + + // streaming + stream_status = { open: false }; + pending_stream_messages: Record = {}; + pending_diff_streams: Record = {}; + event_callbacks: Record Promise> = {}; + unclosed_events: Set = new Set(); + heartbeat_event: EventSource | null = null; + abort_controller: AbortController | null = null; + stream_instance: EventSource | null = null; + current_payload: any; + ws_map: Record = {}; + + fetch(input: RequestInfo | URL, init?: RequestInit): Promise { + const headers = new Headers(init?.headers || {}); + if (this && this.cookies) { + headers.append("Cookie", this.cookies); + } + + return fetch(input, { ...init, headers }); + } + + stream(url: URL): EventSource { + const headers = new Headers(); + if (this && this.cookies) { + headers.append("Cookie", this.cookies); + } + + this.abort_controller = new AbortController(); + + this.stream_instance = readable_stream(url.toString(), { + credentials: "include", + headers: headers, + signal: this.abort_controller.signal + }); + + return this.stream_instance; + } + + view_api: () => Promise>; + upload_files: ( + root_url: string, + files: (Blob | File)[], + upload_id?: string + ) => Promise; + upload: ( + file_data: FileData[], + root_url: string, + upload_id?: string, + max_file_size?: number + ) => Promise<(FileData | null)[] | null>; + handle_blob: ( + endpoint: string, + data: unknown[], + endpoint_info: EndpointInfo + ) => Promise; + post_data: ( + url: string, + body: unknown, + additional_headers?: any + ) => Promise; + submit: ( + endpoint: string | number, + data: unknown[] | Record | undefined, + event_data?: unknown, + trigger_id?: number | null, + all_events?: boolean + ) => SubmitIterable; + predict: ( + endpoint: string | number, + data: unknown[] | Record | undefined, + event_data?: unknown + ) => Promise; + open_stream: () => Promise; + private resolve_config: (endpoint: string) => Promise; + private resolve_cookies: () => Promise; + constructor( + app_reference: string, + options: ClientOptions = { events: ["data"] } + ) { + this.app_reference = app_reference; + if (!options.events) { + options.events = ["data"]; + } + + this.options = options; + this.current_payload = {}; + this.view_api = view_api.bind(this); + this.upload_files = upload_files.bind(this); + this.handle_blob = handle_blob.bind(this); + this.post_data = post_data.bind(this); + this.submit = submit.bind(this); + this.predict = predict.bind(this); + this.open_stream = open_stream.bind(this); + this.resolve_config = resolve_config.bind(this); + this.resolve_cookies = resolve_cookies.bind(this); + this.upload = upload.bind(this); + this.fetch = this.fetch.bind(this); + this.handle_space_success = this.handle_space_success.bind(this); + this.stream = this.stream.bind(this); + } + + private async init(): Promise { + if ( + (typeof window === "undefined" || !("WebSocket" in window)) && + !global.WebSocket + ) { + const ws = await import("ws"); + global.WebSocket = ws.WebSocket as unknown as typeof WebSocket; + } + + if (this.options.auth) { + await this.resolve_cookies(); + } + + await this._resolve_config().then(({ config }) => + this._resolve_hearbeat(config) + ); + + this.api_info = await this.view_api(); + this.api_map = map_names_to_ids(this.config?.dependencies || []); + } + + async _resolve_hearbeat(_config: Config): Promise { + if (_config) { + this.config = _config; + this.api_prefix = _config.api_prefix || ""; + + if (this.config && this.config.connect_heartbeat) { + if (this.config.space_id && this.options.hf_token) { + this.jwt = await get_jwt( + this.config.space_id, + this.options.hf_token, + this.cookies + ); + } + } + } + + if (_config.space_id && this.options.hf_token) { + this.jwt = await get_jwt(_config.space_id, this.options.hf_token); + } + + if (this.config && this.config.connect_heartbeat) { + // connect to the heartbeat endpoint via GET request + const heartbeat_url = new URL( + `${this.config.root}${this.api_prefix}/${HEARTBEAT_URL}/${this.session_hash}` + ); + + // if the jwt is available, add it to the query params + if (this.jwt) { + heartbeat_url.searchParams.set("__sign", this.jwt); + } + + // Just connect to the endpoint without parsing the response. Ref: https://github.com/gradio-app/gradio/pull/7974#discussion_r1557717540 + if (!this.heartbeat_event) { + this.heartbeat_event = this.stream(heartbeat_url); + } + } + } + + static async connect( + app_reference: string, + options: ClientOptions = { + events: ["data"] + } + ): Promise { + const client = new this(app_reference, options); // this refers to the class itself, not the instance + await client.init(); + return client; + } + + close(): void { + close_stream(this.stream_status, this.abort_controller); + } + + set_current_payload(payload: any): void { + this.current_payload = payload; + } + + static async duplicate( + app_reference: string, + options: DuplicateOptions = { + events: ["data"] + } + ): Promise { + return duplicate(app_reference, options); + } + + private async _resolve_config(): Promise { + const { http_protocol, host, space_id } = await process_endpoint( + this.app_reference, + this.options.hf_token + ); + + const { status_callback } = this.options; + + if (space_id && status_callback) { + await check_and_wake_space(space_id, status_callback); + } + + let config: Config | undefined; + + try { + config = await this.resolve_config(`${http_protocol}//${host}`); + + if (!config) { + throw new Error(CONFIG_ERROR_MSG); + } + + return this.config_success(config); + } catch (e: any) { + if (space_id && status_callback) { + check_space_status( + space_id, + RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", + this.handle_space_success + ); + } else { + if (status_callback) + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }); + throw Error(e); + } + } + } + + private async config_success( + _config: Config + ): Promise { + this.config = _config; + this.api_prefix = _config.api_prefix || ""; + + if (typeof window !== "undefined" && typeof document !== "undefined") { + if (window.location.protocol === "https:") { + this.config.root = this.config.root.replace("http://", "https://"); + } + } + + if (this.config.auth_required) { + return this.prepare_return_obj(); + } + + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(API_INFO_ERROR_MSG + (e as Error).message); + } + + return this.prepare_return_obj(); + } + + async handle_space_success(status: SpaceStatus): Promise { + if (!this) { + throw new Error(CONFIG_ERROR_MSG); + } + const { status_callback } = this.options; + if (status_callback) status_callback(status); + if (status.status === "running") { + try { + this.config = await this._resolve_config(); + this.api_prefix = this?.config?.api_prefix || ""; + + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); + } + + const _config = await this.config_success(this.config); + + return _config as Config; + } catch (e) { + if (status_callback) { + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }); + } + throw e; + } + } + } + + public async component_server( + component_id: number, + fn_name: string, + data: unknown[] | { binary: boolean; data: Record } + ): Promise { + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); + } + + const headers: { + Authorization?: string; + "Content-Type"?: "application/json"; + } = {}; + + const { hf_token } = this.options; + const { session_hash } = this; + + if (hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + + let root_url: string; + let component = this.config.components.find( + (comp) => comp.id === component_id + ); + if (component?.props?.root_url) { + root_url = component.props.root_url; + } else { + root_url = this.config.root; + } + + let body: FormData | string; + + if ("binary" in data) { + body = new FormData(); + for (const key in data.data) { + if (key === "binary") continue; + body.append(key, data.data[key]); + } + body.set("component_id", component_id.toString()); + body.set("fn_name", fn_name); + body.set("session_hash", session_hash); + } else { + body = JSON.stringify({ + data: data, + component_id, + fn_name, + session_hash + }); + + headers["Content-Type"] = "application/json"; + } + + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + try { + const response = await this.fetch( + `${root_url}${this.api_prefix}/${COMPONENT_SERVER_URL}/`, + { + method: "POST", + body: body, + headers, + credentials: "include" + } + ); + + if (!response.ok) { + throw new Error( + "Could not connect to component server: " + response.statusText + ); + } + + const output = await response.json(); + return output; + } catch (e) { + console.warn(e); + } + } + + public set_cookies(raw_cookies: string): void { + this.cookies = parse_and_set_cookies(raw_cookies).join("; "); + } + + private prepare_return_obj(): client_return { + return { + config: this.config, + predict: this.predict, + submit: this.submit, + view_api: this.view_api, + component_server: this.component_server + }; + } + + private async connect_ws(url: string): Promise { + return new Promise((resolve, reject) => { + let ws; + try { + ws = new WebSocket(url); + } catch (e) { + this.ws_map[url] = "failed"; + return; + } + + ws.onopen = () => { + resolve(); + }; + + ws.onerror = (error) => { + console.error("WebSocket error:", error); + this.close_ws(url); + this.ws_map[url] = "failed"; + resolve(); + }; + + ws.onclose = () => { + delete this.ws_map[url]; + this.ws_map[url] = "failed"; + }; + + ws.onmessage = (event) => {}; + this.ws_map[url] = ws; + }); + } + + async send_ws_message(url: string, data: any): Promise { + // connect if not connected + if (!(url in this.ws_map)) { + await this.connect_ws(url); + } + const ws = this.ws_map[url]; + if (ws instanceof WebSocket) { + ws.send(JSON.stringify(data)); + } else { + this.post_data(url, data); + } + } + + async close_ws(url: string): Promise { + if (url in this.ws_map) { + const ws = this.ws_map[url]; + if (ws instanceof WebSocket) { + ws.close(); + delete this.ws_map[url]; + } + } + } +} + +/** + * @deprecated This method will be removed in v1.0. Use `Client.connect()` instead. + * Creates a client instance for interacting with Gradio apps. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app. + * @param {ClientOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export async function client( + app_reference: string, + options: ClientOptions = { + events: ["data"] + } +): Promise { + return await Client.connect(app_reference, options); +} + +/** + * @deprecated This method will be removed in v1.0. Use `Client.duplicate()` instead. + * Creates a duplicate of a space and returns a client instance for the duplicated space. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app to duplicate. + * @param {DuplicateOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export async function duplicate_space( + app_reference: string, + options: DuplicateOptions +): Promise { + return await Client.duplicate(app_reference, options); +} + +export type ClientInstance = Client; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/globals.d.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..126f284c8e845e8fe4d8b9e34fe9732e3478a31f --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/globals.d.ts @@ -0,0 +1,11 @@ +import { ApiData, ApiInfo, Config } from "./types"; + +declare global { + interface Window { + __gradio_mode__: "app" | "website"; + gradio_config: Config; + gradio_api_info: ApiInfo | { api: ApiInfo }; + __is_colab__: boolean; + __gradio_space__: string | null; + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/api_info.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/api_info.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3e5a655a2dc5991112b9d09642f4a3b16b0cdbe --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/api_info.ts @@ -0,0 +1,458 @@ +import { + HOST_URL, + INVALID_URL_MSG, + QUEUE_FULL_MSG, + SPACE_METADATA_ERROR_MSG +} from "../constants"; +import type { + ApiData, + ApiInfo, + Config, + JsApiData, + EndpointInfo, + Status +} from "../types"; +import { determine_protocol } from "./init_helpers"; + +export const RE_SPACE_NAME = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/; +export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/; + +export async function process_endpoint( + app_reference: string, + hf_token?: `hf_${string}` +): Promise<{ + space_id: string | false; + host: string; + ws_protocol: "ws" | "wss"; + http_protocol: "http:" | "https:"; +}> { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const _app_reference = app_reference.trim().replace(/\/$/, ""); + + if (RE_SPACE_NAME.test(_app_reference)) { + // app_reference is a HF space name + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${_app_reference}/${HOST_URL}`, + { headers } + ); + + const _host = (await res.json()).host; + + return { + space_id: app_reference, + ...determine_protocol(_host) + }; + } catch (e) { + throw new Error(SPACE_METADATA_ERROR_MSG); + } + } + + if (RE_SPACE_DOMAIN.test(_app_reference)) { + // app_reference is a direct HF space domain + const { ws_protocol, http_protocol, host } = + determine_protocol(_app_reference); + + return { + space_id: host.replace(".hf.space", ""), + ws_protocol, + http_protocol, + host + }; + } + + return { + space_id: false, + ...determine_protocol(_app_reference) + }; +} + +export const join_urls = (...urls: string[]): string => { + try { + return urls.reduce((base_url: string, part: string) => { + base_url = base_url.replace(/\/+$/, ""); + part = part.replace(/^\/+/, ""); + return new URL(part, base_url + "/").toString(); + }); + } catch (e) { + throw new Error(INVALID_URL_MSG); + } +}; + +export function transform_api_info( + api_info: ApiInfo, + config: Config, + api_map: Record +): ApiInfo { + const transformed_info: ApiInfo = { + named_endpoints: {}, + unnamed_endpoints: {} + }; + + Object.keys(api_info).forEach((category) => { + if (category === "named_endpoints" || category === "unnamed_endpoints") { + transformed_info[category] = {}; + + Object.entries(api_info[category]).forEach( + ([endpoint, { parameters, returns }]) => { + const dependencyIndex = + config.dependencies.find( + (dep) => + dep.api_name === endpoint || + dep.api_name === endpoint.replace("/", "") + )?.id || + api_map[endpoint.replace("/", "")] || + -1; + + const dependencyTypes = + dependencyIndex !== -1 + ? config.dependencies.find((dep) => dep.id == dependencyIndex) + ?.types + : { generator: false, cancel: false }; + + if ( + dependencyIndex !== -1 && + config.dependencies.find((dep) => dep.id == dependencyIndex)?.inputs + ?.length !== parameters.length + ) { + const components = config.dependencies + .find((dep) => dep.id == dependencyIndex)! + .inputs.map( + (input) => config.components.find((c) => c.id === input)?.type + ); + + try { + components.forEach((comp, idx) => { + if (comp === "state") { + const new_param = { + component: "state", + example: null, + parameter_default: null, + parameter_has_default: true, + parameter_name: null, + hidden: true + }; + + // @ts-ignore + parameters.splice(idx, 0, new_param); + } + }); + } catch (e) { + console.error(e); + } + } + + const transform_type = ( + data: ApiData, + component: string, + serializer: string, + signature_type: "return" | "parameter" + ): JsApiData => ({ + ...data, + description: get_description(data?.type, serializer), + type: + get_type(data?.type, component, serializer, signature_type) || "" + }); + + transformed_info[category][endpoint] = { + parameters: parameters.map((p: ApiData) => + transform_type(p, p?.component, p?.serializer, "parameter") + ), + returns: returns.map((r: ApiData) => + transform_type(r, r?.component, r?.serializer, "return") + ), + type: dependencyTypes + }; + } + ); + } + }); + + return transformed_info; +} + +export function get_type( + type: { type: any; description: string }, + component: string, + serializer: string, + signature_type: "return" | "parameter" +): string | undefined { + switch (type?.type) { + case "string": + return "string"; + case "boolean": + return "boolean"; + case "number": + return "number"; + } + + if ( + serializer === "JSONSerializable" || + serializer === "StringSerializable" + ) { + return "any"; + } else if (serializer === "ListStringSerializable") { + return "string[]"; + } else if (component === "Image") { + return signature_type === "parameter" ? "Blob | File | Buffer" : "string"; + } else if (serializer === "FileSerializable") { + if (type?.type === "array") { + return signature_type === "parameter" + ? "(Blob | File | Buffer)[]" + : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`; + } + return signature_type === "parameter" + ? "Blob | File | Buffer" + : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`; + } else if (serializer === "GallerySerializable") { + return signature_type === "parameter" + ? "[(Blob | File | Buffer), (string | null)][]" + : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`; + } +} + +export function get_description( + type: { type: any; description: string }, + serializer: string +): string { + if (serializer === "GallerySerializable") { + return "array of [file, label] tuples"; + } else if (serializer === "ListStringSerializable") { + return "array of strings"; + } else if (serializer === "FileSerializable") { + return "array of files or single file"; + } + return type?.description; +} + +/* eslint-disable complexity */ +export function handle_message( + data: any, + last_status: Status["stage"] +): { + type: + | "hash" + | "data" + | "update" + | "complete" + | "generating" + | "log" + | "none" + | "heartbeat" + | "streaming" + | "unexpected_error"; + data?: any; + status?: Status; + original_msg?: string; +} { + const queue = true; + switch (data.msg) { + case "send_data": + return { type: "data" }; + case "send_hash": + return { type: "hash" }; + case "queue_full": + return { + type: "update", + status: { + queue, + message: QUEUE_FULL_MSG, + stage: "error", + code: data.code, + success: data.success + } + }; + case "heartbeat": + return { + type: "heartbeat" + }; + case "unexpected_error": + return { + type: "unexpected_error", + status: { + queue, + message: data.message, + stage: "error", + success: false + } + }; + case "estimation": + return { + type: "update", + status: { + queue, + stage: last_status || "pending", + code: data.code, + size: data.queue_size, + position: data.rank, + eta: data.rank_eta, + success: data.success + } + }; + case "progress": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + progress_data: data.progress_data, + success: data.success + } + }; + case "log": + return { type: "log", data: data }; + case "process_generating": + return { + type: "generating", + status: { + queue, + message: !data.success ? data.output.error : null, + stage: data.success ? "generating" : "error", + code: data.code, + progress_data: data.progress_data, + eta: data.average_duration, + changed_state_ids: data.success + ? data.output.changed_state_ids + : undefined + }, + data: data.success ? data.output : null + }; + case "process_streaming": + return { + type: "streaming", + status: { + queue, + message: data.output.error, + stage: "streaming", + time_limit: data.time_limit, + code: data.code, + progress_data: data.progress_data, + eta: data.eta + }, + data: data.output + }; + case "process_completed": + if ("error" in data.output) { + return { + type: "update", + status: { + queue, + message: data.output.error as string, + visible: data.output.visible as boolean, + duration: data.output.duration as number, + stage: "error", + code: data.code, + success: data.success + } + }; + } + return { + type: "complete", + status: { + queue, + message: !data.success ? data.output.error : undefined, + stage: data.success ? "complete" : "error", + code: data.code, + progress_data: data.progress_data, + changed_state_ids: data.success + ? data.output.changed_state_ids + : undefined + }, + data: data.success ? data.output : null + }; + + case "process_starts": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + size: data.rank, + position: 0, + success: data.success, + eta: data.eta + }, + original_msg: "process_starts" + }; + } + + return { type: "none", status: { stage: "error", queue } }; +} +/* eslint-enable complexity */ + +/** + * Maps the provided `data` to the parameters defined by the `/info` endpoint response. + * This allows us to support both positional and keyword arguments passed to the client + * and ensures that all parameters are either directly provided or have default values assigned. + * + * @param {unknown[] | Record} data - The input data for the function, + * which can be either an array of values for positional arguments or an object + * with key-value pairs for keyword arguments. + * @param {JsApiData[]} parameters - Array of parameter descriptions retrieved from the + * `/info` endpoint. + * + * @returns {unknown[]} - Returns an array of resolved data where each element corresponds + * to the expected parameter from the API. The `parameter_default` value is used where + * a value is not provided for a parameter, and optional parameters without defaults are + * set to `undefined`. + * + * @throws {Error} - Throws an error: + * - If more arguments are provided than are defined in the parameters. + * * - If no parameter value is provided for a required parameter and no default value is defined. + * - If an argument is provided that does not match any defined parameter. + */ + +export const map_data_to_params = ( + data: unknown[] | Record = [], + endpoint_info: EndpointInfo +): unknown[] => { + // Workaround for the case where the endpoint_info is undefined + // See https://github.com/gradio-app/gradio/pull/8820#issuecomment-2237381761 + const parameters = endpoint_info ? endpoint_info.parameters : []; + + if (Array.isArray(data)) { + if (data.length > parameters.length) { + console.warn("Too many arguments provided for the endpoint."); + } + return data; + } + + const resolved_data: unknown[] = []; + const provided_keys = Object.keys(data); + + parameters.forEach((param, index) => { + if (data.hasOwnProperty(param.parameter_name)) { + resolved_data[index] = data[param.parameter_name]; + } else if (param.parameter_has_default) { + resolved_data[index] = param.parameter_default; + } else { + throw new Error( + `No value provided for required parameter: ${param.parameter_name}` + ); + } + }); + + provided_keys.forEach((key) => { + if (!parameters.some((param) => param.parameter_name === key)) { + throw new Error( + `Parameter \`${key}\` is not a valid keyword argument. Please refer to the API for usage.` + ); + } + }); + + resolved_data.forEach((value, idx) => { + if (value === undefined && !parameters[idx].parameter_has_default) { + throw new Error( + `No value provided for required parameter: ${parameters[idx].parameter_name}` + ); + } + }); + + return resolved_data; +}; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/data.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..a79cd2eb4d0ae659e4c283ca147cfcd32d3e91a2 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/data.ts @@ -0,0 +1,221 @@ +import { + type ApiData, + type BlobRef, + type Config, + type EndpointInfo, + type JsApiData, + type DataType, + Command, + type Dependency, + type ComponentMeta +} from "../types"; +import { FileData } from "../upload"; + +const is_node = + typeof process !== "undefined" && process.versions && process.versions.node; + +export function update_object( + object: { [x: string]: any }, + newValue: any, + stack: (string | number)[] +): void { + while (stack.length > 1) { + const key = stack.shift(); + if (typeof key === "string" || typeof key === "number") { + object = object[key]; + } else { + throw new Error("Invalid key type"); + } + } + + const key = stack.shift(); + if (typeof key === "string" || typeof key === "number") { + object[key] = newValue; + } else { + throw new Error("Invalid key type"); + } +} + +export async function walk_and_store_blobs( + data: DataType, + type: string | undefined = undefined, + path: string[] = [], + root = false, + endpoint_info: EndpointInfo | undefined = undefined +): Promise { + if (Array.isArray(data)) { + let blob_refs: BlobRef[] = []; + + await Promise.all( + data.map(async (_, index) => { + let new_path = path.slice(); + new_path.push(String(index)); + + const array_refs = await walk_and_store_blobs( + data[index], + root + ? endpoint_info?.parameters[index]?.component || undefined + : type, + new_path, + false, + endpoint_info + ); + + blob_refs = blob_refs.concat(array_refs); + }) + ); + + return blob_refs; + } else if ( + (globalThis.Buffer && data instanceof globalThis.Buffer) || + data instanceof Blob + ) { + return [ + { + path: path, + blob: new Blob([data]), + type + } + ]; + } else if (typeof data === "object" && data !== null) { + let blob_refs: BlobRef[] = []; + for (const key of Object.keys(data) as (keyof typeof data)[]) { + const new_path = [...path, key]; + const value = data[key]; + + blob_refs = blob_refs.concat( + await walk_and_store_blobs( + value, + undefined, + new_path, + false, + endpoint_info + ) + ); + } + + return blob_refs; + } + + return []; +} + +export function skip_queue(id: number, config: Config): boolean { + let fn_queue = config?.dependencies?.find((dep) => dep.id == id)?.queue; + if (fn_queue != null) { + return !fn_queue; + } + return !config.enable_queue; +} + +// todo: add jsdoc for this function + +export function post_message( + message: any, + origin: string +): Promise { + return new Promise((res, _rej) => { + const channel = new MessageChannel(); + channel.port1.onmessage = (({ data }) => { + channel.port1.close(); + res(data); + }) as (ev: MessageEvent) => void; + window.parent.postMessage(message, origin, [channel.port2]); + }); +} + +export function handle_file( + file_or_url: File | string | Blob | Buffer +): FileData | Blob | Command { + if (typeof file_or_url === "string") { + if ( + file_or_url.startsWith("http://") || + file_or_url.startsWith("https://") + ) { + return { + path: file_or_url, + url: file_or_url, + orig_name: file_or_url.split("/").pop() ?? "unknown", + meta: { _type: "gradio.FileData" } + }; + } + + if (is_node) { + // Handle local file paths + return new Command("upload_file", { + path: file_or_url, + name: file_or_url, + orig_path: file_or_url + }); + } + } else if (typeof File !== "undefined" && file_or_url instanceof File) { + return new Blob([file_or_url]); + } else if (file_or_url instanceof Buffer) { + return new Blob([file_or_url]); + } else if (file_or_url instanceof Blob) { + return file_or_url; + } + throw new Error( + "Invalid input: must be a URL, File, Blob, or Buffer object." + ); +} + +/** + * Handles the payload by filtering out state inputs and returning an array of resolved payload values. + * We send null values for state inputs to the server, but we don't want to include them in the resolved payload. + * + * @param resolved_payload - The resolved payload values received from the client or the server + * @param dependency - The dependency object. + * @param components - The array of component metadata. + * @param with_null_state - Optional. Specifies whether to include null values for state inputs. Default is false. + * @returns An array of resolved payload values, filtered based on the dependency and component metadata. + */ +export function handle_payload( + resolved_payload: unknown[], + dependency: Dependency, + components: ComponentMeta[], + type: "input" | "output", + with_null_state = false +): unknown[] { + if (type === "input" && !with_null_state) { + throw new Error("Invalid code path. Cannot skip state inputs for input."); + } + // data comes from the server with null state values so we skip + if (type === "output" && with_null_state) { + return resolved_payload; + } + + let updated_payload: unknown[] = []; + let payload_index = 0; + const deps = type === "input" ? dependency.inputs : dependency.outputs; + for (let i = 0; i < deps.length; i++) { + const input_id = deps[i]; + const component = components.find((c) => c.id === input_id); + + if (component?.type === "state") { + // input + with_null_state needs us to fill state with null values + if (with_null_state) { + if (resolved_payload.length === deps.length) { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; + } else { + updated_payload.push(null); + } + } else { + // this is output & !with_null_state, we skip state inputs + // the server payload always comes with null state values so we move along the payload index + payload_index++; + continue; + } + // input & !with_null_state isn't a case we care about, server needs null + continue; + } else { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; + } + } + + return updated_payload; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/init_helpers.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/init_helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..82b6fc1719d95240d52916ddd10da1b9c421420f --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/init_helpers.ts @@ -0,0 +1,226 @@ +import type { Config } from "../types"; +import { + CONFIG_ERROR_MSG, + CONFIG_URL, + INVALID_CREDENTIALS_MSG, + LOGIN_URL, + MISSING_CREDENTIALS_MSG, + SPACE_METADATA_ERROR_MSG, + UNAUTHORIZED_MSG +} from "../constants"; +import { Client } from ".."; +import { join_urls, process_endpoint } from "./api_info"; + +/** + * This function is used to resolve the URL for making requests when the app has a root path. + * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or + * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting + * Gradio apps on Hugging Face Spaces. + * @param {string} base_url The base URL at which the Gradio server is hosted + * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces) + * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized. + * @returns {string} the resolved URL + */ +export function resolve_root( + base_url: string, + root_path: string, + prioritize_base: boolean +): string { + if (root_path.startsWith("http://") || root_path.startsWith("https://")) { + return prioritize_base ? base_url : root_path; + } + return base_url + root_path; +} + +export async function get_jwt( + space: string, + token: `hf_${string}`, + cookies?: string | null +): Promise { + try { + const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, { + headers: { + Authorization: `Bearer ${token}`, + ...(cookies ? { Cookie: cookies } : {}) + } + }); + + const jwt = (await r.json()).token; + + return jwt || false; + } catch (e) { + return false; + } +} + +export function map_names_to_ids( + fns: Config["dependencies"] +): Record { + let apis: Record = {}; + + fns.forEach(({ api_name, id }) => { + if (api_name) apis[api_name] = id; + }); + return apis; +} + +export async function resolve_config( + this: Client, + endpoint: string +): Promise { + const headers: Record = this.options.hf_token + ? { Authorization: `Bearer ${this.options.hf_token}` } + : {}; + + headers["Content-Type"] = "application/json"; + + if ( + typeof window !== "undefined" && + window.gradio_config && + location.origin !== "http://localhost:9876" && + !window.gradio_config.dev_mode + ) { + const path = window.gradio_config.root; + const config = window.gradio_config; + let config_root = resolve_root(endpoint, config.root, false); + config.root = config_root; + return { ...config, path } as Config; + } else if (endpoint) { + const config_url = join_urls(endpoint, CONFIG_URL); + + const response = await this.fetch(config_url, { + headers, + credentials: "include" + }); + + if (response?.status === 401 && !this.options.auth) { + throw new Error(MISSING_CREDENTIALS_MSG); + } else if (response?.status === 401 && this.options.auth) { + throw new Error(INVALID_CREDENTIALS_MSG); + } + if (response?.status === 200) { + let config = await response.json(); + config.path = config.path ?? ""; + config.root = endpoint; + config.dependencies?.forEach((dep: any, i: number) => { + if (dep.id === undefined) { + dep.id = i; + } + }); + return config; + } else if (response?.status === 401) { + throw new Error(UNAUTHORIZED_MSG); + } + throw new Error(CONFIG_ERROR_MSG); + } + + throw new Error(CONFIG_ERROR_MSG); +} + +export async function resolve_cookies(this: Client): Promise { + const { http_protocol, host } = await process_endpoint( + this.app_reference, + this.options.hf_token + ); + + try { + if (this.options.auth) { + const cookie_header = await get_cookie_header( + http_protocol, + host, + this.options.auth, + this.fetch, + this.options.hf_token + ); + + if (cookie_header) this.set_cookies(cookie_header); + } + } catch (e: unknown) { + throw Error((e as Error).message); + } +} + +// separating this from client-bound resolve_cookies so that it can be used in duplicate +export async function get_cookie_header( + http_protocol: string, + host: string, + auth: [string, string], + _fetch: typeof fetch, + hf_token?: `hf_${string}` +): Promise { + const formData = new FormData(); + formData.append("username", auth?.[0]); + formData.append("password", auth?.[1]); + + let headers: { Authorization?: string } = {}; + + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const res = await _fetch(`${http_protocol}//${host}/${LOGIN_URL}`, { + headers, + method: "POST", + body: formData, + credentials: "include" + }); + + if (res.status === 200) { + return res.headers.get("set-cookie"); + } else if (res.status === 401) { + throw new Error(INVALID_CREDENTIALS_MSG); + } else { + throw new Error(SPACE_METADATA_ERROR_MSG); + } +} + +export function determine_protocol(endpoint: string): { + ws_protocol: "ws" | "wss"; + http_protocol: "http:" | "https:"; + host: string; +} { + if (endpoint.startsWith("http")) { + const { protocol, host, pathname } = new URL(endpoint); + + if (host.endsWith("hf.space")) { + return { + ws_protocol: "wss", + host: host, + http_protocol: protocol as "http:" | "https:" + }; + } + return { + ws_protocol: protocol === "https:" ? "wss" : "ws", + http_protocol: protocol as "http:" | "https:", + host: host + (pathname !== "/" ? pathname : "") + }; + } else if (endpoint.startsWith("file:")) { + // This case is only expected to be used for the Wasm mode (Gradio-lite), + // where users can create a local HTML file using it and open the page in a browser directly via the `file:` protocol. + return { + ws_protocol: "ws", + http_protocol: "http:", + host: "lite.local" // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`. + }; + } + + // default to secure if no protocol is provided + + return { + ws_protocol: "wss", + http_protocol: "https:", + host: new URL(endpoint).host + }; +} + +export const parse_and_set_cookies = (cookie_header: string): string[] => { + let cookies: string[] = []; + const parts = cookie_header.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/); + parts.forEach((cookie) => { + const [cookie_name, cookie_value] = cookie.split(";")[0].split("="); + if (cookie_name && cookie_value) { + cookies.push(`${cookie_name.trim()}=${cookie_value.trim()}`); + } + }); + return cookies; +}; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/spaces.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/spaces.ts new file mode 100644 index 0000000000000000000000000000000000000000..c290939c52a61f23a6f98e405f19f4235c08fa40 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/helpers/spaces.ts @@ -0,0 +1,252 @@ +import { + RUNTIME_URL, + SLEEPTIME_URL, + SPACE_STATUS_ERROR_MSG +} from "../constants"; +import { RE_SPACE_NAME } from "./api_info"; +import type { SpaceStatusCallback } from "../types"; + +export async function check_space_status( + id: string, + type: "subdomain" | "space_name", + status_callback: SpaceStatusCallback +): Promise { + let endpoint = + type === "subdomain" + ? `https://huggingface.co/api/spaces/by-subdomain/${id}` + : `https://huggingface.co/api/spaces/${id}`; + let response; + let _status; + try { + response = await fetch(endpoint); + _status = response.status; + if (_status !== 200) { + throw new Error(); + } + response = await response.json(); + } catch (e) { + status_callback({ + status: "error", + load_status: "error", + message: SPACE_STATUS_ERROR_MSG, + detail: "NOT_FOUND" + }); + return; + } + + if (!response || _status !== 200) return; + const { + runtime: { stage }, + id: space_name + } = response; + + switch (stage) { + case "STOPPED": + case "SLEEPING": + status_callback({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: stage + }); + + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1000); // poll for status + break; + case "PAUSED": + status_callback({ + 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: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + case "RUNNING": + case "RUNNING_BUILDING": + status_callback({ + status: "running", + load_status: "complete", + message: "Space is running.", + detail: stage + }); + break; + case "BUILDING": + status_callback({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: stage + }); + + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1000); + break; + case "APP_STARTING": + status_callback({ + status: "starting", + load_status: "pending", + message: "Space is starting...", + detail: stage + }); + + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1000); + break; + default: + status_callback({ + status: "space_error", + load_status: "error", + message: "This space is experiencing an issue.", + detail: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + } +} + +export const check_and_wake_space = async ( + space_id: string, + status_callback: SpaceStatusCallback +): Promise => { + let retries = 0; + const max_retries = 12; + const check_interval = 5000; + + return new Promise((resolve) => { + check_space_status( + space_id, + RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", + (status) => { + status_callback(status); + + if (status.status === "running") { + resolve(); + } else if ( + status.status === "error" || + status.status === "paused" || + status.status === "space_error" + ) { + resolve(); + } else if ( + status.status === "sleeping" || + status.status === "building" + ) { + if (retries < max_retries) { + retries++; + setTimeout(() => { + check_and_wake_space(space_id, status_callback).then(resolve); + }, check_interval); + } else { + resolve(); + } + } + } + ); + }); +}; + +const RE_DISABLED_DISCUSSION = + /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; +export async function discussions_enabled(space_id: string): Promise { + try { + const r = await fetch( + `https://huggingface.co/api/spaces/${space_id}/discussions`, + { + method: "HEAD" + } + ); + + const error = r.headers.get("x-error-message"); + + if (!r.ok || (error && RE_DISABLED_DISCUSSION.test(error))) return false; + return true; + } catch (e) { + return false; + } +} + +export async function get_space_hardware( + space_id: string, + hf_token?: `hf_${string}` | undefined +): Promise<(typeof hardware_types)[number]> { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${RUNTIME_URL}`, + { headers } + ); + + if (res.status !== 200) + throw new Error("Space hardware could not be obtained."); + + const { hardware } = await res.json(); + + return hardware.current; + } catch (e: any) { + throw new Error(e.message); + } +} + +export async function set_space_timeout( + space_id: string, + timeout: number, + hf_token?: `hf_${string}` +): Promise { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const body: { + seconds?: number; + } = { + seconds: timeout + }; + + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${SLEEPTIME_URL}`, + { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: JSON.stringify(body) + } + ); + + if (res.status !== 200) { + throw new 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." + ); + } + + const response = await res.json(); + return response; + } catch (e: any) { + throw new Error(e.message); + } +} + +export const hardware_types = [ + "cpu-basic", + "cpu-upgrade", + "cpu-xl", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a10g-largex2", + "a10g-largex4", + "a100-large", + "zero-a10g", + "h100", + "h100x8" +] as const; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ba30fc37a3e6865c6ae986e13f43364efbe568c --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/index.ts @@ -0,0 +1,23 @@ +export { Client } from "./client"; + +export { predict } from "./utils/predict"; +export { submit } from "./utils/submit"; +export { upload_files } from "./utils/upload_files"; +export { FileData, upload, prepare_files } from "./upload"; +export { handle_file } from "./helpers/data"; + +export type { + SpaceStatus, + StatusMessage, + Status, + client_return, + UploadResponse, + RenderMessage, + LogMessage, + Payload, + Config +} from "./types"; + +// todo: remove in @gradio/client v1.0 +export { client } from "./client"; +export { duplicate_space as duplicate } from "./client"; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/types.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac4f2b54721dbaf3ca56871fbc5c1d9378323a44 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/types.ts @@ -0,0 +1,392 @@ +// API Data Types + +import { hardware_types } from "./helpers/spaces"; +import type { SvelteComponent } from "svelte"; +import type { ComponentType } from "svelte"; + +export interface ApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: { + type: any; + description: string; + }; + component: string; + example_input?: any; + python_type: { type: string; description: string }; + serializer: string; +} + +export interface JsApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: string; + description: string; + component: string; + example_input?: any; + serializer: string; + python_type: { type: string; description: string }; +} + +export interface EndpointInfo { + parameters: T[]; + returns: T[]; + type?: DependencyTypes; +} + +export interface ApiInfo { + named_endpoints: Record>; + unnamed_endpoints: Record>; +} + +export interface BlobRef { + path: string[]; + type: string | undefined; + blob: Blob | File | false; +} + +export type DataType = string | Buffer | Record | any[]; + +// custom class used for uploading local files +export class Command { + type: string; + command: string; + meta: { + path: string; + name: string; + orig_path: string; + }; + fileData?: FileData; + + constructor( + command: string, + meta: { path: string; name: string; orig_path: string } + ) { + this.type = "command"; + this.command = command; + this.meta = meta; + } +} + +// Function Signature Types + +export type SubmitFunction = ( + endpoint: string | number, + data?: unknown[] | Record, + event_data?: unknown, + trigger_id?: number | null +) => SubmitIterable; + +export type PredictFunction = ( + endpoint: string | number, + data?: unknown[] | Record, + event_data?: unknown +) => Promise; + +export type client_return = { + config: Config | undefined; + predict: PredictFunction; + submit: SubmitFunction; + component_server: ( + component_id: number, + fn_name: string, + data: unknown[] + ) => any; + view_api: (_fetch: typeof fetch) => Promise>; +}; + +export interface SubmitIterable extends AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator; + cancel: () => Promise; + event_id: () => string; +} + +export type PredictReturn = { + type: EventType; + time: Date; + data: unknown; + endpoint: string; + fn_index: number; +}; + +// Space Status Types + +export type SpaceStatus = SpaceStatusNormal | SpaceStatusError; + +export interface SpaceStatusNormal { + status: + | "sleeping" + | "running" + | "building" + | "error" + | "stopped" + | "starting"; + detail: + | "SLEEPING" + | "RUNNING" + | "RUNNING_BUILDING" + | "BUILDING" + | "APP_STARTING" + | "NOT_FOUND"; + load_status: "pending" | "error" | "complete" | "generating"; + message: string; +} + +export interface SpaceStatusError { + status: "space_error" | "paused"; + detail: + | "NO_APP_FILE" + | "CONFIG_ERROR" + | "BUILD_ERROR" + | "RUNTIME_ERROR" + | "PAUSED"; + load_status: "error"; + message: string; + discussions_enabled: boolean; +} + +export type SpaceStatusCallback = (a: SpaceStatus) => void; + +// Configuration and Response Types +// -------------------------------- +export interface Config { + auth_required?: true; + analytics_enabled: boolean; + connect_heartbeat: boolean; + auth_message: string; + components: ComponentMeta[]; + css: string | null; + js: string | null; + head: string | null; + dependencies: Dependency[]; + dev_mode: boolean; + enable_queue: boolean; + show_error: boolean; + layout: any; + mode: "blocks" | "interface"; + root: string; + root_url?: string; + theme: string; + title: string; + version: string; + space_id: string | null; + is_space: boolean; + is_colab: boolean; + show_api: boolean; + stylesheets: string[]; + path: string; + protocol: "sse_v3" | "sse_v2.1" | "sse_v2" | "sse_v1" | "sse" | "ws"; + max_file_size?: number; + theme_hash?: number; + username: string | null; + api_prefix?: string; + fill_height?: boolean; + fill_width?: boolean; +} + +// todo: DRY up types +export interface ComponentMeta { + type: string; + id: number; + has_modes: boolean; + props: SharedProps; + instance: SvelteComponent; + component: ComponentType; + documentation?: Documentation; + children?: ComponentMeta[]; + parent?: ComponentMeta; + value?: any; + component_class_id: string; + key: string | number | null; + rendered_in?: number; +} + +interface SharedProps { + elem_id?: string; + elem_classes?: string[]; + components?: string[]; + server_fns?: string[]; + interactive: boolean; + [key: string]: unknown; + root_url?: string; +} + +export interface Documentation { + type?: TypeDescription; + description?: TypeDescription; + example_data?: string; +} + +interface TypeDescription { + input_payload?: string; + response_object?: string; + payload?: string; +} + +export interface Dependency { + id: number; + targets: [number, string][]; + inputs: number[]; + outputs: number[]; + backend_fn: boolean; + js: string | null; + scroll_to_output: boolean; + trigger: "click" | "load" | string; + max_batch_size: number; + show_progress: "full" | "minimal" | "hidden"; + frontend_fn: ((...args: unknown[]) => Promise) | null; + status?: string; + queue: boolean | null; + every: number | null; + batch: boolean; + api_name: string | null; + cancels: number[]; + types: DependencyTypes; + collects_event_data: boolean; + pending_request?: boolean; + trigger_after?: number; + trigger_only_on_success?: boolean; + trigger_mode: "once" | "multiple" | "always_last"; + final_event: Payload | null; + show_api: boolean; + zerogpu?: boolean; + rendered_in: number | null; + connection: "stream" | "sse"; + time_limit: number; + stream_every: number; + like_user_message: boolean; + event_specific_args: string[]; +} + +export interface DependencyTypes { + generator: boolean; + cancel: boolean; +} + +export interface Payload { + fn_index: number; + data: unknown[]; + time?: Date; + event_data?: unknown; + trigger_id?: number | null; +} + +export interface PostResponse { + error?: string; + [x: string]: any; +} + +export interface UploadResponse { + error?: string; + files?: string[]; +} + +// Client and File Handling Types + +export interface DuplicateOptions extends ClientOptions { + private?: boolean; + hardware?: (typeof hardware_types)[number]; + timeout?: number; +} + +export interface ClientOptions { + hf_token?: `hf_${string}`; + status_callback?: SpaceStatusCallback | null; + auth?: [string, string] | null; + with_null_state?: boolean; + events?: EventType[]; +} + +export interface FileData { + name: string; + orig_name?: string; + size?: number; + data: string; + blob?: File; + is_file?: boolean; + mime_type?: string; + alt_text?: string; +} + +// Event and Listener Types + +export type EventType = "data" | "status" | "log" | "render"; + +export interface EventMap { + data: PayloadMessage; + status: StatusMessage; + log: LogMessage; + render: RenderMessage; +} + +export type GradioEvent = { + [P in EventType]: EventMap[P]; +}[EventType]; + +export interface Log { + log: string; + level: "warning" | "info"; +} +export interface Render { + data: { + components: any[]; + layout: any; + dependencies: Dependency[]; + render_id: number; + }; +} + +export interface Status { + queue: boolean; + code?: string; + success?: boolean; + stage: "pending" | "error" | "complete" | "generating" | "streaming"; + duration?: number; + visible?: boolean; + broken?: boolean; + size?: number; + position?: number; + eta?: number; + message?: string; + progress_data?: { + progress: number | null; + index: number | null; + length: number | null; + unit: string | null; + desc: string | null; + }[]; + time?: Date; + changed_state_ids?: number[]; + time_limit?: number; +} + +export interface StatusMessage extends Status { + type: "status"; + endpoint: string; + fn_index: number; + original_msg?: string; +} + +export interface PayloadMessage extends Payload { + type: "data"; + endpoint: string; + fn_index: number; +} + +export interface LogMessage extends Log { + type: "log"; + endpoint: string; + fn_index: number; + duration: number | null; + visible: boolean; +} + +export interface RenderMessage extends Render { + type: "render"; + endpoint: string; + fn_index: number; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/upload.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/upload.ts new file mode 100644 index 0000000000000000000000000000000000000000..175093a2c40f81e52efe5ce4c3d5dc1b9aba922a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/upload.ts @@ -0,0 +1,109 @@ +import type { Client } from "./client"; + +export async function upload( + this: Client, + file_data: FileData[], + root_url: string, + upload_id?: string, + max_file_size?: number +): Promise<(FileData | null)[] | null> { + let files = (Array.isArray(file_data) ? file_data : [file_data]).map( + (file_data) => file_data.blob! + ); + + const oversized_files = files.filter( + (f) => f.size > (max_file_size ?? Infinity) + ); + if (oversized_files.length) { + throw new Error( + `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files + .map((f) => f.name) + .join(", ")}` + ); + } + + return await Promise.all( + await this.upload_files(root_url, files, upload_id).then( + async (response: { files?: string[]; error?: string }) => { + if (response.error) { + throw new Error(response.error); + } else { + if (response.files) { + return response.files.map((f, i) => { + const file = new FileData({ + ...file_data[i], + path: f, + url: `${root_url}${this.api_prefix}/file=${f}` + }); + return file; + }); + } + + return []; + } + } + ) + ); +} + +export async function prepare_files( + files: File[], + is_stream?: boolean +): Promise { + return files.map( + (f) => + new FileData({ + path: f.name, + orig_name: f.name, + blob: f, + size: f.size, + mime_type: f.type, + is_stream + }) + ); +} + +export class FileData { + path: string; + url?: string; + orig_name?: string; + size?: number; + blob?: File; + is_stream?: boolean; + mime_type?: string; + alt_text?: string; + b64?: string; + readonly meta = { _type: "gradio.FileData" }; + + constructor({ + path, + url, + orig_name, + size, + blob, + is_stream, + mime_type, + alt_text, + b64 + }: { + path: string; + url?: string; + orig_name?: string; + size?: number; + blob?: File; + is_stream?: boolean; + mime_type?: string; + alt_text?: string; + b64?: string; + }) { + this.path = path; + this.url = url; + this.orig_name = orig_name; + this.size = size; + this.blob = url ? undefined : blob; + this.is_stream = is_stream; + this.mime_type = mime_type; + this.alt_text = alt_text; + this.b64 = b64; + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/post_data.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/post_data.ts new file mode 100644 index 0000000000000000000000000000000000000000..53264a3c86f3083df3ff336c867b697e20a3f69e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/post_data.ts @@ -0,0 +1,38 @@ +import { BROKEN_CONNECTION_MSG } from "../constants"; +import type { PostResponse } from "../types"; +import { Client } from ".."; + +export async function post_data( + this: Client, + url: string, + body: unknown, + additional_headers?: any +): Promise<[PostResponse, number]> { + const headers: { + Authorization?: string; + "Content-Type": "application/json"; + } = { "Content-Type": "application/json" }; + if (this.options.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + try { + var response = await this.fetch(url, { + method: "POST", + body: JSON.stringify(body), + headers: { ...headers, ...additional_headers }, + credentials: "include" + }); + } catch (e) { + return [{ error: BROKEN_CONNECTION_MSG }, 500]; + } + let output: PostResponse; + let status: number; + try { + output = await response.json(); + status = response.status; + } catch (e) { + output = { error: `Could not parse server response: ${e}` }; + status = 500; + } + return [output, status]; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/predict.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/predict.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6eda5831a9e3c7f9e57d85e1ba140f4d854d9fb --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/predict.ts @@ -0,0 +1,51 @@ +import { Client } from "../client"; +import type { Dependency, PredictReturn } from "../types"; + +export async function predict( + this: Client, + endpoint: string | number, + data: unknown[] | Record = {} +): Promise { + let data_returned = false; + let status_complete = false; + let dependency: Dependency; + + if (!this.config) { + throw new Error("Could not resolve app config"); + } + + if (typeof endpoint === "number") { + dependency = this.config.dependencies.find((dep) => dep.id == endpoint)!; + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + dependency = this.config.dependencies.find( + (dep) => dep.id == this.api_map[trimmed_endpoint] + )!; + } + + return new Promise(async (resolve, reject) => { + const app = this.submit(endpoint, data, null, null, true); + let result: unknown; + + for await (const message of app) { + if (message.type === "data") { + if (status_complete) { + resolve(result as PredictReturn); + } + data_returned = true; + result = message; + } + + if (message.type === "status") { + if (message.stage === "error") reject(message); + if (message.stage === "complete") { + status_complete = true; + // if complete message comes after data, resolve here + if (data_returned) { + resolve(result as PredictReturn); + } + } + } + } + }); +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/stream.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..edfe5e555e8afe27b5f446b1729a7968edc5ab30 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/stream.ts @@ -0,0 +1,228 @@ +import { BROKEN_CONNECTION_MSG, SSE_URL } from "../constants"; +import type { Client } from "../client"; +import { stream } from "fetch-event-stream"; + +export async function open_stream(this: Client): Promise { + let { + event_callbacks, + unclosed_events, + pending_stream_messages, + stream_status, + config, + jwt + } = this; + + const that = this; + + if (!config) { + throw new Error("Could not resolve app config"); + } + + stream_status.open = true; + + let stream: EventSource | null = null; + let params = new URLSearchParams({ + session_hash: this.session_hash + }).toString(); + + let url = new URL(`${config.root}${this.api_prefix}/${SSE_URL}?${params}`); + + if (jwt) { + url.searchParams.set("__sign", jwt); + } + + stream = this.stream(url); + + if (!stream) { + console.warn("Cannot connect to SSE endpoint: " + url.toString()); + return; + } + + stream.onmessage = async function (event: MessageEvent) { + let _data = JSON.parse(event.data); + if (_data.msg === "close_stream") { + close_stream(stream_status, that.abort_controller); + return; + } + const event_id = _data.event_id; + if (!event_id) { + await Promise.all( + Object.keys(event_callbacks).map((event_id) => + event_callbacks[event_id](_data) + ) + ); + } else if (event_callbacks[event_id] && config) { + if ( + _data.msg === "process_completed" && + ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes( + config.protocol + ) + ) { + unclosed_events.delete(event_id); + } + let fn: (data: any) => void = event_callbacks[event_id]; + + if (typeof window !== "undefined" && typeof document !== "undefined") { + // fn(_data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See + setTimeout(fn, 0, _data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See https://github.com/gradio-app/gradio/pull/7055 + } else { + fn(_data); + } + } else { + if (!pending_stream_messages[event_id]) { + pending_stream_messages[event_id] = []; + } + pending_stream_messages[event_id].push(_data); + } + }; + stream.onerror = async function () { + await Promise.all( + Object.keys(event_callbacks).map((event_id) => + event_callbacks[event_id]({ + msg: "unexpected_error", + message: BROKEN_CONNECTION_MSG + }) + ) + ); + }; +} + +export function close_stream( + stream_status: { open: boolean }, + abort_controller: AbortController | null +): void { + if (stream_status) { + stream_status.open = false; + abort_controller?.abort(); + } +} + +export function apply_diff_stream( + pending_diff_streams: Record, + event_id: string, + data: any +): void { + let is_first_generation = !pending_diff_streams[event_id]; + if (is_first_generation) { + pending_diff_streams[event_id] = []; + data.data.forEach((value: any, i: number) => { + pending_diff_streams[event_id][i] = value; + }); + } else { + data.data.forEach((value: any, i: number) => { + let new_data = apply_diff(pending_diff_streams[event_id][i], value); + pending_diff_streams[event_id][i] = new_data; + data.data[i] = new_data; + }); + } +} + +export function apply_diff( + obj: any, + diff: [string, (number | string)[], any][] +): any { + diff.forEach(([action, path, value]) => { + obj = apply_edit(obj, path, action, value); + }); + + return obj; +} + +function apply_edit( + target: any, + path: (number | string)[], + action: string, + value: any +): any { + if (path.length === 0) { + if (action === "replace") { + return value; + } else if (action === "append") { + return target + value; + } + throw new Error(`Unsupported action: ${action}`); + } + + let current = target; + for (let i = 0; i < path.length - 1; i++) { + current = current[path[i]]; + } + + const last_path = path[path.length - 1]; + switch (action) { + case "replace": + current[last_path] = value; + break; + case "append": + current[last_path] += value; + break; + case "add": + if (Array.isArray(current)) { + current.splice(Number(last_path), 0, value); + } else { + current[last_path] = value; + } + break; + case "delete": + if (Array.isArray(current)) { + current.splice(Number(last_path), 1); + } else { + delete current[last_path]; + } + break; + default: + throw new Error(`Unknown action: ${action}`); + } + return target; +} + +export function readable_stream( + input: RequestInfo | URL, + init: RequestInit = {} +): EventSource { + const instance: EventSource & { readyState: number } = { + close: () => { + console.warn("Method not implemented."); + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + url: input.toString(), + withCredentials: false, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + addEventListener: () => { + throw new Error("Method not implemented."); + }, + dispatchEvent: () => { + throw new Error("Method not implemented."); + }, + removeEventListener: () => { + throw new Error("Method not implemented."); + } + }; + + stream(input, init) + .then(async (res) => { + instance.readyState = instance.OPEN; + try { + for await (const chunk of res) { + //@ts-ignore + instance.onmessage && instance.onmessage(chunk); + } + instance.readyState = instance.CLOSED; + } catch (e) { + instance.onerror && instance.onerror(e as Event); + instance.readyState = instance.CLOSED; + } + }) + .catch((e) => { + console.error(e); + instance.onerror && instance.onerror(e as Event); + instance.readyState = instance.CLOSED; + }); + + return instance as EventSource; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/submit.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/submit.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5863b478e45f98217b619198d111168090858d6 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/submit.ts @@ -0,0 +1,862 @@ +/* eslint-disable complexity */ +import type { + Status, + Payload, + GradioEvent, + JsApiData, + EndpointInfo, + ApiInfo, + Config, + Dependency, + SubmitIterable +} from "../types"; + +import { skip_queue, post_message, handle_payload } from "../helpers/data"; +import { resolve_root } from "../helpers/init_helpers"; +import { + handle_message, + map_data_to_params, + process_endpoint +} from "../helpers/api_info"; +import semiver from "semiver"; +import { + BROKEN_CONNECTION_MSG, + QUEUE_FULL_MSG, + SSE_URL, + SSE_DATA_URL, + RESET_URL, + CANCEL_URL +} from "../constants"; +import { apply_diff_stream, close_stream } from "./stream"; +import { Client } from "../client"; + +export function submit( + this: Client, + endpoint: string | number, + data: unknown[] | Record = {}, + event_data?: unknown, + trigger_id?: number | null, + all_events?: boolean +): SubmitIterable { + try { + const { hf_token } = this.options; + const { + fetch, + app_reference, + config, + session_hash, + api_info, + api_map, + stream_status, + pending_stream_messages, + pending_diff_streams, + event_callbacks, + unclosed_events, + post_data, + options, + api_prefix + } = this; + + const that = this; + + if (!api_info) throw new Error("No API found"); + if (!config) throw new Error("Could not resolve app config"); + + let { fn_index, endpoint_info, dependency } = get_endpoint_info( + api_info, + endpoint, + api_map, + config + ); + + let resolved_data = map_data_to_params(data, endpoint_info); + + let websocket: WebSocket; + let stream: EventSource | null; + let protocol = config.protocol ?? "ws"; + let event_id_final = ""; + let event_id_cb: () => string = () => event_id_final; + + const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint; + let payload: Payload; + let event_id: string | null = null; + let complete: Status | undefined | false = false; + let last_status: Record = {}; + let url_params = + typeof window !== "undefined" && typeof document !== "undefined" + ? new URLSearchParams(window.location.search).toString() + : ""; + + const events_to_publish = + options?.events?.reduce( + (acc, event) => { + acc[event] = true; + return acc; + }, + {} as Record + ) || {}; + + // event subscription methods + function fire_event(event: GradioEvent): void { + if (all_events || events_to_publish[event.type]) { + push_event(event); + } + } + + async function cancel(): Promise { + const _status: Status = { + stage: "complete", + queue: false, + time: new Date() + }; + complete = _status; + fire_event({ + ..._status, + type: "status", + endpoint: _endpoint, + fn_index: fn_index + }); + + let reset_request = {}; + let cancel_request = {}; + if (protocol === "ws") { + if (websocket && websocket.readyState === 0) { + websocket.addEventListener("open", () => { + websocket.close(); + }); + } else { + websocket.close(); + } + reset_request = { fn_index, session_hash }; + } else { + close_stream(stream_status, that.abort_controller); + close(); + reset_request = { event_id }; + cancel_request = { event_id, session_hash, fn_index }; + } + + try { + if (!config) { + throw new Error("Could not resolve app config"); + } + + if ("event_id" in cancel_request) { + await fetch(`${config.root}${api_prefix}/${CANCEL_URL}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(cancel_request) + }); + } + + await fetch(`${config.root}${api_prefix}/${RESET_URL}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(reset_request) + }); + } catch (e) { + console.warn( + "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable." + ); + } + } + + const resolve_heartbeat = async (config: Config): Promise => { + await this._resolve_hearbeat(config); + }; + + async function handle_render_config(render_config: any): Promise { + if (!config) return; + let render_id: number = render_config.render_id; + config.components = [ + ...config.components.filter((c) => c.props.rendered_in !== render_id), + ...render_config.components + ]; + config.dependencies = [ + ...config.dependencies.filter((d) => d.rendered_in !== render_id), + ...render_config.dependencies + ]; + const any_state = config.components.some((c) => c.type === "state"); + const any_unload = config.dependencies.some((d) => + d.targets.some((t) => t[1] === "unload") + ); + config.connect_heartbeat = any_state || any_unload; + await resolve_heartbeat(config); + fire_event({ + type: "render", + data: render_config, + endpoint: _endpoint, + fn_index + }); + } + + this.handle_blob(config.root, resolved_data, endpoint_info).then( + async (_payload) => { + let input_data = handle_payload( + _payload, + dependency, + config.components, + "input", + true + ); + payload = { + data: input_data || [], + event_data, + fn_index, + trigger_id + }; + if (skip_queue(fn_index, config)) { + fire_event({ + type: "status", + endpoint: _endpoint, + stage: "pending", + queue: false, + fn_index, + time: new Date() + }); + + post_data( + `${config.root}${api_prefix}/run${ + _endpoint.startsWith("/") ? _endpoint : `/${_endpoint}` + }${url_params ? "?" + url_params : ""}`, + { + ...payload, + session_hash + } + ) + .then(([output, status_code]: any) => { + const data = output.data; + if (status_code == 200) { + fire_event({ + type: "data", + endpoint: _endpoint, + fn_index, + data: handle_payload( + data, + dependency, + config.components, + "output", + options.with_null_state + ), + time: new Date(), + event_data, + trigger_id + }); + if (output.render_config) { + handle_render_config(output.render_config); + } + + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + stage: "complete", + eta: output.average_duration, + queue: false, + time: new Date() + }); + } else { + fire_event({ + type: "status", + stage: "error", + endpoint: _endpoint, + fn_index, + message: output.error, + queue: false, + time: new Date() + }); + } + }) + .catch((e) => { + fire_event({ + type: "status", + stage: "error", + message: e.message, + endpoint: _endpoint, + fn_index, + queue: false, + time: new Date() + }); + }); + } else if (protocol == "ws") { + const { ws_protocol, host } = await process_endpoint( + app_reference, + hf_token + ); + + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + + let url = new URL( + `${ws_protocol}://${resolve_root( + host, + config.path as string, + true + )}/queue/join${url_params ? "?" + url_params : ""}` + ); + + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + + websocket = new WebSocket(url); + + websocket.onclose = (evt) => { + if (!evt.wasClean) { + fire_event({ + type: "status", + stage: "error", + broken: true, + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } + }; + + websocket.onmessage = function (event) { + const _data = JSON.parse(event.data); + const { type, status, data } = handle_message( + _data, + last_status[fn_index] + ); + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + ...status + }); + if (status.stage === "error") { + websocket.close(); + } + } else if (type === "hash") { + websocket.send(JSON.stringify({ fn_index, session_hash })); + return; + } else if (type === "data") { + websocket.send(JSON.stringify({ ...payload, session_hash })); + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + duration: data.duration, + visible: data.visible, + fn_index + }); + } else if (type === "generating") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index, + event_data, + trigger_id + }); + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + websocket.close(); + } + } + }; + + // different ws contract for gradio versions older than 3.6.0 + //@ts-ignore + if (semiver(config.version || "2.0.0", "3.6") < 0) { + addEventListener("open", () => + websocket.send(JSON.stringify({ hash: session_hash })) + ); + } + } else if (protocol == "sse") { + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + var params = new URLSearchParams({ + fn_index: fn_index.toString(), + session_hash: session_hash + }).toString(); + let url = new URL( + `${config.root}${api_prefix}/${SSE_URL}?${ + url_params ? url_params + "&" : "" + }${params}` + ); + + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + + stream = this.stream(url); + + if (!stream) { + return Promise.reject( + new Error("Cannot connect to SSE endpoint: " + url.toString()) + ); + } + + stream.onmessage = async function (event: MessageEvent) { + const _data = JSON.parse(event.data); + const { type, status, data } = handle_message( + _data, + last_status[fn_index] + ); + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + ...status + }); + if (status.stage === "error") { + stream?.close(); + close(); + } + } else if (type === "data") { + let [_, status] = await post_data( + `${config.root}${api_prefix}/queue/data`, + { + ...payload, + session_hash, + event_id + } + ); + if (status !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + stream?.close(); + close(); + } + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + duration: data.duration, + visible: data.visible, + fn_index + }); + } else if (type === "generating" || type === "streaming") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index, + event_data, + trigger_id + }); + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + stream?.close(); + close(); + } + } + }; + } else if ( + protocol == "sse_v1" || + protocol == "sse_v2" || + protocol == "sse_v2.1" || + protocol == "sse_v3" + ) { + // latest API format. v2 introduces sending diffs for intermediate outputs in generative functions, which makes payloads lighter. + // v3 only closes the stream when the backend sends the close stream message. + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + let hostname = ""; + if ( + typeof window !== "undefined" && + typeof document !== "undefined" + ) { + hostname = window?.location?.hostname; + } + + let hfhubdev = "dev.spaces.huggingface.tech"; + const origin = hostname.includes(".dev.") + ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` + : `https://huggingface.co`; + + const is_iframe = + typeof window !== "undefined" && + typeof document !== "undefined" && + window.parent != window; + const is_zerogpu_space = dependency.zerogpu && config.space_id; + const zerogpu_auth_promise = + is_iframe && is_zerogpu_space + ? post_message("zerogpu-headers", origin) + : Promise.resolve(null); + const post_data_promise = zerogpu_auth_promise.then((headers) => { + return post_data( + `${config.root}${api_prefix}/${SSE_DATA_URL}?${url_params}`, + { + ...payload, + session_hash + }, + headers + ); + }); + post_data_promise.then(async ([response, status]: any) => { + if (status === 503) { + fire_event({ + type: "status", + stage: "error", + message: QUEUE_FULL_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else if (status !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else { + event_id = response.event_id as string; + event_id_final = event_id; + let callback = async function (_data: object): Promise { + try { + const { type, status, data, original_msg } = handle_message( + _data, + last_status[fn_index] + ); + + if (type == "heartbeat") { + return; + } + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + original_msg: original_msg, + ...status + }); + } else if (type === "complete") { + complete = status; + } else if (type == "unexpected_error") { + console.error("Unexpected error", status?.message); + fire_event({ + type: "status", + stage: "error", + message: + status?.message || "An Unexpected Error Occurred!", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + duration: data.duration, + visible: data.visible, + fn_index + }); + return; + } else if (type === "generating" || type === "streaming") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + if ( + data && + dependency.connection !== "stream" && + ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol) + ) { + apply_diff_stream(pending_diff_streams, event_id!, data); + } + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index + }); + if (data.render_config) { + await handle_render_config(data.render_config); + } + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + + close(); + } + } + + if ( + status?.stage === "complete" || + status?.stage === "error" + ) { + if (event_callbacks[event_id!]) { + delete event_callbacks[event_id!]; + } + if (event_id! in pending_diff_streams) { + delete pending_diff_streams[event_id!]; + } + } + } catch (e) { + console.error("Unexpected client exception", e); + fire_event({ + type: "status", + stage: "error", + message: "An Unexpected Error Occurred!", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) { + close_stream(stream_status, that.abort_controller); + stream_status.open = false; + close(); + } + } + }; + + if (event_id in pending_stream_messages) { + pending_stream_messages[event_id].forEach((msg) => + callback(msg) + ); + delete pending_stream_messages[event_id]; + } + // @ts-ignore + event_callbacks[event_id] = callback; + unclosed_events.add(event_id); + if (!stream_status.open) { + await this.open_stream(); + } + } + }); + } + } + ); + + let done = false; + const values: (IteratorResult | PromiseLike)[] = []; + const resolvers: (( + value: IteratorResult | PromiseLike + ) => void)[] = []; + + function close(): void { + done = true; + while (resolvers.length > 0) + (resolvers.shift() as (typeof resolvers)[0])({ + value: undefined, + done: true + }); + } + + function push( + data: { value: GradioEvent; done: boolean } | PromiseLike + ): void { + if (done) return; + if (resolvers.length > 0) { + (resolvers.shift() as (typeof resolvers)[0])(data); + } else { + values.push(data); + } + } + + function push_error(error: unknown): void { + push(thenable_reject(error)); + close(); + } + + function push_event(event: GradioEvent): void { + push({ value: event, done: false }); + } + + function next(): Promise> { + if (values.length > 0) + return Promise.resolve(values.shift() as (typeof values)[0]); + if (done) return Promise.resolve({ value: undefined, done: true }); + return new Promise((resolve) => resolvers.push(resolve)); + } + + const iterator = { + [Symbol.asyncIterator]: () => iterator, + next, + throw: async (value: unknown) => { + push_error(value); + return next(); + }, + return: async () => { + close(); + return next(); + }, + cancel, + event_id: event_id_cb + }; + + return iterator; + } catch (error) { + console.error("Submit function encountered an error:", error); + throw error; + } +} + +function thenable_reject(error: T): PromiseLike { + return { + then: ( + resolve: (value: never) => PromiseLike, + reject: (error: T) => PromiseLike + ) => reject(error) + }; +} + +function get_endpoint_info( + api_info: ApiInfo, + endpoint: string | number, + api_map: Record, + config: Config +): { + fn_index: number; + endpoint_info: EndpointInfo; + dependency: Dependency; +} { + let fn_index: number; + let endpoint_info: EndpointInfo; + let dependency: Dependency; + + if (typeof endpoint === "number") { + fn_index = endpoint; + endpoint_info = api_info.unnamed_endpoints[fn_index]; + dependency = config.dependencies.find((dep) => dep.id == endpoint)!; + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + + fn_index = api_map[trimmed_endpoint]; + endpoint_info = api_info.named_endpoints[endpoint.trim()]; + dependency = config.dependencies.find( + (dep) => dep.id == api_map[trimmed_endpoint] + )!; + } + + if (typeof fn_index !== "number") { + throw new Error( + "There is no endpoint matching that name of fn_index matching that number." + ); + } + return { fn_index, endpoint_info, dependency }; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/upload_files.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/upload_files.ts new file mode 100644 index 0000000000000000000000000000000000000000..6babe212bd4943013e93341e8ede61493f4978d3 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/upload_files.ts @@ -0,0 +1,52 @@ +import type { Client } from ".."; +import { BROKEN_CONNECTION_MSG, UPLOAD_URL } from "../constants"; +import type { UploadResponse } from "../types"; + +export async function upload_files( + this: Client, + root_url: string, + files: (Blob | File)[], + upload_id?: string +): Promise { + const headers: { + Authorization?: string; + } = {}; + if (this?.options?.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + + const chunkSize = 1000; + const uploadResponses = []; + let response: Response; + + for (let i = 0; i < files.length; i += chunkSize) { + const chunk = files.slice(i, i + chunkSize); + const formData = new FormData(); + chunk.forEach((file) => { + formData.append("files", file); + }); + try { + const upload_url = upload_id + ? `${root_url}${this.api_prefix}/${UPLOAD_URL}?upload_id=${upload_id}` + : `${root_url}${this.api_prefix}/${UPLOAD_URL}`; + + response = await this.fetch(upload_url, { + method: "POST", + body: formData, + headers, + credentials: "include" + }); + } catch (e) { + throw new Error(BROKEN_CONNECTION_MSG + (e as Error).message); + } + if (!response.ok) { + const error_text = await response.text(); + return { error: `HTTP ${response.status}: ${error_text}` }; + } + const output: UploadResponse["files"] = await response.json(); + if (output) { + uploadResponses.push(...output); + } + } + return { files: uploadResponses }; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/view_api.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/view_api.ts new file mode 100644 index 0000000000000000000000000000000000000000..52268bd745e3b0e5959b6e0b568e1cbb5d7540ce --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/utils/view_api.ts @@ -0,0 +1,71 @@ +import type { ApiInfo, ApiData } from "../types"; +import semiver from "semiver"; +import { API_INFO_URL, BROKEN_CONNECTION_MSG } from "../constants"; +import { Client } from "../client"; +import { SPACE_FETCHER_URL } from "../constants"; +import { join_urls, transform_api_info } from "../helpers/api_info"; + +export async function view_api(this: Client): Promise { + if (this.api_info) return this.api_info; + + const { hf_token } = this.options; + const { config } = this; + + const headers: { + Authorization?: string; + "Content-Type": "application/json"; + } = { "Content-Type": "application/json" }; + + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + if (!config) { + return; + } + + try { + let response: Response; + let api_info: ApiInfo | { api: ApiInfo }; + if (typeof window !== "undefined" && window.gradio_api_info) { + api_info = window.gradio_api_info; + } else { + if (semiver(config?.version || "2.0.0", "3.30") < 0) { + response = await this.fetch(SPACE_FETCHER_URL, { + method: "POST", + body: JSON.stringify({ + serialize: false, + config: JSON.stringify(config) + }), + headers, + credentials: "include" + }); + } else { + const url = join_urls(config.root, this.api_prefix, API_INFO_URL); + response = await this.fetch(url, { + headers, + credentials: "include" + }); + } + + if (!response.ok) { + throw new Error(BROKEN_CONNECTION_MSG); + } + api_info = await response.json(); + } + if ("api" in api_info) { + api_info = api_info.api; + } + + if ( + api_info.named_endpoints["/predict"] && + !api_info.unnamed_endpoints["0"] + ) { + api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"]; + } + + return transform_api_info(api_info, config, this.api_map); + } catch (e) { + "Could not get API info. " + (e as Error).message; + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/vite-env.d.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/vite-env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11f02fe2a0061d6e6e1f271b21da95423b448b32 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/tsconfig.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ddee6c503883f8c697dfd6e464a8cfbab3df3743 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/client/tsconfig.json @@ -0,0 +1,27 @@ +{ + "include": ["src/**/*"], + "exclude": ["src/**/*.test.ts", "src/**/*.node-test.ts"], + "compilerOptions": { + "allowJs": true, + "declaration": true, + "emitDeclarationOnly": true, + "outDir": "dist", + "declarationMap": true, + "module": "ESNext", + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + + /* Bundler */ + "moduleResolution": "bundler", + "skipDefaultLibCheck": true, + "allowImportingTsExtensions": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + + /* Linting */ + "strict": true + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..3d71cead10437149e745b77e891de8e46fe0db4e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/Index.svelte @@ -0,0 +1,159 @@ + + + + + + gradio.dispatch("clear_status", loading_status)} + /> + handle_value_change(e.detail)} + on:select={(e) => gradio.dispatch("select", e.detail)} + {wrap} + {datatype} + {latex_delimiters} + editable={interactive} + {max_height} + i18n={gradio.i18n} + {line_breaks} + {column_widths} + upload={(...args) => gradio.client.upload(...args)} + stream_handler={(...args) => gradio.client.stream(...args)} + /> + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..037b99f17df607860c94dfdebe04b0428c2e6998 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/package.json @@ -0,0 +1,52 @@ +{ + "name": "@gradio/dataframe", + "version": "0.11.2", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "private": false, + "main_changeset": true, + "main": "./Index.svelte", + "dependencies": { + "@gradio/atoms": "workspace:^", + "@gradio/button": "workspace:^", + "@gradio/client": "workspace:^", + "@gradio/markdown": "workspace:^", + "@gradio/statustracker": "workspace:^", + "@gradio/upload": "workspace:^", + "@gradio/utils": "workspace:^", + "@types/d3-dsv": "^3.0.0", + "@types/dompurify": "^3.0.2", + "@types/katex": "^0.16.0", + "d3-dsv": "^3.0.1", + "dequal": "^2.0.2", + "dompurify": "^3.0.3", + "katex": "^0.16.7", + "marked": "^12.0.0" + }, + "exports": { + ".": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + }, + "./example": { + "gradio": "./Example.svelte", + "svelte": "./dist/Example.svelte", + "types": "./dist/Example.svelte.d.ts" + }, + "./package.json": "./package.json" + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/dataframe" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Arrow.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Arrow.svelte new file mode 100644 index 0000000000000000000000000000000000000000..52000514b5a6116811da89e3f2fbdf2bb43531a0 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Arrow.svelte @@ -0,0 +1,10 @@ + + + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/CellMenu.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/CellMenu.svelte new file mode 100644 index 0000000000000000000000000000000000000000..9ba1aaa3093fbd362e390669877b2d4dade26434 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/CellMenu.svelte @@ -0,0 +1,111 @@ + + +
+ {#if !is_header} + + + {/if} + + +
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Example.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Example.svelte new file mode 100644 index 0000000000000000000000000000000000000000..d15d677ba1dac8ab8564a0fc042569ca1db407be --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Example.svelte @@ -0,0 +1,29 @@ + + +
+ {#each value.slice(0, 3) as row} + + {#each row.slice(0, 3) as cell} + + {/each} + {#if row.length > 3} + + {/if} + + {/each} + {#if value.length > 3} + + {#each Array(Math.min(4, value[0].length)) as _} + + {/each} + + {/if} +
{cell}...
...
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Table.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Table.svelte new file mode 100644 index 0000000000000000000000000000000000000000..a101e5b26149b034ba3f150d4ec657555ea623bd --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/Table.svelte @@ -0,0 +1,1235 @@ + + + set_cell_widths()} +/> + +
+ {#if label && label.length !== 0 && show_label} +

+ {label} +

+ {/if} +
handle_keydown(e)} + role="grid" + tabindex="0" + > + + {#if label && label.length !== 0} + + {/if} + + + {#each _headers as { value, id }, i (id)} + + {/each} + + + + + {#each max as { value, id }, j (id)} + + {/each} + + +
{label}
+
+ + +
+ + + +
+
+
+
+ +
+
+ blob_to_string(data_uri_to_blob(e.detail.data))} + bind:dragging + > + + {#if label && label.length !== 0} + {label} + {/if} + + {#each _headers as { value, id }, i (id)} + { + toggle_header_button(i); + }} + > +
+
+ edit_header(i)} + {select_on_focus} + header + {root} + /> + + + +
{ + event.stopPropagation(); + handle_sort(i); + }} + > + + + +
+
+ + {#if editable} + + {/if} +
+ + {/each} + + + + {#each item as { value, id }, j (id)} + start_edit(index, j)} + on:click={() => { + handle_cell_click(index, j); + toggle_cell_button(index, j); + }} + on:dblclick={() => start_edit(index, j)} + style:width="var(--cell-width-{j})" + style={styling?.[index]?.[j] || ""} + class:focus={dequal(selected, [index, j])} + class:menu-active={active_cell_menu && + active_cell_menu.row === index && + active_cell_menu.col === j} + > +
+ ((clear_on_focus = false), parent.focus())} + {clear_on_focus} + {root} + /> + {#if editable} + + {/if} +
+ + {/each} + +
+
+
+
+ +{#if active_cell_menu !== null} + add_row_at(active_cell_menu?.row ?? -1, "above")} + on_add_row_below={() => add_row_at(active_cell_menu?.row ?? -1, "below")} + on_add_column_left={() => add_col_at(active_cell_menu?.col ?? -1, "left")} + on_add_column_right={() => add_col_at(active_cell_menu?.col ?? -1, "right")} + /> +{/if} + +{#if active_header_menu !== null} + add_col_at(active_header_menu?.col ?? -1, "left")} + on_add_column_right={() => + add_col_at(active_header_menu?.col ?? -1, "right")} + /> +{/if} + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/VirtualTable.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/VirtualTable.svelte new file mode 100644 index 0000000000000000000000000000000000000000..ecc47252ef2bbe92f70f6ce583cd0a871d5ba532 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/VirtualTable.svelte @@ -0,0 +1,346 @@ + + + + + + + + + {#if visible.length && visible[0].data.length} + {#each visible as item (item.data[0].id)} + + Missing Table Row + + {/each} + {/if} + + + + +
+
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/utils.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..09d4e0940d01bd5b0b340ab20f613691443ffde0 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dataframe/shared/utils.ts @@ -0,0 +1,7 @@ +export type Headers = string[]; +export type Data = (string | number)[][]; +export type Datatype = "str" | "markdown" | "html" | "number" | "bool" | "date"; +export type Metadata = { + [key: string]: string[][] | null; +} | null; +export type HeadersWithIDs = { value: string; id: string }[]; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Example.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Example.svelte new file mode 100644 index 0000000000000000000000000000000000000000..fa3904233f98bbb4507c4894f8eac5b712f29ff9 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Example.svelte @@ -0,0 +1,5 @@ + + +{value || ""} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..65adfe6b037858c7235a00e0dc276d6c3a60ea2a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/datetime/Index.svelte @@ -0,0 +1,215 @@ + + + + + +
+ {label} +
+
+ { + if (evt.key === "Enter") { + submit_values(); + gradio.dispatch("submit"); + } + }} + on:blur={submit_values} + /> + {#if include_time} + { + const date = new Date(datevalue); + entered_value = format_date(date); + submit_values(); + }} + /> + {:else} + { + const date = new Date(datevalue); + entered_value = format_date(date); + submit_values(); + }} + /> + {/if} + + +
+
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Dropdown.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Dropdown.svelte new file mode 100644 index 0000000000000000000000000000000000000000..e64d72252f4a44ed9ccafbb024b0c1f0a7208d6f --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Dropdown.svelte @@ -0,0 +1,327 @@ + + +
+ {label} + +
+
+
+ + dispatch("key_up", { + key: e.key, + input_value: input_text + })} + on:blur={handle_blur} + on:focus={handle_focus} + readonly={!filterable} + /> + {#if !disabled} +
+ +
+ {/if} +
+
+ +
+
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Multiselect.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Multiselect.svelte new file mode 100644 index 0000000000000000000000000000000000000000..d94532b5f31e00cca21baf6aa4df55933931ab3d --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/Multiselect.svelte @@ -0,0 +1,421 @@ + + + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/utils.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..72c30f493fe168c0e10ade580d21683638bbc656 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/dropdown/shared/utils.ts @@ -0,0 +1,56 @@ +function positive_mod(n: number, m: number): number { + return ((n % m) + m) % m; +} + +export function handle_filter( + choices: [string, string | number][], + input_text: string +): number[] { + return choices.reduce((filtered_indices, o, index) => { + if ( + input_text ? o[0].toLowerCase().includes(input_text.toLowerCase()) : true + ) { + filtered_indices.push(index); + } + return filtered_indices; + }, [] as number[]); +} + +export function handle_change( + dispatch: any, + value: string | number | (string | number)[] | undefined, + value_is_output: boolean +): void { + dispatch("change", value); + if (!value_is_output) { + dispatch("input"); + } +} + +export function handle_shared_keys( + e: KeyboardEvent, + active_index: number | null, + filtered_indices: number[] +): [boolean, number | null] { + if (e.key === "Escape") { + return [false, active_index]; + } + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + if (filtered_indices.length >= 0) { + if (active_index === null) { + active_index = + e.key === "ArrowDown" + ? filtered_indices[0] + : filtered_indices[filtered_indices.length - 1]; + } else { + const index_in_filtered = filtered_indices.indexOf(active_index); + const increment = e.key === "ArrowUp" ? -1 : 1; + active_index = + filtered_indices[ + positive_mod(index_in_filtered + increment, filtered_indices.length) + ]; + } + } + } + return [true, active_index]; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/group/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/group/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..e8f3e66e5d8f60635c86044d9510966355de4f57 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/group/Index.svelte @@ -0,0 +1,43 @@ + + +
+
+ +
+
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/html/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/html/package.json new file mode 100644 index 0000000000000000000000000000000000000000..02ef95512988b333a609e93eed1868f284a613ef --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/html/package.json @@ -0,0 +1,45 @@ +{ + "name": "@gradio/html", + "version": "0.4.1", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "private": false, + "main_changeset": true, + "dependencies": { + "@gradio/atoms": "workspace:^", + "@gradio/statustracker": "workspace:^", + "@gradio/utils": "workspace:^", + "@gradio/icons": "workspace:^" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + }, + "./example": { + "gradio": "./Example.svelte", + "svelte": "./dist/Example.svelte", + "types": "./dist/Example.svelte.d.ts" + }, + "./base": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + } + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/html" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..66a19bfc9693fdc5b78bd6dac668b4c2fa375314 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/Index.svelte @@ -0,0 +1,87 @@ + + + + + + gradio.dispatch("clear_status", loading_status)} + /> +
+ gradio.dispatch("change")} + {latex_delimiters} + {sanitize_html} + {line_breaks} + {header_links} + {show_copy_button} + root={gradio.root} + {loading_status} + /> +
+
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/MarkdownCode.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/MarkdownCode.svelte new file mode 100644 index 0000000000000000000000000000000000000000..84ce5b6be141083e1db0ff4ed8158f999886e478 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/MarkdownCode.svelte @@ -0,0 +1,211 @@ + + + + {@html html} + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/prism-dark.css b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/prism-dark.css new file mode 100644 index 0000000000000000000000000000000000000000..892bd5932e145f876e009caf49f5a0c922b62e34 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/markdown/shared/prism-dark.css @@ -0,0 +1,68 @@ +.dark .md .token.comment, +.dark .md .token.prolog, +.dark .md .token.doctype, +.dark .md .token.cdata { + color: hsl(30, 20%, 50%); +} + +.dark .md .token.punctuation { + opacity: 0.7; +} + +.dark .md .token.namespace { + opacity: 0.7; +} + +.dark .md .token.property, +.dark .md .token.tag, +.dark .md .token.boolean, +.dark .md .token.number, +.dark .md .token.constant, +.dark .md .token.symbol { + color: hsl(350, 40%, 70%); +} + +.dark .md .token.selector, +.dark .md .token.attr-name, +.dark .md .token.string, +.dark .md .token.char, +.dark .md .token.builtin, +.dark .md .token.inserted { + color: hsl(75, 70%, 60%); +} + +.dark .md .token.operator, +.dark .md .token.entity, +.dark .md .token.url, +.dark .md .language-css .token.string, +.dark .md .style .token.string, +.dark .md .token.variable { + color: hsl(40, 90%, 60%); +} + +.dark .md .token.atrule, +.dark .md .token.attr-value, +.dark .md .token.keyword { + color: hsl(350, 40%, 70%); +} + +.dark .md .token.regex, +.dark .md .token.important { + color: #e90; +} + +.dark .md .token.important, +.dark .md .token.bold { + font-weight: bold; +} +.dark .md .token.italic { + font-style: italic; +} + +.dark .md .token.entity { + cursor: help; +} + +.dark .md .token.deleted { + color: red; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Example.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Example.svelte new file mode 100644 index 0000000000000000000000000000000000000000..3fca8a55b7662024980b942159dfac5a25f8d3f6 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Example.svelte @@ -0,0 +1,11 @@ + + +{#if title} + {title} +{:else} + {x} x {y} +{/if} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..20829000e1d29d09c9832358f8c0bd1b5fa5b487 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/Index.svelte @@ -0,0 +1,552 @@ + + + + {#if loading_status} + gradio.dispatch("clear_status", loading_status)} + /> + {/if} + {label} + {#if value && is_browser} +
+ + {#if caption} +

{caption}

+ {/if} + {:else} + + {/if} +
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/package.json new file mode 100644 index 0000000000000000000000000000000000000000..966d49911498db35935e47c063cd79706f45b0a5 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/nativeplot/package.json @@ -0,0 +1,44 @@ +{ + "name": "@gradio/nativeplot", + "version": "0.4.1", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "private": false, + "main_changeset": true, + "exports": { + ".": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + }, + "./example": { + "gradio": "./Example.svelte", + "svelte": "./dist/Example.svelte", + "types": "./dist/Example.svelte.d.ts" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@gradio/atoms": "workspace:^", + "@gradio/icons": "workspace:^", + "@gradio/statustracker": "workspace:^", + "@gradio/utils": "workspace:^", + "@gradio/theme": "workspace:^", + "vega": "^5.23.0", + "vega-embed": "^6.25.0", + "vega-lite": "^5.12.0" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/nativeplot" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/number/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/number/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..48562507d9bcb9fc5ecb1c60828bad801948adea --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/number/Index.svelte @@ -0,0 +1,131 @@ + + + + gradio.dispatch("clear_status", loading_status)} + /> + + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Example.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Example.svelte new file mode 100644 index 0000000000000000000000000000000000000000..1ebb90d67dd34c97304ad2f6b72ebc069c07af90 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Example.svelte @@ -0,0 +1,19 @@ + + +
+ {value ? value : ""} +
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..6f3d125630ad08a9683284e869403fc0380cdfd6 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpledropdown/Index.svelte @@ -0,0 +1,107 @@ + + + + {#if loading_status} + gradio.dispatch("clear_status", loading_status)} + /> + {/if} + + + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpletextbox/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpletextbox/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..5e8e3d82cc2b66c04538108c8dbbe531ba24086e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/simpletextbox/Index.svelte @@ -0,0 +1,130 @@ + + + + + + {#if loading_status} + gradio.dispatch("clear_status", loading_status)} + /> + {/if} + + + + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/Index.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/Index.svelte new file mode 100644 index 0000000000000000000000000000000000000000..dd6e12322ffd7bca12134d7459dec377c5c9f60a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/Index.svelte @@ -0,0 +1,67 @@ + + + + + gradio.dispatch("click")} + on:change={({ detail }) => handle_event(detail, "change")} + on:upload={({ detail }) => handle_event(detail, "upload")} + on:error={({ detail }) => { + gradio.dispatch("error", detail); + }} + upload={(...args) => gradio.client.upload(...args)} +> + {label ? gradio.i18n(label) : ""} + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dadad938aa88ceaa325183df07f9fc387f5e9b34 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/uploadbutton/package.json @@ -0,0 +1,36 @@ +{ + "name": "@gradio/uploadbutton", + "version": "0.7.1", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "private": false, + "main_changeset": true, + "exports": { + ".": { + "gradio": "./Index.svelte", + "svelte": "./dist/Index.svelte", + "types": "./dist/Index.svelte.d.ts" + }, + "./package.json": "./package.json" + }, + "main": "./Index.svelte", + "dependencies": { + "@gradio/button": "workspace:^", + "@gradio/client": "workspace:^", + "@gradio/upload": "workspace:^", + "@gradio/utils": "workspace:^" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/uploadbutton" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/color.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/color.ts new file mode 100644 index 0000000000000000000000000000000000000000..86d3fe6a5c35c450cc6517b5f3d4767ffda1bc2c --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/color.ts @@ -0,0 +1,5 @@ +import { colors, ordered_colors } from "@gradio/theme"; + +export const get_next_color = (index: number): keyof typeof colors => { + return ordered_colors[index % ordered_colors.length]; +}; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5119597e23cb0d4bca83b12e8c364864be644a8c --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/utils/src/index.ts @@ -0,0 +1,2 @@ +export * from "./color.js"; +export * from "./utils.js"; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb16e8563328d74fd0f3d96dd20e0ccd12a60bb8 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/index.ts @@ -0,0 +1,7 @@ +export { default as BaseInteractiveVideo } from "./shared/InteractiveVideo.svelte"; +export { default as BaseStaticVideo } from "./shared/VideoPreview.svelte"; +export { default as BasePlayer } from "./shared/Player.svelte"; +export { prettyBytes, playable, loaded } from "./shared/utils"; +export { default as BaseExample } from "./Example.svelte"; +import { default as Index } from "./Index.svelte"; +export default Index; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4c136d41752742d1b26a398abdc540e5dd1dea25 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/package.json @@ -0,0 +1,59 @@ +{ + "name": "@gradio/video", + "version": "0.11.2", + "description": "Gradio UI packages", + "type": "module", + "author": "", + "license": "ISC", + "private": false, + "dependencies": { + "@ffmpeg/ffmpeg": "^0.12.7", + "@ffmpeg/util": "^0.12.1", + "@gradio/atoms": "workspace:^", + "@gradio/client": "workspace:^", + "@gradio/icons": "workspace:^", + "@gradio/image": "workspace:^", + "@gradio/statustracker": "workspace:^", + "@gradio/upload": "workspace:^", + "@gradio/utils": "workspace:^", + "@gradio/wasm": "workspace:^", + "hls.js": "^1.5.13", + "mrmime": "^2.0.0" + }, + "devDependencies": { + "@gradio/preview": "workspace:^" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "gradio": "./index.ts", + "svelte": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "./example": { + "gradio": "./Example.svelte", + "svelte": "./dist/Example.svelte", + "types": "./dist/Example.svelte.d.ts" + }, + "./shared": { + "gradio": "./shared/index.ts", + "svelte": "./dist/shared/index.js", + "types": "./dist/shared/index.d.ts" + }, + "./base": { + "gradio": "./shared/VideoPreview.svelte", + "svelte": "./dist/shared/VideoPreview.svelte", + "types": "./dist/shared/VideoPreview.svelte.d.ts" + } + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "main": "index.ts", + "main_changeset": true, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/video" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/Video.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/Video.svelte new file mode 100644 index 0000000000000000000000000000000000000000..34aab69a913fbcbcba10e1fae606da21dde11a2f --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/Video.svelte @@ -0,0 +1,199 @@ + + + +
+ + + +
+ + + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/VideoTimeline.svelte b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/VideoTimeline.svelte new file mode 100644 index 0000000000000000000000000000000000000000..dcc7ea2ab503f7cfe4ebfc455d0bcb2bf073eb64 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/VideoTimeline.svelte @@ -0,0 +1,279 @@ + + +
+ {#if loadingTimeline} +
+ +
+ {:else} +
+
+ {/if} +
+ + diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..979dcd6831de9101415b198eba0ad286d658211a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/index.ts @@ -0,0 +1 @@ +export { default as Video } from "./Video.svelte"; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/utils.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..89a85de68f9e755fd214ac6d878c04734c501a0e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/video/shared/utils.ts @@ -0,0 +1,146 @@ +import { toBlobURL } from "@ffmpeg/util"; +import { FFmpeg } from "@ffmpeg/ffmpeg"; +import { lookup } from "mrmime"; + +export const prettyBytes = (bytes: number): string => { + let units = ["B", "KB", "MB", "GB", "PB"]; + let i = 0; + while (bytes > 1024) { + bytes /= 1024; + i++; + } + let unit = units[i]; + return bytes.toFixed(1) + " " + unit; +}; + +export const playable = (): boolean => { + // TODO: Fix this + // let video_element = document.createElement("video"); + // let mime_type = mime.lookup(filename); + // return video_element.canPlayType(mime_type) != ""; + return true; // FIX BEFORE COMMIT - mime import causing issues +}; + +export function loaded( + node: HTMLVideoElement, + { autoplay }: { autoplay: boolean } +): any { + async function handle_playback(): Promise { + if (!autoplay) return; + await node.play(); + } + + node.addEventListener("loadeddata", handle_playback); + + return { + destroy(): void { + node.removeEventListener("loadeddata", handle_playback); + } + }; +} + +export default async function loadFfmpeg(): Promise { + const ffmpeg = new FFmpeg(); + const baseURL = "https://unpkg.com/@ffmpeg/core@0.12.4/dist/esm"; + + await ffmpeg.load({ + coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"), + wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm") + }); + + return ffmpeg; +} + +export function blob_to_data_url(blob: Blob): Promise { + return new Promise((fulfill, reject) => { + let reader = new FileReader(); + reader.onerror = reject; + reader.onload = () => fulfill(reader.result as string); + reader.readAsDataURL(blob); + }); +} + +export async function trimVideo( + ffmpeg: FFmpeg, + startTime: number, + endTime: number, + videoElement: HTMLVideoElement +): Promise { + const videoUrl = videoElement.src; + const mimeType = lookup(videoElement.src) || "video/mp4"; + const blobUrl = await toBlobURL(videoUrl, mimeType); + const response = await fetch(blobUrl); + const vidBlob = await response.blob(); + const type = getVideoExtensionFromMimeType(mimeType) || "mp4"; + const inputName = `input.${type}`; + const outputName = `output.${type}`; + + try { + if (startTime === 0 && endTime === 0) { + return vidBlob; + } + + await ffmpeg.writeFile( + inputName, + new Uint8Array(await vidBlob.arrayBuffer()) + ); + + let command = [ + "-i", + inputName, + ...(startTime !== 0 ? ["-ss", startTime.toString()] : []), + ...(endTime !== 0 ? ["-to", endTime.toString()] : []), + "-c:a", + "copy", + outputName + ]; + + await ffmpeg.exec(command); + const outputData = await ffmpeg.readFile(outputName); + const outputBlob = new Blob([outputData], { + type: `video/${type}` + }); + + return outputBlob; + } catch (error) { + console.error("Error initializing FFmpeg:", error); + return vidBlob; + } +} + +const getVideoExtensionFromMimeType = (mimeType: string): string | null => { + const videoMimeToExtensionMap: { [key: string]: string } = { + "video/mp4": "mp4", + "video/webm": "webm", + "video/ogg": "ogv", + "video/quicktime": "mov", + "video/x-msvideo": "avi", + "video/x-matroska": "mkv", + "video/mpeg": "mpeg", + "video/3gpp": "3gp", + "video/3gpp2": "3g2", + "video/h261": "h261", + "video/h263": "h263", + "video/h264": "h264", + "video/jpeg": "jpgv", + "video/jpm": "jpm", + "video/mj2": "mj2", + "video/mpv": "mpv", + "video/vnd.ms-playready.media.pyv": "pyv", + "video/vnd.uvvu.mp4": "uvu", + "video/vnd.vivo": "viv", + "video/x-f4v": "f4v", + "video/x-fli": "fli", + "video/x-flv": "flv", + "video/x-m4v": "m4v", + "video/x-ms-asf": "asf", + "video/x-ms-wm": "wm", + "video/x-ms-wmv": "wmv", + "video/x-ms-wmx": "wmx", + "video/x-ms-wvx": "wvx", + "video/x-sgi-movie": "movie", + "video/x-smv": "smv" + }; + + return videoMimeToExtensionMap[mimeType] || null; +}; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/network/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/network/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6bfcf3608444774feb7c5ae1fda9c7a5bc6d361 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/network/index.ts @@ -0,0 +1 @@ +export * from "./host"; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/package.json b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aaab828171836c252e06de4e9ff7e4be973ee781 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/package.json @@ -0,0 +1,49 @@ +{ + "name": "@gradio/wasm", + "version": "0.14.1", + "description": "Gradio Wasm package", + "type": "module", + "main": "./dist/src/index.js", + "exports": { + ".": { + "gradio": "./src/index.ts", + "import": "./dist/src/index.js", + "types": "./dist/src/index.d.ts" + }, + "./package.json": "./package.json", + "./svelte": { + "gradio": "./svelte/index.ts", + "svelte": "./dist/svelte/index.js", + "types": "./dist/svelte/index.d.ts" + }, + "./network": { + "import": "./network/index.ts", + "types": "./dist/network/index.d.ts" + } + }, + "keywords": [], + "author": "", + "license": "ISC", + "main_changeset": true, + "scripts": { + "dev:client": "tsc -w --incremental", + "dev:worker": "vite build --config vite.worker.config.js --watch --emptyOutDir=false", + "dev": "run-p dev:*", + "build:client": "svelte-package --input=. --cwd=../../.config/", + "build:worker": "vite build --config vite.worker.config.js", + "build": "run-s build:client build:worker" + }, + "dependencies": { + "@types/path-browserify": "^1.0.0", + "path-browserify": "^1.0.1", + "pyodide": "0.26.1" + }, + "peerDependencies": { + "svelte": "^4.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gradio-app/gradio.git", + "directory": "js/wasm" + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/asgi-types.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/asgi-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a50c61578af3cc1624799c3ddf585b4058245e0 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/asgi-types.ts @@ -0,0 +1,37 @@ +import type { PyProxy } from "pyodide/ffi"; + +// A reference to an ASGI application instance in Python +// Ref: https://asgi.readthedocs.io/en/latest/specs/main.html#applications +export type ASGIScope = Record; +export type ASGIApplication = ( + scope: ASGIScope, + receive: () => Promise, + send: (event: PyProxy) => Promise // `event` is a `SendEvent` dict in Python and passed as a `PyProxy` in JS via Pyodide's type conversion (https://pyodide.org/en/stable/usage/type-conversions.html#type-translations-pyproxy-to-js). +) => Promise; + +export type ReceiveEvent = RequestReceiveEvent | DisconnectReceiveEvent; +// https://asgi.readthedocs.io/en/latest/specs/www.html#request-receive-event +export interface RequestReceiveEvent { + type: "http.request"; + body?: Uint8Array; // `bytes` in Python + more_body?: boolean; +} +// https://asgi.readthedocs.io/en/latest/specs/www.html#disconnect-receive-event +export interface DisconnectReceiveEvent { + type: "http.disconnect"; +} + +export type SendEvent = ResponseStartSendEvent | ResponseBodySendEvent; +// https://asgi.readthedocs.io/en/latest/specs/www.html#response-start-send-event +export interface ResponseStartSendEvent { + type: "http.response.start"; + status: number; + headers: Iterable<[Uint8Array, Uint8Array]>; + trailers: boolean; +} +// https://asgi.readthedocs.io/en/latest/specs/www.html#response-body-send-event +export interface ResponseBodySendEvent { + type: "http.response.body"; + body: Uint8Array; // `bytes` in Python + more_body: boolean; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/cross-origin-worker.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/cross-origin-worker.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a6b257d092ebcc230acadcafebb14e9fb9a88e9 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/cross-origin-worker.ts @@ -0,0 +1,62 @@ +// A hack to load a worker script from a different origin. +// Vite's built-in Web Workers feature does not support inlining the worker code +// into the main bundle and always emits it to a separate file, +// which is not compatible with the cross-origin worker. +// So we use this hack to load the separate worker code from a domain different from the parent page. +// Vite deals with the special syntax `new Worker(new URL("worker.ts", import.meta.url))` for the worker build, +// so this `CrossOriginWorkerMaker` class must be defined in a separate file and +// be imported as the `Worker` alias into the file where the syntax is used to load the worker. +// This implementation was based on https://github.com/whitphx/stlite/blob/v0.34.0/packages/kernel/src/kernel.ts, +// and this technique was introduced originally for Webpack at https://github.com/webpack/webpack/discussions/14648#discussioncomment-1589272 + +// Caching is important not only for performance but also for ensuring that the same blob URL is used for the same requested URL. +const worker_blob_url_cache = new Map(); +function get_blob_url(url: URL): string { + const cached_worker_blob_url = worker_blob_url_cache.get(url.toString()); + if (cached_worker_blob_url) { + console.debug(`Reusing the cached worker blob URL for ${url.toString()}.`); + return cached_worker_blob_url; + } + + const worker_blob = new Blob([`importScripts("${url.toString()}");`], { + type: "text/javascript" + }); + const worker_blob_url = URL.createObjectURL(worker_blob); + worker_blob_url_cache.set(url.toString(), worker_blob_url); + return worker_blob_url; +} + +function is_same_origin(url: URL): boolean { + return url.origin === window.location.origin; +} + +export class CrossOriginWorkerMaker { + public readonly worker: Worker | SharedWorker; + + constructor(url: URL, options?: WorkerOptions & { shared?: boolean }) { + const { shared = false, ...workerOptions } = options ?? {}; + + if (is_same_origin(url)) { + console.debug( + `Loading a worker script from the same origin: ${url.toString()}.` + ); + // This is the normal way to load a worker script, which is the best straightforward if possible. + this.worker = shared + ? new SharedWorker(url, workerOptions) + : new Worker(url, workerOptions); + + // NOTE: We use here `if-else` checking the origin instead of `try-catch` + // because the `try-catch` approach doesn't work on some browsers like FireFox. + // In the cross-origin case, FireFox throws a SecurityError asynchronously after the worker is created, + // so we can't catch the error synchronously. + } else { + console.debug( + `Loading a worker script from a different origin: ${url.toString()}.` + ); + const worker_blob_url = get_blob_url(url); + this.worker = shared + ? new SharedWorker(worker_blob_url, workerOptions) + : new Worker(worker_blob_url, workerOptions); + } + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/http.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/http.ts new file mode 100644 index 0000000000000000000000000000000000000000..37e07f347ba3fcec6e882cc7c8db4665407d167e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/http.ts @@ -0,0 +1,77 @@ +export interface HttpRequest { + method: "GET" | "POST" | "PUT" | "DELETE"; + path: string; + query_string: string; // This field must not contain the leading `?`, as it's directly used in the ASGI spec which requires this. + headers: Record; + body?: Uint8Array | ReadableStream | null; +} +export interface HttpResponse { + status: number; + headers: Record; + body: Uint8Array; +} + +// Inspired by https://github.com/rstudio/shinylive/blob/v0.1.2/src/messageporthttp.ts +export function headersToASGI( + headers: HttpRequest["headers"] +): [string, string][] { + const result: [string, string][] = []; + for (const [key, value] of Object.entries(headers)) { + result.push([key, value]); + } + return result; +} + +export function uint8ArrayToString(buf: Uint8Array): string { + let result = ""; + for (let i = 0; i < buf.length; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + +export function asgiHeadersToRecord(headers: any): Record { + headers = headers.map(([key, val]: [Uint8Array, Uint8Array]) => { + return [uint8ArrayToString(key), uint8ArrayToString(val)]; + }); + return Object.fromEntries(headers); +} + +export function getHeaderValue( + headers: HttpRequest["headers"], + key: string +): string | undefined { + // The keys in `headers` are case-insensitive. + const unifiedKey = key.toLowerCase(); + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === unifiedKey) { + return v; + } + } +} + +export function logHttpReqRes( + request: HttpRequest, + response: HttpResponse +): void { + if (Math.floor(response.status / 100) !== 2) { + let bodyText: string; + let bodyJson: unknown; + try { + bodyText = new TextDecoder().decode(response.body); + } catch (e) { + bodyText = "(failed to decode body)"; + } + try { + bodyJson = JSON.parse(bodyText); + } catch (e) { + bodyJson = "(failed to parse body as JSON)"; + } + console.error("Wasm HTTP error", { + request, + response, + bodyText, + bodyJson + }); + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/promise-delegate.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/promise-delegate.ts new file mode 100644 index 0000000000000000000000000000000000000000..1501900a0f1b2a14628eba448eec3c5c95fd4588 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/promise-delegate.ts @@ -0,0 +1,26 @@ +type PromiseImplFn = ConstructorParameters>[0]; + +export class PromiseDelegate { + promiseInternal: Promise; + resolveInternal!: Parameters>[0]; + rejectInternal!: Parameters>[1]; + + constructor() { + this.promiseInternal = new Promise((resolve, reject) => { + this.resolveInternal = resolve; + this.rejectInternal = reject; + }); + } + + get promise(): Promise { + return this.promiseInternal; + } + + public resolve(value: T): void { + this.resolveInternal(value); + } + + public reject(reason: unknown): void { + this.rejectInternal(reason); + } +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/webworker/requirements.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/webworker/requirements.ts new file mode 100644 index 0000000000000000000000000000000000000000..de45cdf388a6289fc26aeaa3e12d59ac61bd54f2 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/webworker/requirements.ts @@ -0,0 +1,18 @@ +export function verifyRequirements(requirements: string[]): void { + requirements.forEach((req) => { + let url: URL; + try { + url = new URL(req); + } catch { + // `req` is not a URL -> OK + return; + } + + // Ref: The scheme checker in the micropip implementation is https://github.com/pyodide/micropip/blob/v0.1.0/micropip/_compat_in_pyodide.py#L23-L26 + if (url.protocol === "emfs:" || url.protocol === "file:") { + throw new Error( + `"emfs:" and "file:" protocols are not allowed for the requirement (${req})` + ); + } + }); +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/worker-proxy.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/worker-proxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..03304ba173f1bfca19775ab8dcaad2c94800eb61 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/src/worker-proxy.ts @@ -0,0 +1,353 @@ +import { CrossOriginWorkerMaker as Worker } from "./cross-origin-worker"; +import type { + EmscriptenFile, + EmscriptenFileUrl, + InMessage, + InMessageAsgiRequest, + OutMessage, + ReplyMessage +} from "./message-types"; +import { PromiseDelegate } from "./promise-delegate"; +import { + type HttpRequest, + type HttpResponse, + asgiHeadersToRecord, + headersToASGI, + logHttpReqRes +} from "./http"; +import type { ASGIScope, ReceiveEvent, SendEvent } from "./asgi-types"; + +export interface WorkerProxyOptions { + gradioWheelUrl: string; + gradioClientWheelUrl: string; + files: Record; + requirements: string[]; + sharedWorkerMode: boolean; +} + +export class WorkerProxy extends EventTarget { + worker: globalThis.Worker | globalThis.SharedWorker; + postMessageTarget: globalThis.Worker | MessagePort; + firstRunPromiseDelegate = new PromiseDelegate(); + + constructor(options: WorkerProxyOptions) { + super(); + + const sharedWorkerMode = options.sharedWorkerMode; + + console.debug("WorkerProxy.constructor(): Create a new worker."); + // Loading a worker here relies on Vite's support for WebWorkers (https://vitejs.dev/guide/features.html#web-workers), + // assuming that this module is imported from the Gradio frontend (`@gradio/lite`), which is bundled with Vite. + // HACK: Use `CrossOriginWorkerMaker` imported as `Worker` here. + // Read the comment in `cross-origin-worker.ts` for the detail. + const workerMaker = new Worker( + new URL("../webworker/webworker.js", import.meta.url), + { + /* @vite-ignore */ shared: sharedWorkerMode // `@vite-ignore` is needed to avoid an error `Vite is unable to parse the worker options as the value is not static.` + } + ); + + this.worker = workerMaker.worker; + if (sharedWorkerMode) { + this.postMessageTarget = (this.worker as SharedWorker).port; + this.postMessageTarget.start(); + this.postMessageTarget.onmessage = (e) => { + this._processWorkerMessage(e.data); + }; + } else { + this.postMessageTarget = this.worker as globalThis.Worker; + + (this.worker as globalThis.Worker).onmessage = (e) => { + this._processWorkerMessage(e.data); + }; + } + + this.postMessageAsync({ + type: "init-env", + data: { + gradioWheelUrl: options.gradioWheelUrl, + gradioClientWheelUrl: options.gradioClientWheelUrl + } + }) + .then(() => { + console.debug( + "WorkerProxy.constructor(): Environment initialization is done." + ); + }) + .catch((error) => { + console.error( + "WorkerProxy.constructor(): Initialization failed.", + error + ); + this.dispatchEvent( + new CustomEvent("initialization-error", { + detail: error + }) + ); + }); + + this.postMessageAsync({ + type: "init-app", + data: { + files: options.files, + requirements: options.requirements + } + }) + .then(() => { + this.dispatchEvent( + new CustomEvent("initialization-completed", { + detail: null + }) + ); + }) + .catch((error) => { + console.error( + "WorkerProxy.constructor(): Initialization failed.", + error + ); + this.dispatchEvent( + new CustomEvent("initialization-error", { + detail: error + }) + ); + }); + } + + public async runPythonCode(code: string): Promise { + await this.postMessageAsync({ + type: "run-python-code", + data: { + code + } + }); + this.firstRunPromiseDelegate.resolve(); + } + + public async runPythonFile(path: string): Promise { + await this.postMessageAsync({ + type: "run-python-file", + data: { + path + } + }); + this.firstRunPromiseDelegate.resolve(); + } + + // A wrapper for this.worker.postMessage(). Unlike that function, which + // returns void immediately, this function returns a promise, which resolves + // when a ReplyMessage is received from the worker. + // The original implementation is in https://github.com/rstudio/shinylive/blob/v0.1.2/src/pyodide-proxy.ts#L404-L418 + postMessageAsync(msg: InMessage): Promise { + return new Promise((resolve, reject) => { + const channel = new MessageChannel(); + + channel.port1.onmessage = (e) => { + channel.port1.close(); + const msg = e.data as ReplyMessage; + if (msg.type === "reply:error") { + reject(msg.error); + return; + } + + resolve(msg.data); + }; + + this.postMessageTarget.postMessage(msg, [channel.port2]); + }); + } + + _processWorkerMessage(msg: OutMessage): void { + switch (msg.type) { + case "progress-update": { + this.dispatchEvent( + new CustomEvent("progress-update", { + detail: msg.data.log + }) + ); + break; + } + } + } + + // Initialize an ASGI protocol connection with the ASGI app. + // The returned `MessagePort` is used to communicate with the ASGI app + // via the `postMessage()` API and the `message` event. + // `postMessage()` sends a `ReceiveEvent` to the ASGI app (Be careful not to send a `SendEvent`. This is an event the ASGI app "receives".) + // The ASGI app sends a `SendEvent` to the `message` event. + public requestAsgi(scope: Record): MessagePort { + const channel = new MessageChannel(); + + const msg: InMessageAsgiRequest = { + type: "asgi-request", + data: { + scope + } + }; + this.postMessageTarget.postMessage(msg, [channel.port2]); + + return channel.port1; + } + + public async httpRequest(request: HttpRequest): Promise { + // Wait for the first run to be done + // to avoid the "Gradio app has not been launched." error + // in case running the code takes long time. + // Ref: https://github.com/gradio-app/gradio/issues/5957 + await this.firstRunPromiseDelegate.promise; + + console.debug("WorkerProxy.httpRequest()", request); + + // Dispatch an ASGI request to the ASGI app and gather the response data. + return new Promise((resolve, reject) => { + // https://asgi.readthedocs.io/en/latest/specs/www.html#http-connection-scope + const asgiScope: ASGIScope = { + type: "http", + asgi: { + version: "3.0", + spec_version: "2.1" + }, + http_version: "1.1", + scheme: "http", + method: request.method, + path: decodeURIComponent(request.path), + query_string: decodeURIComponent(request.query_string), + root_path: "", + headers: headersToASGI(request.headers) + }; + + const asgiMessagePort = this.requestAsgi(asgiScope); + + let status: number; + let headers: { [key: string]: string }; + let body: Uint8Array = new Uint8Array(); + asgiMessagePort.addEventListener("message", (ev) => { + const asgiSendEvent: SendEvent = ev.data; + + console.debug("send from ASGIapp", asgiSendEvent); + if (asgiSendEvent.type === "http.response.start") { + status = asgiSendEvent.status; + headers = asgiHeadersToRecord(asgiSendEvent.headers); + } else if (asgiSendEvent.type === "http.response.body") { + body = new Uint8Array([...body, ...asgiSendEvent.body]); + if (!asgiSendEvent.more_body) { + const response: HttpResponse = { + status, + headers, + body + }; + console.debug("HTTP response", response); + + asgiMessagePort.postMessage({ + type: "http.disconnect" + } satisfies ReceiveEvent); + + logHttpReqRes(request, response); + resolve(response); + } + } else { + reject(`Unhandled ASGI event: ${JSON.stringify(asgiSendEvent)}`); + } + }); + + asgiMessagePort.start(); + + if (request.body instanceof ReadableStream) { + // The following code reading the stream is based on the example in https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader#examples + const reader = request.body.getReader(); + reader.read().then(function process({ + done, + value + }): Promise | void { + if (done) { + asgiMessagePort.postMessage({ + type: "http.request", + more_body: false, + body: undefined + } satisfies ReceiveEvent); + return; + } + + asgiMessagePort.postMessage({ + type: "http.request", + more_body: !done, + body: value + } satisfies ReceiveEvent); + + return reader.read().then(process); + }); + } else { + asgiMessagePort.postMessage({ + type: "http.request", + more_body: false, + body: request.body ?? undefined + } satisfies ReceiveEvent); + } + }); + } + + public writeFile( + path: string, + data: string | ArrayBufferView, + opts?: Record + ): Promise { + return this.postMessageAsync({ + type: "file:write", + data: { + path, + data, + opts + } + }) as Promise; + } + + public renameFile(oldPath: string, newPath: string): Promise { + return this.postMessageAsync({ + type: "file:rename", + data: { + oldPath, + newPath + } + }) as Promise; + } + + public unlink(path: string): Promise { + return this.postMessageAsync({ + type: "file:unlink", + data: { + path + } + }) as Promise; + } + + public install(requirements: string[]): Promise { + return this.postMessageAsync({ + type: "install", + data: { + requirements + } + }) as Promise; + } + + public terminate(): void { + if (isMessagePort(this.postMessageTarget)) { + console.debug("Closing the message port..."); + this.postMessageTarget.close(); + } + if (isDedicatedWorker(this.worker)) { + console.debug("Terminating the worker..."); + this.worker.terminate(); + } + } +} + +function isDedicatedWorker( + obj: globalThis.Worker | SharedWorker +): obj is globalThis.Worker { + return "terminate" in obj; +} + +function isMessagePort( + obj: globalThis.Worker | MessagePort +): obj is MessagePort { + return "close" in obj; +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/context.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/context.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b9c76adc56bc93cadfdfe6dbfd6e1d403902533 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/context.ts @@ -0,0 +1,12 @@ +import { setContext, getContext } from "svelte"; +import type { WorkerProxy } from "../src/worker-proxy"; + +const WORKER_PROXY_CONTEXT_KEY = "WORKER_PROXY_CONTEXT_KEY"; + +export function setWorkerProxyContext(workerProxy: WorkerProxy): void { + setContext(WORKER_PROXY_CONTEXT_KEY, workerProxy); +} + +export function getWorkerProxyContext(): WorkerProxy | undefined { + return getContext(WORKER_PROXY_CONTEXT_KEY); +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/file-url.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/file-url.ts new file mode 100644 index 0000000000000000000000000000000000000000..1beb7da24b78d27bbbb723dd0376c69752328184 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/file-url.ts @@ -0,0 +1,69 @@ +import { getWorkerProxyContext } from "./context"; +import { is_self_host } from "../network/host"; +import { getHeaderValue } from "../src/http"; +import type { WorkerProxy } from "../src/worker-proxy"; + +type MediaSrc = string | undefined | null; + +export function should_proxy_wasm_src(src: MediaSrc): boolean { + const is_browser = typeof window !== "undefined"; + + if (src == null || !is_browser) { + return false; + } + + const url = new URL(src, window.location.href); + if (!is_self_host(url)) { + // `src` is not accessing a local server resource, so we don't need to proxy this request to the Wasm worker. + return false; + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + // `src` can be a data URL. + return false; + } + + return true; +} + +let maybeWorkerProxy: WorkerProxy | undefined; + +export async function resolve_wasm_src(src: MediaSrc): Promise { + const is_browser = typeof window !== "undefined"; + if (src == null || !is_browser || !should_proxy_wasm_src(src)) { + return src; + } + + if (maybeWorkerProxy == null) { + try { + maybeWorkerProxy = getWorkerProxyContext(); + } catch (e) { + // We are not in the Wasm env. Just use the src as is. + return src; + } + } + + if (maybeWorkerProxy == null) { + // We are not in the Wasm env. Just use the src as is. + return src; + } + + const url = new URL(src, window.location.href); + const path = url.pathname; + return maybeWorkerProxy + .httpRequest({ + method: "GET", + path, + headers: {}, + query_string: "" + }) + .then((response) => { + if (response.status !== 200) { + throw new Error(`Failed to get file ${path} from the Wasm worker.`); + } + const blob = new Blob([response.body], { + type: getHeaderValue(response.headers, "content-type") + }); + const blobUrl = URL.createObjectURL(blob); + return blobUrl; + }); +} diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/index.ts b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e84014a278dabbd0b6530feec28e653d6e901305 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/svelte/index.ts @@ -0,0 +1,3 @@ +export * from "./context"; +export * from "./file-url"; +export { default as DownloadLink } from "./DownloadLink.svelte"; diff --git a/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/vite.worker.config.js b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/vite.worker.config.js new file mode 100644 index 0000000000000000000000000000000000000000..6580303bfb41f6dcda60ab317b6569834e97c92a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/gradio/_frontend_code/wasm/vite.worker.config.js @@ -0,0 +1,34 @@ +import path from "path"; +import { defineConfig } from "vite"; + +/** + * We bundle the worker file before packaging, while other files are only TS-transpiled. + * The consumer of this package, `@gradio/lite`, will be bundled with Vite, + * and Vite only supports module-type WebWorkers (`new Worker("...", { type: "module" })`) to handle `import` in the worker file, + * because in the dev mode it doesn't bundle the worker file and just relies on the browser's native support for module-type workers to resolve the imports. + * However, we need to use `importScripts()` in the worker to load Pyodide from the CDN, which is only supported by classic WebWorkers (`new Worker("...")`), + * while we still want to use `import` in the worker to modularize the code. + * So, we bundle the worker file to resolve `import`s here before exporting, preserving `importScripts()` in the bundled file, + * and load the bundled worker file on `@gradio/lite` as a classic WebWorker. + * + * Note: We tried the following approaches, but they failed: + * 1. Just TS-transpile the worker file like other files into `worker.js`, and use it like `new Worker("worker.js")`. + * It failed because `tsc` reserves `importScripts()` and also appends `export {};` to the end of the file to specify it as a module (`https://github.com/microsoft/TypeScript/issues/41513`), + * however, `importScripts()` is only supported by classic WebWorkers, and `export {};` is not supported by classic WebWorkers. + * 2. Use ESM import instead of `importScripts()`, which is (experimentally?) supported by Pyodide since v0.20.0 (https://pyodide.org/en/stable/project/changelog.html#javascript-package), + * using `import { loadPyodide } from "https://cdn.jsdelivr.net/pyodide/v0.23.2/full/pyodide.js";` in the worker file, instead of `importScripts(...)`. + * It was successful in the dev mode, but failed in the prod mode, which has this problem: https://github.com/pyodide/pyodide/issues/2217#issuecomment-1328344562. + */ + +export default defineConfig({ + build: { + outDir: "dist/webworker", + rollupOptions: { + input: path.join(__dirname, "src/webworker/index.ts"), + // Ref: https://github.com/rollup/rollup/issues/2616#issuecomment-1431551704 + output: { + entryFileNames: "webworker.js" + } + } + } +}); diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_core_metadata.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_core_metadata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8ae18aa5c08bd9e6c8c772203d130cbbd281235 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_core_metadata.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_path.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..220bde9c1c11e139868fa8bd5e75edbec245ddb4 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_path.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_shutil.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_shutil.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2798bbdeae05deed44b449108acd3e012f8fd4d8 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/_shutil.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/namespaces.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/namespaces.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6c1c27c52351c6595fa0f273a046d4785c8acbd Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/namespaces.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/wheel.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/wheel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7324f950b364a17796de67f9bb4341ae5f64738 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/wheel.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/windows_support.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/windows_support.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbca5838f90bf48680e298744bdc69b18fa99236 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/__pycache__/windows_support.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/compat/__init__.py b/evalkit_tf437/lib/python3.10/site-packages/setuptools/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf437/lib/python3.10/site-packages/setuptools/compat/__pycache__/py39.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/setuptools/compat/__pycache__/py39.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc7d1ff66dd9b98fac76c45d8607256a37677475 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/setuptools/compat/__pycache__/py39.cpython-310.pyc differ