Python / gradio
===
###### tags: `Python`
###### tags: `Python`, `gradio`, `UI`
<br>
[TOC]
<br>
## 官網
> https://www.gradio.app/
- 預設 port:7860
- 安裝方式
```
$ pip install gradio
```
<br>
## DEMO
### Hello World

```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch(server_name='0.0.0.0')
```
<br>
<hr>
<br>
### login

```python=
import gradio as gr
def login(username, password):
if username == 'admin' and password == '1234':
return '登錄成功!您好,TJ!'
else:
return '使用者名稱或密碼有錯誤!'
interface = gr.Interface(
fn=login,
inputs=[gr.Textbox(label='使用者名稱'), gr.Textbox(label='密號', type='password')],
outputs='text',
title='登錄',
description='請輸入您的使用者名稱和密碼'
)
interface.launch(server_name='0.0.0.0')
```
- `login` 函數會檢查用戶輸入的用戶名和密碼是否匹配預設的 "admin" 和 "1234"。
- `gr.Interface` 建立了一個介面,其中 inputs 參數包括一個帳號輸入框和一個密碼輸入框。密碼輸入框使用了 `type="password"` 參數,以便在輸入時能隱藏文字。
- `outputs` 為 "text",表示函數的輸出將顯示為文字。
- `title` 和 `description` 提供了介面的標題和描述。
<br>
<hr>
<br>
### Token Counter

```python=
import gradio as gr
def count_stats(text):
tokens = text.split() # 簡單用空白分割來計算 tokens
characters = len(text) # 計算字符數
return len(tokens), characters
interface = gr.Interface(
fn=count_stats,
inputs=gr.Textbox(lines=2, label="Enter Text"),
outputs=[
gr.Number(label="Tokens"),
gr.Number(label="Characters")
],
title="Text Statistics",
description="This interface counts the number of tokens and characters in the input text."
)
interface.launch(server_name='0.0.0.0')
```