kumrsanjeev commited on
Commit
0f42f06
·
verified ·
1 Parent(s): 86498a8

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +104 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,110 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
+ import urllib.parse
4
+ import re
5
 
6
+ # 1. Page Configuration & Custom CSS (Clean Interface)
7
+ st.set_page_config(page_title="Nexus Flow AI Pro", page_icon="⚡", layout="wide")
8
+
9
+ st.markdown("""
10
+ <style>
11
+ #MainMenu {visibility: hidden;}
12
+ footer {visibility: hidden;}
13
+ header {visibility: hidden;}
14
+ .stChatMessage { border-radius: 15px; margin-bottom: 10px; border: 1px solid #333; }
15
+ .stStatusWidget { border-radius: 10px; }
16
+ </style>
17
+ """, unsafe_allow_html=True)
18
 
19
+ # 2. API Security (Secrets se Key uthayega)
20
+ if "GOOGLE_API_KEY" in st.secrets:
21
+ genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
22
+ else:
23
+ st.error("⚠️ Settings > Secrets mein 'GOOGLE_API_KEY' add karein!")
24
+ st.stop()
25
 
26
+ # 3. The "ChatGPT" Brain Instructions
27
+ instruction = """
28
+ You are Nexus Flow AI Pro, the digital avatar of Sanjeev.
29
+ - REASONING: For complex questions, you MUST first think step-by-step inside <thinking> tags.
30
+ - IMAGES: If asked for a photo/image/drawing, respond ONLY with: [GENERATE_IMAGE: highly detailed English prompt]
31
+ - STYLE: Speak in Hinglish. Be an expert in Video Editing (Punch Edit), Python, and SAT/JEE.
32
  """
33
 
34
+ # 4. Initialize Model & Memory
35
+ @st.cache_resource
36
+ def load_model():
37
+ return genai.GenerativeModel("gemini-1.5-flash", system_instruction=instruction)
38
+
39
+ model = load_model()
40
+
41
+ if "messages" not in st.session_state:
42
+ st.session_state.messages = []
43
+ if "chat_session" not in st.session_state:
44
+ st.session_state.chat_session = model.start_chat(history=[])
45
+
46
+ # Sidebar
47
+ with st.sidebar:
48
+ st.title("Nexus Flow Pro 🤖")
49
+ st.write("Owner: Sanjeev")
50
+ if st.button("🗑️ Clear Chat"):
51
+ st.session_state.messages = []
52
+ st.session_state.chat_session = model.start_chat(history=[])
53
+ st.rerun()
54
+
55
+ # 5. Display Chat History
56
+ for m in st.session_state.messages:
57
+ with st.chat_message(m["role"]):
58
+ st.markdown(m["content"])
59
+ if m.get("image"):
60
+ st.image(m["image"], caption="Generated by Nexus Flow")
61
+
62
+ # 6. User Input & Processing
63
+ if prompt := st.chat_input("Kaise help karu Sanjeev?"):
64
+ st.session_state.messages.append({"role": "user", "content": prompt})
65
+ with st.chat_message("user"):
66
+ st.markdown(prompt)
67
+
68
+ with st.chat_message("assistant"):
69
+ final_ans = ""
70
+ img_url = None
71
+
72
+ with st.status("Nexus Flow is thinking...", expanded=True) as status:
73
+ try:
74
+ # Get AI Response
75
+ response = st.session_state.chat_session.send_message(prompt)
76
+ full_res = response.text
77
+
78
+ # Logic A: Deep Reasoning Parsing
79
+ if "<thinking>" in full_res:
80
+ parts = full_res.split("</thinking>")
81
+ thinking_process = parts[0].replace("<thinking>", "").strip()
82
+ st.expander("🧠 My Reasoning Process", expanded=False).write(thinking_process)
83
+ final_ans = parts[1].strip()
84
+
85
+ # Logic B: Image Generation Parsing
86
+ if "[GENERATE_IMAGE:" in full_res:
87
+ match = re.search(r'\[GENERATE_IMAGE:\s*(.*?)\]', full_res)
88
+ if match:
89
+ raw_prompt = match.group(1).strip()
90
+ # Direct Image from Pollinations
91
+ img_url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(raw_prompt)}?width=1024&height=1024&model=flux&nologo=true"
92
+ final_ans = f"✅ Image Ready: **{raw_prompt}**"
93
+
94
+ if not final_ans:
95
+ final_ans = full_res
96
+
97
+ status.update(label="Analysis Complete!", state="complete")
98
+
99
+ except Exception as e:
100
+ final_ans = f"❌ Error: {str(e)}"
101
+ status.update(label="System Crash!", state="error")
102
+
103
+ # UI Update
104
+ st.markdown(final_ans)
105
+ if img_url:
106
+ st.image(img_url)
107
+
108
+ # Save to Session
109
+ st.session_state.messages.append({"role": "assistant", "content": final_ans, "image": img_url})
110
+