Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,27 +1,21 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
from
|
4 |
-
import
|
5 |
-
from
|
6 |
-
from transformers import pipeline
|
7 |
-
from huggingface_hub import InferenceApi
|
8 |
-
import sqlite3
|
9 |
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table
|
10 |
from sqlalchemy.orm import sessionmaker
|
11 |
-
import
|
12 |
-
import
|
13 |
-
import
|
14 |
|
15 |
-
#
|
16 |
DATABASE_URL = "sqlite:///chatbot.db"
|
17 |
engine = create_engine(DATABASE_URL)
|
18 |
Session = sessionmaker(bind=engine)
|
19 |
session = Session()
|
20 |
metadata = MetaData()
|
21 |
|
22 |
-
# Load the image generation model (for example, using a Hugging Face model)
|
23 |
-
image_generator = pipeline("image-generation", model="CompVis/stable-diffusion-v1-4")
|
24 |
-
|
25 |
def create_table(table_name, columns):
|
26 |
if table_name in engine.table_names():
|
27 |
return f"Table '{table_name}' already exists."
|
@@ -56,6 +50,82 @@ def edit_table(table_name, columns):
|
|
56 |
|
57 |
return f"Table '{table_name}' updated successfully."
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
def chatbot_response(task, table_name=None, columns=None):
|
60 |
if task == "create_table":
|
61 |
if table_name and columns:
|
@@ -70,11 +140,8 @@ def chatbot_response(task, table_name=None, columns=None):
|
|
70 |
else:
|
71 |
result = "Unsupported task. Use 'create_table' or 'edit_table'."
|
72 |
|
73 |
-
# Generate a descriptive image based on the response
|
74 |
description = f"Task: {task}, Table Name: {table_name}, Columns: {columns}"
|
75 |
-
|
76 |
-
|
77 |
-
return result, image
|
78 |
|
79 |
def handle_chatbot(task, table_name, columns):
|
80 |
if task not in ['create_table', 'edit_table']:
|
@@ -93,17 +160,31 @@ def generate_image(description):
|
|
93 |
return image
|
94 |
|
95 |
# Gradio interface setup
|
|
|
|
|
|
|
|
|
|
|
96 |
task_input = gr.inputs.Textbox(lines=1, placeholder="Task (create_table or edit_table)")
|
97 |
table_name_input = gr.inputs.Textbox(lines=1, placeholder="Table Name")
|
98 |
columns_input = gr.inputs.Textbox(lines=2, placeholder="Columns (JSON format: {'column1': 'type', 'column2': 'type'})")
|
99 |
|
100 |
interface = gr.Interface(
|
101 |
-
fn=
|
102 |
inputs=[task_input, table_name_input, columns_input],
|
103 |
outputs=[gr.outputs.Textbox(), gr.outputs.Image(type="pil")],
|
104 |
-
title="SQL Database
|
105 |
-
description="A
|
106 |
)
|
107 |
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import json
|
3 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends
|
4 |
+
from fastapi.responses import HTMLResponse
|
5 |
+
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
|
|
|
6 |
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table
|
7 |
from sqlalchemy.orm import sessionmaker
|
8 |
+
import gradio as gr
|
9 |
+
from transformers import pipeline
|
10 |
+
from PIL import Image
|
11 |
|
12 |
+
# Database Setup
|
13 |
DATABASE_URL = "sqlite:///chatbot.db"
|
14 |
engine = create_engine(DATABASE_URL)
|
15 |
Session = sessionmaker(bind=engine)
|
16 |
session = Session()
|
17 |
metadata = MetaData()
|
18 |
|
|
|
|
|
|
|
19 |
def create_table(table_name, columns):
|
20 |
if table_name in engine.table_names():
|
21 |
return f"Table '{table_name}' already exists."
|
|
|
50 |
|
51 |
return f"Table '{table_name}' updated successfully."
|
52 |
|
53 |
+
app = FastAPI()
|
54 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
55 |
+
|
56 |
+
class ConnectionManager:
|
57 |
+
def __init__(self):
|
58 |
+
self.active_connections: dict[str, WebSocket] = {}
|
59 |
+
|
60 |
+
async def connect(self, websocket: WebSocket, username: str):
|
61 |
+
await websocket.accept()
|
62 |
+
self.active_connections[username] = websocket
|
63 |
+
|
64 |
+
def disconnect(self, username: str):
|
65 |
+
self.active_connections.pop(username, None)
|
66 |
+
|
67 |
+
async def broadcast(self, message: str):
|
68 |
+
for connection in self.active_connections.values():
|
69 |
+
await connection.send_text(message)
|
70 |
+
|
71 |
+
manager = ConnectionManager()
|
72 |
+
|
73 |
+
@app.websocket("/ws/{username}")
|
74 |
+
async def websocket_endpoint(websocket: WebSocket, username: str, token: str = Depends(oauth2_scheme)):
|
75 |
+
await manager.connect(websocket, username)
|
76 |
+
try:
|
77 |
+
while True:
|
78 |
+
data = await websocket.receive_text()
|
79 |
+
await manager.broadcast(f"{username}: {data}")
|
80 |
+
except WebSocketDisconnect:
|
81 |
+
manager.disconnect(username)
|
82 |
+
|
83 |
+
@app.post("/token")
|
84 |
+
async def login():
|
85 |
+
# Simplified token generation for demo purposes
|
86 |
+
return {"access_token": "fake_token", "token_type": "bearer"}
|
87 |
+
|
88 |
+
@app.post("/chatbot")
|
89 |
+
async def chatbot(task: str, table_name: str, columns: str):
|
90 |
+
response, description = handle_chatbot(task, table_name, columns)
|
91 |
+
return {"result": response, "description": description}
|
92 |
+
|
93 |
+
@app.get("/")
|
94 |
+
async def get():
|
95 |
+
return HTMLResponse("""
|
96 |
+
<html>
|
97 |
+
<head>
|
98 |
+
<title>Real-time Chat</title>
|
99 |
+
</head>
|
100 |
+
<body>
|
101 |
+
<h1>WebSocket Chat</h1>
|
102 |
+
<input id="messageText" type="text" autocomplete="off"/>
|
103 |
+
<button onclick="sendMessage()">Send</button>
|
104 |
+
<ul id='messages'>
|
105 |
+
</ul>
|
106 |
+
<script>
|
107 |
+
var ws = new WebSocket("ws://localhost:8000/ws/test_user");
|
108 |
+
ws.onmessage = function(event) {
|
109 |
+
var messages = document.getElementById('messages')
|
110 |
+
var message = document.createElement('li')
|
111 |
+
var content = document.createTextNode(event.data)
|
112 |
+
message.appendChild(content)
|
113 |
+
messages.appendChild(message)
|
114 |
+
};
|
115 |
+
function sendMessage() {
|
116 |
+
var input = document.getElementById("messageText")
|
117 |
+
ws.send(input.value)
|
118 |
+
input.value = ''
|
119 |
+
}
|
120 |
+
</script>
|
121 |
+
</body>
|
122 |
+
</html>
|
123 |
+
""")
|
124 |
+
|
125 |
+
# Image generation setup
|
126 |
+
image_generator = pipeline("image-generation", model="CompVis/stable-diffusion-v1-4")
|
127 |
+
|
128 |
+
# Helper functions
|
129 |
def chatbot_response(task, table_name=None, columns=None):
|
130 |
if task == "create_table":
|
131 |
if table_name and columns:
|
|
|
140 |
else:
|
141 |
result = "Unsupported task. Use 'create_table' or 'edit_table'."
|
142 |
|
|
|
143 |
description = f"Task: {task}, Table Name: {table_name}, Columns: {columns}"
|
144 |
+
return result, description
|
|
|
|
|
145 |
|
146 |
def handle_chatbot(task, table_name, columns):
|
147 |
if task not in ['create_table', 'edit_table']:
|
|
|
160 |
return image
|
161 |
|
162 |
# Gradio interface setup
|
163 |
+
def handle_gradio_chatbot(task, table_name, columns):
|
164 |
+
response, description = handle_chatbot(task, table_name, columns)
|
165 |
+
image = generate_image(description)
|
166 |
+
return response, image
|
167 |
+
|
168 |
task_input = gr.inputs.Textbox(lines=1, placeholder="Task (create_table or edit_table)")
|
169 |
table_name_input = gr.inputs.Textbox(lines=1, placeholder="Table Name")
|
170 |
columns_input = gr.inputs.Textbox(lines=2, placeholder="Columns (JSON format: {'column1': 'type', 'column2': 'type'})")
|
171 |
|
172 |
interface = gr.Interface(
|
173 |
+
fn=handle_gradio_chatbot,
|
174 |
inputs=[task_input, table_name_input, columns_input],
|
175 |
outputs=[gr.outputs.Textbox(), gr.outputs.Image(type="pil")],
|
176 |
+
title="Multiplayer Game with SQL Database and Image Generation",
|
177 |
+
description="A multiplayer game interface to create and edit SQL tables with image generation."
|
178 |
)
|
179 |
|
180 |
+
# Function to run FastAPI server in the background
|
181 |
+
def run_server():
|
182 |
+
import uvicorn
|
183 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
184 |
+
|
185 |
+
# Run FastAPI server in a separate thread
|
186 |
+
import threading
|
187 |
+
threading.Thread(target=run_server, daemon=True).start()
|
188 |
+
|
189 |
+
# Launch Gradio interface
|
190 |
+
interface.launch()
|