internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: gradio-app/gradio

Issue:
Sweep: Strip the user's username before login in routes.py. Add a unit test for this within test_post_login
It seems that spaces are kept at the beginning and at the end of the username's Textbox on login page.

Can you strip the username in the login route in the script gradio/routes.py?
We also need to add a unit test within test_post_login


Discussion:

Resolving patch:
diff --git a/gradio/routes.py b/gradio/routes.py
--- a/gradio/routes.py
+++ b/gradio/routes.py
@@ -221,7 +221,7 @@ def app_id(request: fastapi.Request) -> dict:
         @app.post("/login")
         @app.post("/login/")
         def login(form_data: OAuth2PasswordRequestForm = Depends()):
-            username, password = form_data.username, form_data.password
+            username, password = form_data.username.strip(), form_data.password
             if app.auth is None:
                 return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
             if (


Test patch:
diff --git a/test/test_routes.py b/test/test_routes.py
--- a/test/test_routes.py
+++ b/test/test_routes.py
@@ -465,6 +465,12 @@ def test_post_login(self):
         )
         assert response.status_code == 400
 
+        response = client.post(
+            "/login",
+            data={"username": " test ", "password": "correct_password"},
+        )
+        assert response.status_code == 200
+
 
 class TestQueueRoutes:
     @pytest.mark.asyncio
Repository: gradio-app/gradio

Issue:
gr.CheckboxGroup.update(choices=..) not working as expected
### Describe the bug

This only happens on main and I believe it's because of the recent tuple addition in #5232

### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

```python
import gradio as gr 

choices = ["First Choice", "Second Choice", "Third Choice"]
with gr.Blocks() as demo:
    chx = gr.CheckboxGroup(choices=choices, interactive=True)
    btn = gr.Button(value="Select All")
    btn.click(lambda: gr.CheckboxGroup.update(choices=["first", "second"]), None, chx)

demo.launch()
```

### Screenshot

After clicking the button

<img width="1301" alt="image" src="https://github.com/gradio-app/gradio/assets/41651716/874fd613-1e22-4dfe-b788-83269f22b3b3">


### Logs

_No response_

### System Info

```shell
main
```


### Severity

Blocking usage of gradio


Discussion:
ah yeah okay I know the issue -- thanks for flagging @freddyaboulton 

Resolving patch:
diff --git a/gradio/components/checkboxgroup.py b/gradio/components/checkboxgroup.py
--- a/gradio/components/checkboxgroup.py
+++ b/gradio/components/checkboxgroup.py
@@ -133,6 +133,11 @@ def update(
         interactive: bool | None = None,
         visible: bool | None = None,
     ):
+        choices = (
+            None
+            if choices is None
+            else [c if isinstance(c, tuple) else (str(c), c) for c in choices]
+        )
         return {
             "choices": choices,
             "label": label,
diff --git a/gradio/components/radio.py b/gradio/components/radio.py
--- a/gradio/components/radio.py
+++ b/gradio/components/radio.py
@@ -135,6 +135,11 @@ def update(
         interactive: bool | None = None,
         visible: bool | None = None,
     ):
+        choices = (
+            None
+            if choices is None
+            else [c if isinstance(c, tuple) else (str(c), c) for c in choices]
+        )
         return {
             "choices": choices,
             "label": label,


Test patch:
diff --git a/test/test_components.py b/test/test_components.py
--- a/test/test_components.py
+++ b/test/test_components.py
@@ -581,6 +581,16 @@ async def test_in_interface(self):
         scores = (await iface.interpret(["b"]))[0]["interpretation"]
         assert scores == [-2.0, None, 2.0]
 
+    def test_update(self):
+        update = gr.Radio.update(
+            choices=[("zeroth", ""), "first", "second"], label="ordinal"
+        )
+        assert update["choices"] == [
+            ("zeroth", ""),
+            ("first", "first"),
+            ("second", "second"),
+        ]
+
 
 class TestDropdown:
     def test_component_functions(self):
Repository: gradio-app/gradio

Issue:
`gr.Gallery` `selected_index` doesn't update as expected
### Describe the bug

**Issue**: A user wants to programmatically unselect a selected gallery item in the Gradio UI and remove the orange selection visual.

**Conversation**:

- Suggested a solution using the function:
  ```python
  def deselect():
      return gr.Gallery(selected_index=None)
  ```
- Confirmed the solution works but noticed a new issue. After using the `deselect` function, subsequent selections don't show the orange visual, even though the selection functionality is still operational.
  


### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

^

### Screenshot

_No response_

### Logs

_No response_

### System Info

```shell
^
```


### Severity

I can work around it


Discussion:

Resolving patch:
diff --git a/demo/gallery_selections/run.py b/demo/gallery_selections/run.py
--- a/demo/gallery_selections/run.py
+++ b/demo/gallery_selections/run.py
@@ -3,7 +3,10 @@
 
 with gr.Blocks() as demo:
     imgs = gr.State()
-    gallery = gr.Gallery()
+    gallery = gr.Gallery(allow_preview=False)
+
+    def deselect_images():
+        return gr.Gallery(selected_index=None)
 
     def generate_images():
         images = []
@@ -19,6 +22,9 @@ def generate_images():
     with gr.Row():
         selected = gr.Number(show_label=False)
         darken_btn = gr.Button("Darken selected")
+    deselect_button = gr.Button("Deselect")
+
+    deselect_button.click(deselect_images, None, gallery)
 
     def get_select_index(evt: gr.SelectData):
         return evt.index


Test patch:
Repository: gradio-app/gradio

Issue:
Gradio.Dataframe does no longer properly pass values updated in the GUI when used as input from version 4
### Describe the bug

When running the [filter records example](https://www.gradio.app/docs/dataframe) code in `3.50.2` the records are filtered based on gender-entries a user made in the webpage and based on the selected gender in the dropdown. These records are displayed in the output dataframe as expected.

However, in gradio version `4.0.2` the values that are entered in the webpage are not properly passed to the backend. Thus, no output is visible in the output dataframe.

Changing the `filter_records(..)` to include a print-statement shows that the values from the GUI are not reaching the backend:
```
def filter_records(records, gender):
    print(records)
    return records[records["gender"] == gender]
```

### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

1. Install gradio version `4.0.2`
2. Add the code from the [filter records example](https://www.gradio.app/docs/dataframe) to a file `df_example.py`
3. Run `python df_example.py`
4. Optionally add the print-statement as mentioned before
5. Enter values in the interface and press `Submit`
6. Observe that the output dataframe stays empty

### Screenshot

_No response_

### Logs

```shell
No (error) logs given
```


### System Info

```shell
gradio environment
Gradio Environment Information:
------------------------------
Operating System: Windows
gradio version: 4.0.2
gradio_client version: 0.7.0

------------------------------------------------
gradio dependencies in your environment:

aiofiles: 23.2.1
altair: 5.1.2
fastapi: 0.104.1
ffmpy: 0.3.1
gradio-client==0.7.0 is not installed.
httpx: 0.25.0
huggingface-hub: 0.18.0
importlib-resources: 6.1.0
jinja2: 3.1.2
markupsafe: 2.1.1
matplotlib: 3.7.0
numpy: 1.23.5
orjson: 3.9.10
packaging: 22.0
pandas: 1.5.3
pillow: 9.4.0
pydantic: 2.4.2
pydub: 0.25.1
python-multipart: 0.0.6
pyyaml: 6.0
requests: 2.28.1
semantic-version: 2.10.0
tomlkit==0.12.0 is not installed.
typer: 0.9.0
typing-extensions: 4.8.0
uvicorn: 0.23.2
websockets: 11.0.3
authlib; extra == 'oauth' is not installed.
itsdangerous; extra == 'oauth' is not installed.


gradio_client dependencies in your environment:

fsspec: 2023.10.0
httpx: 0.25.0
huggingface-hub: 0.18.0
packaging: 22.0
requests: 2.28.1
typing-extensions: 4.8.0
websockets: 11.0.3
```


### Severity

I can work around it


Discussion:
Thanks for creating the issue @Rjdrenth, taking a look

Resolving patch:
diff --git a/demo/dataframe_component/run.py b/demo/dataframe_component/run.py
--- a/demo/dataframe_component/run.py
+++ b/demo/dataframe_component/run.py
@@ -1,6 +1,6 @@
-import gradio as gr 
+import gradio as gr
 
 with gr.Blocks() as demo:
     gr.Dataframe(interactive=True)
 
-demo.launch()
\ No newline at end of file
+demo.launch()


Test patch:
Repository: gradio-app/gradio

Issue:
If gradio.Blocks() is given any arguments, produces "Warning: Cannot statically find a gradio demo called demo. Reload work may fail."
### Describe the bug

According to Gradio documentation, `gr.Blocks()` can take arguments such as `analytics_enabled=False`. However, if `gr.Blocks()` is given any arguments in `with gr.Blocks() as demo:`, Gradio produces a warning:
````
Warning: Cannot statically find a gradio demo called demo. Reload work may fail.
````
This can be silenced by adding a commented line as follows
````
# with gr.Blocks() as demo:
`````


### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

````
import gradio as gr

with gr.Blocks(analytics_disabled=False) as demo:
   gr.Button()
    
if __name__ == "__main__":
   demo.launch()
````

### Screenshot

_No response_

### Logs

_No response_

### System Info

```shell
Gradio Environment Information:
------------------------------
Operating System: Darwin
gradio version: 3.50.2
gradio_client version: 0.6.1

------------------------------------------------
gradio dependencies in your environment:

aiofiles: 23.2.1
altair: 5.1.2
fastapi: 0.104.0
ffmpy: 0.3.1
gradio-client==0.6.1 is not installed.
httpx: 0.25.0
huggingface-hub: 0.17.3
importlib-resources: 6.1.0
jinja2: 3.1.2
markupsafe: 2.1.3
matplotlib: 3.8.0
numpy: 1.26.1
orjson: 3.9.9
packaging: 23.2
pandas: 2.1.1
pillow: 9.5.0
pydantic: 2.4.2
pydub: 0.25.1
python-multipart: 0.0.6
pyyaml: 6.0.1
requests: 2.31.0
semantic-version: 2.10.0
typing-extensions: 4.8.0
uvicorn: 0.23.2
websockets: 11.0.3
authlib; extra == 'oauth' is not installed.
itsdangerous; extra == 'oauth' is not installed.


gradio_client dependencies in your environment:

fsspec: 2023.9.2
httpx: 0.25.0
huggingface-hub: 0.17.3
packaging: 23.2
requests: 2.31.0
typing-extensions: 4.8.0
websockets: 11.0.3
```


### Severity

I can work around it


Discussion:
Interesting.. this only happens if you run your file in reload mode, right? (e.g. `gradio app.py`, but no warning if you do `python app.py`)?
That's correct.
Still an issue
Still an issue, the team can't resolve this basic issue sad 

Resolving patch:
diff --git a/gradio/cli/commands/reload.py b/gradio/cli/commands/reload.py
--- a/gradio/cli/commands/reload.py
+++ b/gradio/cli/commands/reload.py
@@ -35,14 +35,14 @@ def _setup_config(
     app_text = original_path.read_text(encoding=encoding)
 
     patterns = [
-        f"with gr\\.Blocks\\(\\) as {demo_name}",
+        f"with gr\\.Blocks\\(.*\\) as {demo_name}",
         f"{demo_name} = gr\\.Blocks",
         f"{demo_name} = gr\\.Interface",
         f"{demo_name} = gr\\.ChatInterface",
         f"{demo_name} = gr\\.TabbedInterface",
     ]
 
-    if not any(re.search(p, app_text) for p in patterns):
+    if not any(re.search(p, app_text, flags=re.DOTALL) for p in patterns):
         print(
             f"\n[bold red]Warning[/]: Cannot statically find a gradio demo called {demo_name}. "
             "Reload work may fail."


Test patch:
Repository: gradio-app/gradio

Issue:
Writing custom css is frustrating
- [x] I have searched to see if a similar issue already exists.

Writing custom css is incredibly frustrating, to the point where I'm not sure how people have the patience to even bother. 

We need to improve this somehow. Have a few ideas that I'll add shortly.


Discussion:

Resolving patch:
diff --git a/gradio/utils.py b/gradio/utils.py
--- a/gradio/utils.py
+++ b/gradio/utils.py
@@ -170,6 +170,8 @@ def iter_py_files() -> Iterator[Path]:
         for reload_dir in reload_dirs:
             for path in list(reload_dir.rglob("*.py")):
                 yield path.resolve()
+            for path in list(reload_dir.rglob("*.css")):
+                yield path.resolve()
 
     module = None
     reload_dirs = [Path(dir_) for dir_ in reloader.watch_dirs]


Test patch:
Repository: gradio-app/gradio

Issue:
client incorrectly iterates counter, and standard while out in job loop leaves left over outputs not consumed
### Describe the bug

```
            with self.communicator.lock:
                if len(self.communicator.job.outputs) == self._counter + 1:
                    o = self.communicator.job.outputs[self._counter]
                    self._counter += 1
                    return o
                if self.communicator.job.latest_status.code == Status.FINISHED:
                    raise StopIteration()
```

Issue is that by time code reaches the first conditional, the number of job.outputs may already be 2+ while self._counter=0 at first.

So everything hangs until the end.  I find this is quite common.

Additionally, the job finished can be reached, but there are still extra things to be consumed.  So I have to add extra code after the normal `for out in job` to catch this extra stuff, making the client annoying to code for.

In the end I have to hack together a bunch of external code to work around these issues.

### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

A detailed repro is not required and the problem is self-evident from the code.

I can put together a PR if desired.

### Screenshot

_No response_

### Logs

_No response_

### System Info

```shell
gradio 4.15.0 or also older gradio too.
```


### Severity

Blocking usage of gradio


Discussion:
e.g. this works:
```

from gradio_client.utils import Status

n = 0
t0 = time.time()
while True:
    if not job.communicator:
        break
    time.sleep(0.001)

    if len(job.outputs()) - 1 >= n:
        audio_str = job.outputs()[n]
        print("n=%s/%s dt=%s" % (n, len(job.outputs()) - 1, (time.time() - t0)))
        t0 = time.time()
        n += 1
        if do_play:
            play_audio_str(audio_str)

    n_outputs = len(job.outputs())  # must be outside lock below
    with job.communicator.lock:
        if job.communicator.job.latest_status.code == Status.FINISHED and n >= n_outputs:
            break

```

Resolving patch:
diff --git a/client/python/gradio_client/client.py b/client/python/gradio_client/client.py
--- a/client/python/gradio_client/client.py
+++ b/client/python/gradio_client/client.py
@@ -1557,7 +1557,10 @@ def __next__(self) -> tuple | Any:
                     o = self.communicator.job.outputs[self._counter]
                     self._counter += 1
                     return o
-                if self.communicator.job.latest_status.code == Status.FINISHED:
+                if (
+                    self.communicator.job.latest_status.code == Status.FINISHED
+                    and self._counter >= len(self.communicator.job.outputs)
+                ):
                     raise StopIteration()
                 time.sleep(0.001)
 


Test patch:
Repository: gradio-app/gradio

Issue:
Custom component feedback
When I was building my custom component I ran into a number of issues. Dumping here as feedback while we figure out what action to take (if any). The component I was working on was bootstrapped back in prerelease so some of these issues may not be present any more. I will be building a new component this week and will check. 

- tooling / configuration 
  - if the `project.readme` isn't set correctly you get a weird error about long description. 
  - I didn't have `gradio` in my dependencies field. 
  - gradio cc publish failed catastrophically when trying to find the latest versions of the wheel in CI meaning I had to publish manually. (Will make reproduction and file an issue)
- runtime
  - some small css bugs. We should all build some stuff to make sure various internal components work correctly when used in different contexts
  - the static / interactive flipping causes many issues. Created a separate issue for this. 
  - custom status tracker was trickier than I expected, might have just been the above issue complicating things though. The props are definitely a bit weird, I think we could clean this up. 
  - I still have no idea what all of our CSS variables are, it is really difficult to figure out what to use. 
  - I don't know what all of our components are (especially atoms) and it isn't obvious how to use them. 

Other than two obvious bugs (that there are issues for) I think some of these have been resolved in recent versions or are simply a case of improving the docs. 

All that said, it still cool how we have the whole workflow pretty self contained. And other than a few specific issues things worked really nicely. A little more refinement and documentation and this will be really slick I think.


Discussion:
Nice issue @pngwn. The issues around the tooling are already fixed in 4.15 except the issue you saw with publish. Agreed we can make the documentation/discover of CSS and our components much better.

Resolving patch:
diff --git a/gradio/cli/commands/components/publish.py b/gradio/cli/commands/components/publish.py
--- a/gradio/cli/commands/components/publish.py
+++ b/gradio/cli/commands/components/publish.py
@@ -141,7 +141,7 @@ def _publish(
     ]
     wheel_file = max(
         (p for p in distribution_files if p.suffix == ".whl"),
-        key=lambda s: semantic_version.Version(str(s).split("-")[1]),
+        key=lambda s: semantic_version.Version(str(s.name).split("-")[1]),
     )
     if not wheel_file:
         raise ValueError(


Test patch:
Repository: gradio-app/gradio

Issue:
Dataframe appears empty on mobile
### Describe the bug

Dataframe appears empty on mobile

### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

https://chat.lmsys.org/?leaderboard

(working on better repro)

### Screenshot

![image](https://github.com/gradio-app/gradio/assets/1778297/9d761ff0-c966-4f5d-a831-4b593256ddf4)


### Logs

_No response_

### System Info

```shell
gradio==4.17.0
```


### Severity

Blocking usage of gradio


Discussion:
Okay, i have managed to create a minimal repro for this here: https://pngwn-7349-df-repro.hf.space/ 

It is only reproducible on specific devices. Here is a browserstack test with iPhone 15 / Safari 17.2 / Chrome.

https://github.com/gradio-app/gradio/assets/12937446/b17a195c-1bf2-4d76-98d7-6121a7479c1a

This bug occurs when the Dataframe is in a hidden tab. Tabs only set the display properties of the contents they contain, they don't remove things from the page. I believe that the dataframe is trying to measure things when it is mounted to the DOM, which in this case is when it is invisible. I don't think it _re_measures itself when the visibility changes.

I do not know why iOS has different behaviour in chrome/ safari because they have the same rendering engine. Weird but it is what it is.

Things that don't affect it (as far as I can tell):

- The size of the dataframe, the size of the contents, the size of the window (and any strange combination of those, such as the DF being larger than the window, the DF contents being larger than the DF, etc.)
- The data types. I wondered if markdown was causing this but it isn't. It always happens.
- The amount of content (large datasets), i thought this issue was due to leadboard datasets being generally quite large (many columns/ rows) but the main lmsys leaderboard isn't even that big and as you can see in the repro, it doesn't even matter.
- Slow devices. I have testsed with very large datasets with CPU slow down and network slow down and the behaviour is the same. I cant repro it locally.

In short this happens very very consistently as long as the Dataframe is first rendered in a hidden tab.

I have not yet worked out how to fix it but I'm working on that now.

Resolving patch:
diff --git a/demo/dataframe_tab/run.py b/demo/dataframe_tab/run.py
new file mode 100644
--- /dev/null
+++ b/demo/dataframe_tab/run.py
@@ -0,0 +1,12 @@
+import gradio as gr
+
+with gr.Blocks() as demo:
+    with gr.Tab():
+        gr.HTML("<p>hi</p>")
+    with gr.Tab():
+        gr.Dataframe(
+            value=[[i + 1] for i in range(10)],
+        )
+
+if __name__ == "__main__":
+    demo.launch()


Test patch:
Repository: gradio-app/gradio

Issue:
Optimize the wheel file contents for Lite
The following files included in the wheel are not needed for Lite.
* `gradio/_frontend_code`
* `gradio/templates`
* `gradio/test_data`
* `gradio/node`
* `gradio/*.pyi`


Discussion:

Resolving patch:
diff --git a/.config/lite-builder/src/lite_builder/__init__.py b/.config/lite-builder/src/lite_builder/__init__.py
new file mode 100644
diff --git a/.config/lite-builder/src/lite_builder/builder.py b/.config/lite-builder/src/lite_builder/builder.py
new file mode 100644
--- /dev/null
+++ b/.config/lite-builder/src/lite_builder/builder.py
@@ -0,0 +1,5 @@
+from hatchling.builders.wheel import WheelBuilder
+
+
+class LiteBuilder(WheelBuilder):
+    PLUGIN_NAME = 'lite'
\ No newline at end of file
diff --git a/.config/lite-builder/src/lite_builder/hooks.py b/.config/lite-builder/src/lite_builder/hooks.py
new file mode 100644
--- /dev/null
+++ b/.config/lite-builder/src/lite_builder/hooks.py
@@ -0,0 +1,6 @@
+from hatchling.plugin import hookimpl
+from .builder import LiteBuilder
+
+@hookimpl
+def hatch_register_builder():
+    return LiteBuilder
\ No newline at end of file


Test patch:
Repository: gradio-app/gradio

Issue:
logout route not deleting cookies
### Describe the bug

using /logout route, the cookies are not deleted properly 

### Have you searched existing issues?  🔎

- [X] I have searched and found no existing issues

### Reproduction

```python
import gradio as gr

def update_message(request: gr.Request):
    return f"Welcome, {request.username}"

with gr.Blocks() as demo:
    m = gr.Markdown()
    logout_button = gr.Button("Logout", link="/logout")
    demo.load(update_message, None, m)
    
demo.launch(auth=[("Pete", "Pete"), ("Dawood", "Dawood")])
```


### Screenshot

_No response_

### Logs

_No response_

### System Info

```shell
gradio==4.21.0
gradio_client==0.12.0
```


### Severity

I can work around it


Discussion:

Resolving patch:
diff --git a/gradio/routes.py b/gradio/routes.py
--- a/gradio/routes.py
+++ b/gradio/routes.py
@@ -37,7 +37,7 @@
 import httpx
 import markupsafe
 import orjson
-from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Response, status
+from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, status
 from fastapi.responses import (
     FileResponse,
     HTMLResponse,
@@ -331,7 +331,8 @@ def login(form_data: OAuth2PasswordRequestForm = Depends()):
         else:
 
             @app.get("/logout")
-            def logout(response: Response, user: str = Depends(get_current_user)):
+            def logout(user: str = Depends(get_current_user)):
+                response = RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
                 response.delete_cookie(key=f"access-token-{app.cookie_id}", path="/")
                 response.delete_cookie(
                     key=f"access-token-unsecure-{app.cookie_id}", path="/"
@@ -340,7 +341,7 @@ def logout(response: Response, user: str = Depends(get_current_user)):
                 for token in list(app.tokens.keys()):
                     if app.tokens[token] == user:
                         del app.tokens[token]
-                return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
+                return response
 
         ###############
         # Main Routes


Test patch: