tilents commited on
Commit
869c384
·
1 Parent(s): fb0d750

user complete1

Browse files
AppPub/Http/UserHttp.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ #獲取用戶的服務器信息
3
+ def GetUserData(sub):
4
+ # 发送GET请求
5
+ response = requests.get(f'https://tilents.sinaapp.com/assistant/search_userInfo.php?sub={sub}')
6
+ # 检查响应状态码
7
+ if response.status_code == 200:
8
+ # 成功获取数据
9
+ data = response.json() # 如果响应是JSON格式的数据
10
+ print(f"GetUserData{data}")
11
+ return data
12
+ else:
13
+ print(f'Failed to fetch data. Status code: {response.status_code}')
14
+ return None
15
+
16
+ GetUserData()
AppPub/User/Bean/UserInfo.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ from AppPub.User.Bean.User_Data import User_Data
4
+
5
+
6
+ class UserInfo:
7
+ def __init__(self, sub, name, picture):
8
+ self.sub = sub
9
+ self.name = name
10
+ self.picture = picture
11
+ self.data = self.GetUserInfo()
12
+ # self.mobile = ""
13
+
14
+ def HttpGetUserData(self):
15
+ # 发送GET请求
16
+ response = requests.get(f'https://tilents.sinaapp.com/assistant/search_userInfo.php?sub={self.sub}')
17
+ # 检查响应状态码
18
+ if response.status_code == 200:
19
+ # 成功获取数据
20
+ data = response.json() # 使用正确的字符编码
21
+ print(f"GetUserData{data}")
22
+ return data
23
+ else:
24
+ print(f'Failed to fetch data. Status code: {response.status_code}')
25
+ return None
26
+
27
+ import requests
28
+
29
+ def HttpPostUserData(self, push_data):
30
+ # 定义要发送的数据,这里是一个字典
31
+ data = {
32
+ "sub": self.sub, # 假设需要传递的参数名为 "sub"
33
+ "uservalue": push_data
34
+ # 添加其他参数和值
35
+ }
36
+ # 发送POST请求
37
+ response = requests.post('https://tilents.sinaapp.com/assistant/insert_userinfo.php', data=data)
38
+
39
+ # 检查响应状态码
40
+ if response.status_code == 200:
41
+ # 成功获取数据
42
+ data = response.content.decode('utf-8') # 使用正确的字符编码
43
+ print(f"PostUserData: {data}")
44
+ return json.loads(data)
45
+ else:
46
+ print(f'Failed to fetch data. Status code: {response.status_code}')
47
+ return None
48
+
49
+
50
+ def GetUserInfo(self):
51
+ data = self.HttpGetUserData()
52
+ if not data or "Failed to fetch data" in data or "null" in data:
53
+ person = User_Data(self.name, self.picture)
54
+ json_string = json.dumps(person.to_json())
55
+ print("新用戶:"+json_string) # 註冊一個用戶
56
+ result = self.HttpPostUserData(json_string)
57
+ # 处理获取到的数据
58
+ if result is not None:
59
+ # 在这里处理返回的数据
60
+ print(f"新用戶添加結果:{result}") # 註冊一個用戶
61
+ return person
62
+ else:
63
+ # 将JSON字符串解析为类的实例
64
+ person_dict = json.loads(data)
65
+ # User_Data
66
+ person = User_Data(**person_dict)
67
+ return person
AppPub/User/Bean/User_Data.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 用戶data裡面的json數據bean
3
+ """
4
+
5
+
6
+ class User_Data:
7
+ def __init__(
8
+ self,
9
+ name,
10
+ picture: str = "",
11
+ ):
12
+ self.name = name
13
+ self.picture = picture
14
+
15
+ # 定义一个自定义的JSON序列化方法
16
+ def to_json(self):
17
+ return {
18
+ "name": self.name,
19
+ "picture": self.picture
20
+ }
MyWidget/CustomButton.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Button() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import Component, IOComponent, _Keywords
11
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
12
+ from gradio.events import Clickable
13
+
14
+ set_documentation_group("component")
15
+
16
+ import gradio as gr
17
+ @document()
18
+ class CustomButton(Clickable, IOComponent, StringSerializable):
19
+ """
20
+ Used to create a button, that can be assigned arbitrary click() events. The label (value) of the button can be used as an input or set via the output of a function.
21
+
22
+ Preprocessing: passes the button value as a {str} into the function
23
+ Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button
24
+ Demos: blocks_inputs, blocks_kinematics
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ value: str | Callable = "Run",
30
+ *,
31
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
32
+ size: Literal["sm", "lg"] | None = None,
33
+ icon: str | None = None,
34
+ link: str | None = None,
35
+ visible: bool = True,
36
+ interactive: bool = True,
37
+ elem_id: str | None = None,
38
+ elem_classes: list[str] | str | None = None,
39
+ scale: int | None = None,
40
+ min_width: int | None = None,
41
+ **kwargs,
42
+ ):
43
+ """
44
+ Parameters:
45
+ value: Default text for the button to display. If callable, the function will be called whenever the app loads to set the initial value of the component.
46
+ variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button.
47
+ size: Size of the button. Can be "sm" or "lg".
48
+ icon: URL or path to the icon file to display within the button. If None, no icon will be displayed. Must be within the working directory of the Gradio app or an external URL.
49
+ link: URL to open when the button is clicked. If None, no link will be used.
50
+ visible: If False, component will be hidden.
51
+ interactive: If False, the Button will be in a disabled state.
52
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
53
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
54
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
55
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
56
+ """
57
+ IOComponent.__init__(
58
+ self,
59
+ visible=visible,
60
+ elem_id=elem_id,
61
+ elem_classes=elem_classes,
62
+ value=value,
63
+ interactive=interactive,
64
+ scale=scale,
65
+ min_width=min_width,
66
+ **kwargs,
67
+ )
68
+ if variant == "plain":
69
+ warn_deprecation("'plain' variant deprecated, using 'secondary' instead.")
70
+ variant = "secondary"
71
+ self.variant = variant
72
+ self.size = size
73
+ self.icon = icon
74
+ self.link = link
75
+
76
+ def get_config(self):
77
+ return {
78
+ "value": self.value,
79
+ "variant": self.variant,
80
+ "size": self.size,
81
+ "icon": self.icon,
82
+ "link": self.link,
83
+ "interactive": self.interactive,
84
+ "scale": self.scale,
85
+ "min_width": self.min_width,
86
+ **Component.get_config(self),
87
+ }
88
+
89
+ @staticmethod
90
+ def update(
91
+ value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
92
+ variant: Literal["primary", "secondary", "stop"] | None = None,
93
+ size: Literal["sm", "lg"] | None = None,
94
+ icon: str | None = None,
95
+ link: str | None = None,
96
+ visible: bool | None = None,
97
+ interactive: bool | None = None,
98
+ scale: int | None = None,
99
+ min_width: int | None = None,
100
+ ):
101
+ return {
102
+ "variant": variant,
103
+ "size": size,
104
+ "visible": visible,
105
+ "value": value,
106
+ "icon": icon,
107
+ "link": link,
108
+ "interactive": interactive,
109
+ "scale": scale,
110
+ "min_width": min_width,
111
+ "__type__": "update",
112
+ }
113
+
114
+ def style(
115
+ self,
116
+ *,
117
+ full_width: bool | None = None,
118
+ size: Literal["sm", "lg"] | None = None,
119
+ **kwargs,
120
+ ):
121
+ """
122
+ This method is deprecated. Please set these arguments in the constructor instead.
123
+ """
124
+ warn_style_method_deprecation()
125
+ if full_width is not None:
126
+ warn_deprecation(
127
+ "Use `scale` in place of full_width in the constructor. "
128
+ "scale=1 will make the button expand, whereas 0 will not."
129
+ )
130
+ self.scale = 1 if full_width else None
131
+ if size is not None:
132
+ self.size = size
133
+ return self
134
+
135
+ class CustomButton2(gr.Button):
136
+ def __init__(self, *args, **kwargs):
137
+ super().__init__(*args, **kwargs)
138
+ # 在这里可以添加自定义的初始化代码
139
+
140
+
141
+ with gr.Blocks() as demo:
142
+ # gr.Button("Test")
143
+ CustomButton2("2")
144
+
145
+ demo.launch()
MyWidget/CustomLoginButton.py ADDED
File without changes
MyWidget/__init__.py ADDED
File without changes
UI/JS/ShowAndDisable.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 定义一个 JavaScript 函数来隐藏按钮
2
+ #block:元素以块级元素的形式显示,占据整行的空间,前后都会换行。
3
+ #inline:元素以内联元素的形式显示,不会占据整行的空间,可以在文本中显示,前后都不会换行。
4
+ #none:元素不在页面上显示,且不会占据任何空间。
5
+ #flex:元素以弹性布局的形式显示,通常用于构建复杂的页面布局。
6
+ #grid:元素以网格布局的形式显示,通常用于构建二维的页面布局。
7
+ def GetShowObject(id):
8
+ hide_button_js = f"""
9
+ function hideButton() {{
10
+ var button = document.getElementById('{id}');
11
+ button.style.display = 'block';
12
+ }}
13
+ """
14
+ return hide_button_js
15
+
16
+ def GetHideObject(id):
17
+ hide_button_js = f"""
18
+ function hideButton() {{
19
+ var button = document.getElementById('{id}');
20
+ button.style.display = 'none';
21
+ }}
22
+ """
23
+ return hide_button_js
24
+
25
+ def HindObjectJs(id):
26
+ hide_button_js = f"""document.getElementById('{id}').style.display = 'none'"""
27
+ return hide_button_js
28
+
29
+ def ShowObjectJs(id):
30
+ hide_button_js = f"""document.getElementById('{id}').style.display = 'block'"""
31
+ return hide_button_js
UI/LoginPanel.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio.routes import Request
3
+ from typing import Any
4
+
5
+ from AppPub.User.Bean.UserInfo import UserInfo
6
+
7
+ """
8
+ justify:控制组件在水平方向上的对齐方式。可选值包括:
9
+ 'flex-start':默认值,左对齐。
10
+ 'center':居中对齐。
11
+ 'flex-end':右对齐。
12
+ 'space-between':均匀分布,首尾贴边。
13
+ 'space-around':均匀分布,组件两侧留有空白。
14
+ """
15
+
16
+ # 使用HTML元素创建一个自定义的空白区域,使用flex-grow来填充剩余空间
17
+
18
+
19
+ def blank_space():
20
+ return "<div style='flex-grow: 1;'></div>"
21
+
22
+
23
+ class LoginPanel:
24
+ def __init__(self):
25
+ with gr.Row() as row:
26
+ self.loginButton = self.GetLoginButton()
27
+ gr.HTML(blank_space())
28
+ self.logoutButton = self.GetLogOutButton()
29
+ self.row = row
30
+ # 登錄用戶唯一標識碼
31
+ self.sub = 0
32
+ self.userInfo = None
33
+
34
+ def GetLoginButton(self):
35
+ loginbutton = gr.LoginButton(scale=1, size=None)
36
+ def _check_login_status(request: Request) -> dict[str, Any]:
37
+ # Each time the page is refreshed or loaded, check if the user is logged in and adapt label
38
+ session = getattr(request, "session", None) or getattr(
39
+ request.request, "session", None
40
+ )
41
+ if session is None or "oauth_profile" not in session:
42
+ self.sub = 0
43
+ return loginbutton.update("登錄 Hugging Face", interactive=True)
44
+ else:
45
+ username = session["oauth_profile"]["preferred_username"]
46
+ sub = session["oauth_token"]["userinfo"]["sub"]
47
+ self.sub = sub
48
+ self.userInfo = UserInfo(self.sub, session["oauth_token"]["userinfo"]['name'], session["oauth_token"]["userinfo"]["picture"])
49
+ return loginbutton.update(f"你好: {username}", interactive=False)
50
+ loginbutton.attach_load_event(_check_login_status, None)
51
+ return loginbutton
52
+
53
+ def GetLogOutButton(self):
54
+ logoutButton = gr.LogoutButton(value="退出登錄", scale=1, size=None)
55
+ return logoutButton
56
+
UI/MainBlocks.py CHANGED
@@ -1,7 +1,76 @@
 
 
 
 
 
 
 
1
  class MainBlocks:
2
- def __init__(self, name, age):
 
3
  self.name = name
4
- self.age = age
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- def greet(self):
7
- return f"Hello, my name is {self.name} and I am {self.age} years old."
 
1
+ import time
2
+ import gradio as gr
3
+ import os
4
+ from UI.JS.ShowAndDisable import GetHideObject
5
+ from UI.LoginPanel import LoginPanel
6
+
7
+
8
  class MainBlocks:
9
+ def __init__(self, name):
10
+ self.loginPanel = None
11
  self.name = name
12
+ self.main = self.GetDemo()
13
+ self.main.queue()
14
+ self.main.launch()
15
+
16
+ # Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
17
+ def add_text(self, history, text):
18
+ history = history + [(text, None)]
19
+ return history, gr.update(value="", interactive=False)
20
+
21
+ def add_file(self, history, file):
22
+ history = history + [((file.name,), None)]
23
+ return history
24
+
25
+ def bot(self, history):
26
+ if self.loginPanel.sub == 0:
27
+ response = "請登錄再聊"
28
+ # response = "Hello! Click the link below:<br><a href='https://www.baidu.com' target='_blank'>Visit Example.com</a>"
29
+ else:
30
+ response = "hey its cool"
31
+ history[-1][1] = ""
32
+ for character in response:
33
+ history[-1][1] += character
34
+ time.sleep(0.05)
35
+ yield history
36
+
37
+ def GetDemo(self):
38
+ with gr.Blocks() as demo:
39
+ # 登錄頁面
40
+ self.loginPanel = LoginPanel()
41
+ buttonAddText = gr.Button(value="Submit", elem_id="my-button")
42
+ # 使用 btn.click() 定义按钮被点击时的行为
43
+ buttonAddText.click(None, _js=GetHideObject("my-button"))
44
+ chatbot = gr.Chatbot(
45
+ [],
46
+ elem_id="chatbot",
47
+ bubble_full_width=False,
48
+ show_label=False,
49
+ #左邊是我的頭像,右邊是機器人頭像
50
+ avatar_images=("https://huggingface.co/front/assets/huggingface_logo-noborder.svg", (os.path.join(os.path.dirname(__file__), "../gradiodemo/Demo/IMG/didi.jpeg"))),
51
+ )
52
+ with gr.Row():
53
+ txt = gr.Textbox(
54
+ scale=4,
55
+ show_label=False,
56
+ placeholder="Enter text and press enter",
57
+ container=False,
58
+ )
59
+ # btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])
60
+ # btn = gr.Button("確定")
61
+ txt_msg = txt.submit(self.add_text, [chatbot, txt], [chatbot, txt], queue=False)
62
+ txt_msg.then(
63
+ self.bot, chatbot, chatbot
64
+ )
65
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False, _js=GetHideObject("my-button"))
66
+ # txt_msgbtn = btn.click(self.add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
67
+ # self.bot, chatbot, chatbot
68
+ # )
69
+ # file_msg = btn.upload(self.add_file, [chatbot, btn], [chatbot], queue=False).then(
70
+ # self.bot, chatbot, chatbot
71
+ # )
72
+ return demo
73
+
74
 
75
+ if __name__ == "__main__":
76
+ mainBlocks1 = MainBlocks("test")
app.py CHANGED
@@ -2,52 +2,9 @@ import gradio as gr
2
  import os
3
  import time
4
 
5
- # Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
6
- def add_text(history, text):
7
- history = history + [(text, None)]
8
- return history, gr.update(value="", interactive=False)
9
- def add_file(history, file):
10
- history = history + [((file.name,), None)]
11
- return history
12
-
13
-
14
- def bot(history):
15
- response = "**That's cool!**"
16
- history[-1][1] = ""
17
- for character in response:
18
- history[-1][1] += character
19
- time.sleep(0.05)
20
- yield history
21
-
22
-
23
- with gr.Blocks() as demo:
24
- buttonAddText = gr.Button("添加文本框")
25
- chatbot = gr.Chatbot(
26
- [],
27
- elem_id="chatbot",
28
- bubble_full_width=False,
29
- avatar_images=(None, (os.path.join(os.path.dirname(__file__), "./gradiodemo/Demo/IMG/didi.jpeg"))),
30
- )
31
-
32
- with gr.Row():
33
- txt = gr.Textbox(
34
- scale=4,
35
- show_label=False,
36
- placeholder="Enter text and press enter, or upload an image",
37
- container=False,
38
- )
39
- btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])
40
-
41
-
42
 
 
43
 
44
- txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
45
- bot, chatbot, chatbot
46
- )
47
- txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
48
- file_msg = btn.upload(add_file, [chatbot, btn], [chatbot], queue=False).then(
49
- bot, chatbot, chatbot
50
- )
51
  if __name__ == "__main__":
52
- demo.queue()
53
- demo.launch()
 
2
  import os
3
  import time
4
 
5
+ from UI.MainBlocks import MainBlocks
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
8
 
 
 
 
 
 
 
 
9
  if __name__ == "__main__":
10
+ mainBlocks1 = MainBlocks("test")
 
gradiodemo/Demo/Blocks/t.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ with gr.Blocks() as demo:
4
+ with gr.Blocks() as block1:
5
+ gr.Button("1")
6
+ with gr.Blocks() as block2:
7
+ gr.Button("2")
8
+
9
+ # gr.Button("Toggle Block 1").click(toggle_block1, None)
10
+
11
+ # 在这里,您可以将不同的组件添加到块1和块2中
12
+ # 然后通过点击按钮来切换块1的可见性
13
+
14
+ demo.launch()
gradiodemo/Demo/ChatBotSimple.py CHANGED
@@ -10,7 +10,8 @@ with gr.Blocks() as demo:
10
  clear = gr.ClearButton([msg, chatbot])
11
 
12
  def respond(message, chat_history):
13
- bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
 
14
  chat_history.append((message, bot_message))
15
  time.sleep(2)
16
  print(chat_history)
 
10
  clear = gr.ClearButton([msg, chatbot])
11
 
12
  def respond(message, chat_history):
13
+ # bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
14
+ bot_message = "Hello! Click the link below:<br><a href='https://www.baidu.com' target='_blank'>Visit Example.com</a>"
15
  chat_history.append((message, bot_message))
16
  time.sleep(2)
17
  print(chat_history)
gradiodemo/Demo/Customer/t.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+
3
+ import gradio as gr
4
+
5
+
6
+ class CustomBlocks(gr.Blocks):
7
+ def __init__(self, *args, **kwargs):
8
+ super().__init__(*args, **kwargs)
9
+ # 在这里可以添加自定义的初始化代码
10
+
11
+ def custom_action(self):
12
+ # 在这里可以添加自定义的按钮点击行为
13
+ print("Custom button clicked!")
14
+
15
+
16
+
17
+ class CustomButton(gr.Button):
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__(*args, **kwargs)
20
+ # 在这里可以添加自定义的初始化代码
21
+
22
+ def custom_action(self):
23
+ # 在这里可以添加自定义的按钮点击行为
24
+ print("Custom button clicked!")
25
+
26
+ # 创建 Gradio 接口
27
+ import gradio as gr
28
+
29
+ def image_classifier(inp):
30
+ return {'cat': 0.3, 'dog': 0.7}
31
+
32
+ with CustomBlocks() as demo:
33
+ custom_button = CustomButton("Custom Button")
34
+
35
+ # 启动 Gradio 界面
36
+ demo.launch()
gradiodemo/Demo/GradioLogin.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ # User login function for authentication
4
+ def login(username, password):
5
+ # In a real application, you would perform username and password validation here.
6
+ # If the validation succeeds, you can return a success message; otherwise, return a failure message.
7
+ if username == "user" and password == "password":
8
+ return "Login successful"
9
+ else:
10
+ return "Login failed"
11
+
12
+ # Create a login button
13
+ login_button = gr.LoginButton()
14
+
15
+ # Create a Gradio interface
16
+ iface = gr.Interface(
17
+ fn=login,
18
+ inputs=[gr.Textbox("Username"), gr.Textbox("Password", input_type="password"), login_button],
19
+ outputs=gr.Textbox(),
20
+ live=True,
21
+ title="User Login",
22
+ description="Please enter your username and password.",
23
+ )
24
+
25
+ # Launch the Gradio interface
26
+ iface.launch()
gradiodemo/Demo/Javascript/AutoRun.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ # 定义 JavaScript 代码
4
+ javascript_code = """
5
+ function showAlert() {
6
+ alert("Button clicked!");
7
+ }
8
+ """
9
+
10
+ with gr.Blocks() as demo2:
11
+ # 添加一个按钮
12
+ button = gr.Button("Click Me2222")
13
+ def clickDo(text):
14
+ demo2.launch(in_browser=True)
15
+
16
+ with gr.Blocks() as demo:
17
+ # 添加一个按钮
18
+ button = gr.Button("Click Me")
19
+ loginbutton = gr.LoginButton()
20
+ # 使用 gr.Code 组件嵌入 JavaScript 代码
21
+ javascript_code_component = gr.Code(
22
+ value=javascript_code,
23
+ language="javascript",
24
+ output=None,
25
+ live=False
26
+ )
27
+
28
+ # 当按钮被点击时,执行 JavaScript 脚本
29
+ button.click(clickDo, _js="document.write(\"<h1>Hello World!</h1>\");")
30
+
31
+
32
+ demo.launch()
gradiodemo/Demo/Javascript/t.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+
4
+ import gradio as gr
5
+
6
+ from UI.JS.ShowAndDisable import GetHideObject, HindObjectJs, ShowObjectJs
7
+
8
+
9
+ def add_text(self, history, text):
10
+ history = history + [(text, None)]
11
+ return history, gr.update(value="", interactive=False)
12
+
13
+ def bot(self,history):
14
+ # response = "Hello! Click the link below:<br><a href='https://www.baidu.com' target='_blank'>Visit Example.com</a>"
15
+ response = "hey its cool"
16
+ history[-1][1] = ""
17
+ for character in response:
18
+ history[-1][1] += character
19
+ time.sleep(0.05)
20
+ yield history
21
+
22
+
23
+ blocks = gr.Blocks()
24
+ with blocks as demo:
25
+ chatbot = gr.Chatbot(
26
+ [],
27
+ elem_id="chatbot_id",
28
+ bubble_full_width=False,
29
+ avatar_images=(None, (os.path.join(os.path.dirname(__file__), "../gradiodemo/Demo/IMG/didi.jpeg"))),
30
+ )
31
+ with gr.Row():
32
+ txt = gr.Textbox(
33
+ scale=4,
34
+ show_label=False,
35
+ placeholder="Enter text and press enter, or upload an image",
36
+ container=False,
37
+ )
38
+ txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
39
+ bot, chatbot, chatbot
40
+ )
41
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
42
+ chatbot.visible = False
43
+ foo_bar_btn = gr.Button("開始")
44
+ foo_bar_btn.click(None, [], [], _js=HindObjectJs("chatbot_id"))
45
+ foo_bar_btn = gr.Button("開始2")
46
+ foo_bar_btn.click(None, [], [], _js=ShowObjectJs("chatbot_id"))
47
+ demo.queue()
48
+ demo.launch()
gradiodemo/Demo/Login/2.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ # # 定义一个简单的用户数据库,用于模拟用户验证
4
+ # user_database = {
5
+ # "username": "password", # 用于存储用户名和密码的字典
6
+ # }
7
+ #
8
+ #
9
+ # # 处理登录按钮的点击事件
10
+ # def login_click():
11
+ # username = login_button.username # 获取输入的用户名
12
+ # password = login_button.password # 获取输入的密码
13
+ #
14
+ # # 验证用户名和密码是否在用户数据库中
15
+ # if username in user_database and user_database[username] == password:
16
+ # login_button.login_successful() # 登录成功
17
+ # else:
18
+ # login_button.login_failed() # 登录失败
19
+ # 创建登录按钮
20
+
21
+ # with gr.Blocks() as demo:
22
+ # # 创建 Gradio 接口
23
+ # # 创建登录按钮并在 Blocks 上下文内创建
24
+ # login_button = gr.LoginButton()
25
+ # login_button.activate()
26
+ # # 绑定登录按钮的点击事件处理函数
27
+ # login_button.click(login_click)
28
+ #
29
+ # # 启动 Gradio 界面
30
+ # demo.launch()
31
+
32
+ import gradio as gr
33
+
34
+ import gradio as gr
35
+
36
+ from MyWidget.CustomLoginButton import CustomLoginButton
37
+
38
+
39
+ def login_callback(button):
40
+ # 处理登录逻辑
41
+ if button.clicked():
42
+ # 用户点击了登录按钮
43
+ # 在这里执行登录操作,例如验证用户输入的用户名和密码
44
+ # 如果登录成功,可以执行其他操作或更新界面
45
+ print("User clicked the login button.")
46
+
47
+ with gr.Blocks() as demo:
48
+ loginbutton = CustomLoginButton()
49
+ logout = gr.LogoutButton()
50
+
51
+ demo.launch()
gradiodemo/Demo/Login/3.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ def login_callback(button):
4
+ # 处理登录逻辑
5
+ # if button.clicked():
6
+ # 用户点击了登录按钮
7
+ # 在这里执行登录操作,例如验证用户输入的用户名和密码
8
+ # 如果登录成功,可以执行其他操作或更新界面
9
+ print("User clicked the login button.")
10
+
11
+
12
+ import gradio as gr
13
+
14
+ with gr.Blocks() as demo:
15
+ gr.LoginButton()
16
+
17
+ demo.launch()
gradiodemo/Demo/{Login.py → Login/Login.py} RENAMED
File without changes
gradiodemo/Demo/Login/__init__.py ADDED
File without changes
gradiodemo/Demo/__init__.py ADDED
File without changes
gradiodemo/Demo/cookie/t.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from flask import request
3
+
4
+ # 创建一个函数,该函数设置 cookie 并返回消息
5
+ def set_cookie():
6
+ request.cookies.set("user_cookie", "HelloCookie")
7
+ return "Cookie has been set!"
8
+
9
+ # 创建 Gradio 接口,指定输入为 None(因为这里不需要输入)
10
+ iface = gr.Interface(fn=set_cookie, inputs=None, outputs="text")
11
+
12
+ # 启动 Gradio 应用
13
+ iface.launch()
gradiodemo/Demo/mHtl/HtmlJs.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ # 自定义 HTML 和 JavaScript 代码
4
+ custom_html = """
5
+ <!DOCTYPE html>
6
+ <html>
7
+ <head>
8
+ <title>Custom JavaScript</title>
9
+ </head>
10
+ <body>
11
+ <button id="myButton">Click me</button>
12
+ <script>
13
+ document.getElementById("myButton").addEventListener("click", function() {
14
+ alert("Button clicked!");
15
+ });
16
+ </script>
17
+ </body>
18
+ </html>
19
+ """
20
+ def greet(name):
21
+ return "Hello " + name + "!"
22
+ # 创建 Gradio 应用,嵌入自定义 HTML
23
+ with gr.Blocks() as demo:
24
+ custom_component = gr.HTML(custom_html)
25
+ gr.Interface(fn=greet, inputs="text", outputs="text")
26
+
27
+ demo.launch()
gradiodemo/Demo/mHtl/JS.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ import gradio as gr
4
+ import random
5
+ import time
6
+ # 动态生成 HTML 和 JavaScript 代码
7
+ def generate_button_html():
8
+ # button_html = f"""
9
+ # <script> function show() {{
10
+ # // 在这里执行 JavaScript 代码
11
+ # alert("Button clicked!");
12
+ # // 隐藏按钮
13
+ # var button = document.getElementById('my-button2');
14
+ # button.style.display = 'none';
15
+ # }}
16
+ # </script>
17
+ # <button id="my-button" onclick="show();">Click Me</button>
18
+ # <button id="my-button2" onclick="show();">Click Me2</button>
19
+ # """
20
+ button_html = f"""
21
+ <script> alert("Button clicked!") </script>
22
+ """
23
+ button_html = button_html.replace("\n","<br>")
24
+ print(button_html)
25
+ return button_html
26
+
27
+ with gr.Blocks() as demo:
28
+ chatbot = gr.Chatbot()
29
+ btn = gr.Button(value="Submit")
30
+ btn.visible = False
31
+ msg = gr.Textbox()
32
+ clear = gr.ClearButton([msg, chatbot])
33
+
34
+ def respond(message, chat_history):
35
+ # bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
36
+ bot_message = f"Hello! Click the button below:<br>{generate_button_html()}"
37
+ chat_history.append((message, bot_message))
38
+ time.sleep(2)
39
+
40
+ btn.visible = True
41
+ gr.update(value="", interactive=True)
42
+ return "", chat_history,btn
43
+
44
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
45
+
46
+ if __name__ == "__main__":
47
+ demo.launch()
gradiodemo/Demo/mHtl/JS2.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def welcome(name,btn):
4
+ # 在回复消息中嵌入 JavaScript 代码
5
+ js_code = "<script>alert('Button clicked!');</script>"
6
+ response = f"Hello! Click the button below:<br><button onclick=\"{js_code}\">Click Me</button>"
7
+
8
+ return "response"
9
+
10
+
11
+ with gr.Blocks() as demo:
12
+ gr.Markdown(
13
+ """
14
+ # Hello World!
15
+ Start typing below to see the output.
16
+ """)
17
+ inp = gr.Textbox(placeholder="What is your name?")
18
+ out = gr.Textbox()
19
+ btn = gr.Button("1")
20
+ def changeIcon(btnw):
21
+ # btnw.icon = "didi.jpeg"
22
+ return "tt",gr.update(value="", interactive=True)
23
+ inp.change(welcome, [inp,btn], btn).then(changeIcon,btn,btn)
24
+
25
+ if __name__ == "__main__":
26
+ demo.launch()
27
+
gradiodemo/Demo/mHtl/didi.jpeg ADDED
gradiodemo/Demo/mHtl/tt.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def show_button(flag):
4
+ button = gr.Button("Click Me")
5
+ # button.visible = flag # 控制按钮的可见性
6
+ return "ddd"
7
+
8
+ demo = gr.Interface(
9
+ show_button,
10
+ "checkbox", # 添加一个复选框组件,用于控制按钮的可见性
11
+ "button"
12
+ )
13
+
14
+ if __name__ == "__main__":
15
+ demo.launch()
gradiodemo/Demo/request/1.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ def echo(name, request: gr.Request):
3
+ print("Request headers dictionary:", request.headers)
4
+ print("IP address:", request.client.host)
5
+ return name
6
+ io = gr.Interface(echo, "textbox", "textbox").launch()
gradiodemo/Flask/Helloworld.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask
2
+
3
+ app = Flask(__name__)
4
+
5
+ @app.route('/')
6
+ def hello_world():
7
+ return 'Hello, World!'
8
+
9
+ if __name__ == '__main__':
10
+ app.run()
gradiodemo/Flask/RunGradio.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from flask import Flask, render_template
3
+
4
+ app = Flask(__name__)
5
+ def my_function_1(name):
6
+ return "dfd"
7
+ # 定义多个 Gradio 接口
8
+ def gradio_interface_1():
9
+ interface = gr.Interface(
10
+ fn=my_function_1,
11
+ inputs="text",
12
+ outputs="text",
13
+ )
14
+ return interface
15
+
16
+ def gradio_interface_2():
17
+ interface = gr.Interface(
18
+ fn=my_function_1,
19
+ inputs="image",
20
+ outputs="text",
21
+ )
22
+ return interface
23
+
24
+ # 创建多个 Gradio 接口
25
+ gr_interface_1 = gradio_interface_1()
26
+ gr_interface_2 = gradio_interface_2()
27
+
28
+ # 添加多个 Gradio 接口到 Flask Web 应用程序
29
+ @app.route('/')
30
+ def home():
31
+ return render_template('index.html')
32
+
33
+ @app.route('/interface1')
34
+ def interface1():
35
+ return gr_interface_1.launch()
36
+
37
+ @app.route('/interface2')
38
+ def interface2():
39
+ return gr_interface_2.launch()
40
+
41
+ if __name__ == '__main__':
42
+ app.run(debug=True)
gradiodemo/Flask/t.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request
2
+ import gradio as gr
3
+
4
+ app = Flask(__name__)
5
+
6
+ # 定义 Gradio Blocks 示例
7
+ def gradio_blocks_demo():
8
+ with gr.Blocks() as demo:
9
+ # 在这里添加您的 Gradio Blocks 组件
10
+ gr.Button("Test")
11
+ return demo
12
+
13
+ # 创建 Gradio Blocks 示例
14
+ gradio_demo = gradio_blocks_demo()
15
+
16
+ @app.route('/')
17
+ def home():
18
+ # 渲染 HTML 模板,将 Gradio Blocks 示例嵌入到模板中
19
+ return render_template('index.html', gradio_demo=gradio_demo)
20
+
21
+ if __name__ == '__main__':
22
+ gradio_demo.launch()
gradiodemo/Flask/templates/index.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Title</title>
6
+ </head>
7
+ <body>
8
+
9
+ </body>
10
+ </html>
requirements.txt CHANGED
@@ -1 +1,4 @@
1
  gradio==3.42.0
 
 
 
 
1
  gradio==3.42.0
2
+ Flask==2.3.3
3
+
4
+ requests~=2.31.0