import asyncio import json from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends from fastapi.responses import HTMLResponse from fastapi.security import OAuth2PasswordBearer from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table from sqlalchemy.orm import sessionmaker import gradio as gr from transformers import pipeline from PIL import Image # Database Setup DATABASE_URL = "sqlite:///chatbot.db" engine = create_engine(DATABASE_URL) Session = sessionmaker(bind=engine) session = Session() metadata = MetaData() def create_table(table_name, columns): if table_name in engine.table_names(): return f"Table '{table_name}' already exists." columns_list = [Column('id', Integer, primary_key=True)] for col_name, col_type in columns.items(): if col_type.lower() == 'string': columns_list.append(Column(col_name, String)) elif col_type.lower() == 'integer': columns_list.append(Column(col_name, Integer)) else: return "Unsupported column type. Use 'String' or 'Integer'." new_table = Table(table_name, metadata, *columns_list) metadata.create_all(engine) return f"Table '{table_name}' created successfully." def edit_table(table_name, columns): if table_name not in engine.table_names(): return f"Table '{table_name}' does not exist." table = Table(table_name, metadata, autoload_with=engine) for col_name, col_type in columns.items(): if col_name not in table.c: if col_type.lower() == 'string': new_column = Column(col_name, String) elif col_type.lower() == 'integer': new_column = Column(col_name, Integer) else: return "Unsupported column type. Use 'String' or 'Integer'." new_column.create(table, populate_default=True) return f"Table '{table_name}' updated successfully." app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class ConnectionManager: def __init__(self): self.active_connections: dict[str, WebSocket] = {} async def connect(self, websocket: WebSocket, username: str): await websocket.accept() self.active_connections[username] = websocket def disconnect(self, username: str): self.active_connections.pop(username, None) async def broadcast(self, message: str): for connection in self.active_connections.values(): await connection.send_text(message) manager = ConnectionManager() @app.websocket("/ws/{username}") async def websocket_endpoint(websocket: WebSocket, username: str, token: str = Depends(oauth2_scheme)): await manager.connect(websocket, username) try: while True: data = await websocket.receive_text() await manager.broadcast(f"{username}: {data}") except WebSocketDisconnect: manager.disconnect(username) @app.post("/token") async def login(): # Simplified token generation for demo purposes return {"access_token": "fake_token", "token_type": "bearer"} @app.post("/chatbot") async def chatbot(task: str, table_name: str, columns: str): response, description = handle_chatbot(task, table_name, columns) return {"result": response, "description": description} @app.get("/") async def get(): return HTMLResponse("""