CoolFace
Apppublic

Narutolxy1024/nl2sql-agent

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py62 linesDownload Raw Back to root
1import gradio as gr2import pandas as pd3from pandasql import sqldf4 5# 模拟数据库表6products = pd.DataFrame({7    "product_id": [1, 2, 3, 4, 5],8    "name": ["iPhone 14", "Galaxy S22", "Sony WH-1000XM5", "MacBook Pro", "Echo Dot"],9    "category": ["Electronics", "Electronics", "Audio", "Computers", "Smart Home"],10    "price": [799.99, 699.99, 399.99, 1999.99, 49.99],11    "stock": [50, 40, 30, 20, 70]12})13 14orders = pd.DataFrame({15    "order_id": [1, 2, 3],16    "order_number": ["ORD001", "ORD002", "ORD003"],17    "customer_id": [1, 2, 3],18    "total_amount": [1599.98, 699.99, 399.99],19    "status": ["PAID", "PAID", "PENDING"]20})21 22customers = pd.DataFrame({23    "customer_id": [1, 2, 3],24    "name": ["Alice", "Bob", "Charlie"],25    "email": ["alice@example.com", "bob@example.com", "charlie@example.com"],26    "phone": ["1234567890", "2345678901", "3456789012"]27})28 29order_items = pd.DataFrame({30    "order_item_id": [1, 2, 3],31    "order_id": [1, 2, 3],32    "product_id": [1, 2, 3],33    "quantity": [2, 1, 1],34    "subtotal": [1599.98, 699.99, 399.99]35})36 37# 定义查询函数38def query_to_sql(sql_query):39    try:40        # 将 Pandas 数据帧作为 SQL 查询的上下文41        context = {42            "products": products,43            "orders": orders,44            "customers": customers,45            "order_items": order_items46        }47        result = sqldf(sql_query, context)48        return result.to_string(index=False)  # 返回查询结果49    except Exception as e:50        return f"Error: {str(e)}"51 52# 创建 Gradio 界面53interface = gr.Interface(54    fn=query_to_sql,55    inputs="text",56    outputs="text",57    title="SQL Query Simulator",58    description="输入 SQL 查询语句,模拟查询结果。"59)60 61# 启动应用62interface.launch()