File size: 6,850 Bytes
b689891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595b5e1
 
 
a495cca
3032303
595b5e1
a495cca
 
 
595b5e1
 
a495cca
b689891
 
 
a495cca
 
 
b689891
 
a495cca
 
 
 
595b5e1
b689891
a495cca
 
 
 
b689891
 
a495cca
 
b689891
 
 
595b5e1
 
a495cca
595b5e1
a495cca
595b5e1
b689891
 
 
 
 
 
 
 
a495cca
 
b689891
a495cca
 
 
 
 
 
b689891
 
 
a495cca
 
 
b689891
 
 
a495cca
 
 
 
b689891
a495cca
 
 
b689891
 
a495cca
 
 
b689891
 
 
a495cca
 
 
 
ef2e31e
b689891
a495cca
7243569
 
a495cca
 
632eedb
b689891
 
 
a495cca
 
 
b689891
 
 
a495cca
b689891
 
a495cca
 
 
 
b689891
a495cca
 
 
b689891
 
 
a495cca
b689891
 
 
 
 
 
 
 
a495cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# from fastapi import FastAPI, Request, Form, UploadFile, File
# from fastapi.templating import Jinja2Templates
# from fastapi.responses import HTMLResponse, RedirectResponse
# from fastapi.staticfiles import StaticFiles
# from dotenv import load_dotenv
# import os, io
# from PIL import Image
# import markdown
# import google.generativeai as genai

# # Load environment variable
# load_dotenv()
# API_KEY = os.getenv("GOOGLE_API_KEY")
# genai.configure(api_key=API_KEY)

# app = FastAPI()
# templates = Jinja2Templates(directory="templates")
# app.mount("/static", StaticFiles(directory="static"), name="static")

# model = genai.GenerativeModel('gemini-2.0-flash')

# # Create a global chat session
# chat = None
# chat_history = []

# @app.get("/", response_class=HTMLResponse)
# async def root(request: Request):
#     return templates.TemplateResponse("index.html", {
#         "request": request,
#         "chat_history": chat_history,
#     })

# @app.post("/", response_class=HTMLResponse)
# async def handle_input(
#     request: Request,
#     user_input: str = Form(...),
#     image: UploadFile = File(None)
# ):
#     global chat, chat_history
    
#     # Initialize chat session if needed
#     if chat is None:
#         chat = model.start_chat(history=[])
    
#     parts = []
#     if user_input:
#         parts.append(user_input)

#     # For display in the UI
#     user_message = user_input
    
#     if image and image.content_type.startswith("image/"):
#         data = await image.read()
#         try:
#             img = Image.open(io.BytesIO(data))
#             parts.append(img)
#             user_message += " [Image uploaded]"  # Indicate image in chat history
#         except Exception as e:
#             chat_history.append({
#                 "role": "model",
#                 "content": markdown.markdown(f"**Error loading image:** {e}")
#             })
#             return RedirectResponse("/", status_code=303)

#     # Store user message for display
#     chat_history.append({"role": "user", "content": user_message})

#     try:
#         # Send message to Gemini model
#         resp = chat.send_message(parts)
#         # Add model response to history
#         raw = resp.text
#         chat_history.append({"role": "model", "content": raw})

#     except Exception as e:
#         err = f"**Error:** {e}"
#         chat_history.append({
#             "role": "model",
#             "content": markdown.markdown(err)
#         })

#     # Post-Redirect-Get
#     return RedirectResponse("/", status_code=303)

# # Clear chat history and start fresh
# @app.post("/new")
# async def new_chat():
#     global chat, chat_history
#     chat = None
#     chat_history.clear()
#     return RedirectResponse("/", status_code=303)
import os
import io
import streamlit as st
from dotenv import load_dotenv
from PIL import Image
import google.generativeai as genai
from langgraph.graph import StateGraph, END
from typing import TypedDict, List, Union

# ---------------------------
# Load API Key
# ---------------------------
load_dotenv()
API_KEY = os.getenv("GOOGLE_API_KEY")
genai.configure(api_key=API_KEY)

model = genai.GenerativeModel("gemini-2.0-flash")

# ---------------------------
# State Definition
# ---------------------------
class ChatState(TypedDict):
    user_input: str
    image: Union[Image.Image, None]
    raw_response: str
    final_response: str
    chat_history: List[dict]


# ---------------------------
# LangGraph Nodes
# ---------------------------
def input_node(state: ChatState) -> ChatState:
    return state


def processing_node(state: ChatState) -> ChatState:
    parts = [state["user_input"]]
    if state["image"]:
        parts.append(state["image"])

    try:
        chat = model.start_chat(history=[])
        resp = chat.send_message(parts)
        state["raw_response"] = resp.text
    except Exception as e:
        state["raw_response"] = f"Error: {e}"

    return state


def checking_node(state: ChatState) -> ChatState:
    raw = state["raw_response"]

    # Remove unnecessary lines from Gemini responses
    if raw.startswith("Sure!") or "The image shows" in raw:
        lines = raw.split("\n")
        filtered = [
            line for line in lines
            if not line.startswith("Sure!") and "The image shows" not in line
        ]
        final = "\n".join(filtered).strip()
        state["final_response"] = final
    else:
        state["final_response"] = raw

    # Save to session chat history
    st.session_state.chat_history.append({"role": "user", "content": state["user_input"]})
    st.session_state.chat_history.append({"role": "model", "content": state["final_response"]})

    return state


# ---------------------------
# Build the LangGraph
# ---------------------------
builder = StateGraph(ChatState)
builder.add_node("input", input_node)
builder.add_node("processing", processing_node)
builder.add_node("checking", checking_node)

builder.set_entry_point("input")
builder.add_edge("input", "processing")
builder.add_edge("processing", "checking")
builder.add_edge("checking", END)

graph = builder.compile()

# ---------------------------
# Streamlit UI Setup
# ---------------------------
st.set_page_config(page_title="Math Chatbot", layout="centered")
st.title("Math Chatbot")

# Initialize session state
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []

# Display chat history
for msg in st.session_state.chat_history:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# ---------------------------
# Sidebar
# ---------------------------
with st.sidebar:
    st.header("Options")
    if st.button("New Chat"):
        st.session_state.chat_history = []
        st.rerun()

# ---------------------------
# Chat Input Form
# ---------------------------
with st.form("chat_form", clear_on_submit=True):
    user_input = st.text_input("Your message:", placeholder="Ask your math problem here")

    uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
    
    submitted = st.form_submit_button("Send")

    if submitted:
        # Load image safely
        image = None
        if uploaded_file:
            try:
                image = Image.open(io.BytesIO(uploaded_file.read()))
            except Exception as e:
                st.error(f"Error loading image: {e}")
                st.stop()

        # Prepare state
        input_state = {
            "user_input": user_input,
            "image": image,
            "raw_response": "",
            "final_response": "",
            "chat_history": st.session_state.chat_history,
        }

        # Run LangGraph
        output = graph.invoke(input_state)

        # Show model response
        with st.chat_message("model"):
            st.markdown(output["final_response"])