File size: 3,168 Bytes
81dac89
65995bf
81dac89
 
 
bbb2f85
81dac89
bbb2f85
 
 
 
81dac89
bbb2f85
 
81dac89
 
 
 
 
 
 
 
 
 
 
bbb2f85
81dac89
 
 
 
 
 
bbb2f85
81dac89
bbb2f85
81dac89
 
bbb2f85
81dac89
 
 
 
 
 
 
bbb2f85
 
81dac89
65995bf
81dac89
 
 
 
 
 
 
 
 
 
 
 
 
bbb2f85
81dac89
 
bbb2f85
81dac89
 
 
bbb2f85
81dac89
bbb2f85
5ff4451
 
 
bbb2f85
5ff4451
 
 
 
bbb2f85
81dac89
 
 
 
 
 
 
 
bbb2f85
81dac89
bbb2f85
81dac89
bbb2f85
81dac89
bbb2f85
 
 
 
 
81dac89
 
 
 
 
bbb2f85
 
 
81dac89
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import streamlit as st
from engine import run
from datetime import datetime

# =========================
# PAGE CONFIG
# =========================
st.set_page_config(
    page_title="Text-to-SQL AI",
    layout="wide"
)

st.title("🧠 Text-to-SQL Assistant")
st.caption("Ask questions in natural language. I’ll generate SQL using your database metadata.")

# =========================
# SESSION STATE
# =========================
if "messages" not in st.session_state:
    st.session_state.messages = []

if "transcript" not in st.session_state:
    st.session_state.transcript = []

# =========================
# CHAT HISTORY
# =========================
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"], unsafe_allow_html=True)

# =========================
# USER INPUT
# =========================
user_input = st.chat_input("Ask something like: 'Show employees in IT department'")

if user_input:
    # Display user message
    st.session_state.messages.append(
        {"role": "user", "content": user_input}
    )

    with st.chat_message("user"):
        st.markdown(user_input)

    # Call engine
    with st.spinner("Generating SQL..."):
        try:
            result = run(user_input)
        except Exception as e:
            result = {
                "status": "error",
                "message": str(e)
            }

    # =========================
    # BUILD RESPONSE
    # =========================
    reply = ""

    if result.get("status") == "ok":
        if result.get("message"):
            reply += f"### ✅ Result\n{result['message']}\n\n"

        if result.get("sql"):
            reply += "### 🧾 Generated SQL\n"
            reply += f"```sql\n{result['sql']}\n```"

    else:
        reply = f"❌ **Error:** {result.get('message')}"

    # Save transcript
    st.session_state.transcript.append({
        "timestamp": datetime.utcnow().isoformat(),
        "question": user_input,
        "reply": reply,
        "sql": result.get("sql"),
        "error": result.get("message") if result.get("status") != "ok" else None
    })

    # Show assistant reply
    st.session_state.messages.append(
        {"role": "assistant", "content": reply}
    )

    with st.chat_message("assistant"):
        st.markdown(reply, unsafe_allow_html=True)

# =========================
# DOWNLOAD LOG
# =========================
def download_transcript():
    lines = []
    for i, t in enumerate(st.session_state.transcript, 1):
        lines.append(f"\n--- Query {i} ---")
        lines.append(f"Time: {t['timestamp']}")
        lines.append(f"Question: {t['question']}")
        lines.append(f"Reply:\n{t['reply']}")
        if t.get("sql"):
            lines.append(f"SQL:\n{t['sql']}")
    return "\n".join(lines)

if st.session_state.transcript:
    st.divider()
    st.download_button(
        "⬇️ Download Query Log",
        data=download_transcript(),
        file_name="text_to_sql_log.txt",
        mime="text/plain",
        use_container_width=True
    )