CodeFlame commited on
Commit
d043782
Β·
verified Β·
1 Parent(s): 2a7fe6e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +148 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,150 @@
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
+ from huggingface_hub import InferenceClient
3
+ from duckduckgo_search import DDGS
4
+ from PIL import Image
5
+ import datetime
6
+ import io
7
 
8
+ # =====================================================================
9
+ # 1. LIVE CONFIGURATION & UI CUSTOMIZATION INTERFACE
10
+ # =====================================================================
11
+ st.set_page_config(page_title="SparkHelix AI", page_icon="🧬", layout="wide")
12
+
13
+ st.sidebar.title("🧬 SparkHelix Settings")
14
+ st.sidebar.markdown("---")
15
+
16
+ st.sidebar.subheader("🎨 UI Theme Engine")
17
+ accent_color = st.sidebar.color_picker("Brand Highlight Color", "#3b82f6")
18
+
19
+ st.sidebar.subheader("🧠 Model Tuning Parameters")
20
+ creativity = st.sidebar.slider("AI Engine Creativity (Temperature)", 0.0, 1.0, 0.4, 0.05)
21
+ max_tokens = st.sidebar.slider("Maximum Length Limit", 128, 1024, 512, 64)
22
+
23
+ # Dynamic CSS injection based on sidebar configurations
24
+ st.markdown(f"<style>div.stButton > button:first-child {{ background-color: {accent_color}; color: white; border: none; }}</style>", unsafe_allow_html=True)
25
+
26
+ # =====================================================================
27
+ # 2. CHAT TOPIC JOURNAL ARCHIVE SETUP (PERSISTENT HISTORY)
28
+ # =====================================================================
29
+ if "all_chats" not in st.session_state:
30
+ st.session_state.all_chats = {"Default Topic": []}
31
+ if "active_chat" not in st.session_state:
32
+ st.session_state.active_chat = "Default Topic"
33
+
34
+ st.sidebar.subheader("πŸ’¬ Historical Chat Topics")
35
+ if st.sidebar.button("βž• Create New Conversation Thread"):
36
+ timestamp = datetime.datetime.now().strftime("%I:%M %p")
37
+ new_id = f"Chat Topic - {timestamp}"
38
+ st.session_state.all_chats[new_id] = []
39
+ st.session_state.active_chat = new_id
40
+ st.rerun()
41
+
42
+ chosen_chat = st.sidebar.radio(
43
+ "Select Context History Window:",
44
+ options=list(st.session_state.all_chats.keys()),
45
+ index=list(st.session_state.all_chats.keys()).index(st.session_state.active_chat)
46
+ )
47
+ st.session_state.active_chat = chosen_chat
48
+
49
+ # =====================================================================
50
+ # 3. AI BACKEND CORE ARCHITECTURE
51
+ # =====================================================================
52
+ TEXT_MODEL = "Qwen/Qwen2.5-7B-Instruct"
53
+ IMAGE_MODEL = "black-forest-labs/FLUX.1-dev"
54
+ client = InferenceClient()
55
+
56
+ def query_web_search(text_query):
57
+ try:
58
+ with DDGS() as ddgs:
59
+ results = [r for r in ddgs.text(text_query, max_results=3)]
60
+ if results:
61
+ return "\n".join([f"[{res['title']}] {res['body']}" for res in results])
62
+ except:
63
+ return "Network infrastructure too congested for query lookup."
64
+ return "No contextual data fragments found."
65
+
66
+ # =====================================================================
67
+ # 4. MAIN INTERFACE LOGIC RENDER CODES
68
+ # =====================================================================
69
+ st.title(f"🧬 SparkHelix AI Console: {st.session_state.active_chat}")
70
+ st.caption("Integrated Core Environment: Multi-Session Logs, Live Web Connect, Drawing Engine & File Processing Matrix.")
71
+
72
+ active_log = st.session_state.all_chats[st.session_state.active_chat]
73
+
74
+ for message in active_log:
75
+ with st.chat_message(message["role"]):
76
+ if "content" in message and message["content"]:
77
+ st.markdown(message["content"])
78
+ if "file_meta" in message:
79
+ st.info(message["file_meta"])
80
+ if "img_data" in message:
81
+ st.image(message["img_data"])
82
+ if "vid_placeholder" in message:
83
+ st.warning(message["vid_placeholder"])
84
+
85
+ st.subheader("πŸŽ™οΈ Dictation Node & Attachment System")
86
+ mic_input = st.audio_input("Microphone Wave Scanner")
87
+ if mic_input:
88
+ st.success("βœ” Audio block encoded! Connection payload mapped.")
89
+
90
+ prompt_object = st.chat_input("Ask SparkHelix, upload elements, or execute commands (/draw or /video)...", accept_file=True)
91
+
92
+ if prompt_object:
93
+ user_string = prompt_object.text if prompt_object.text else ""
94
+ attached_file = prompt_object.files[0] if prompt_object.files else None
95
+
96
+ with st.chat_message("user"):
97
+ if user_string:
98
+ st.markdown(user_string)
99
+ if attached_file:
100
+ st.caption(f"πŸ“ Processing File: {attached_file.name} | Size: {attached_file.size} bytes")
101
+
102
+ log_entry = {"role": "user", "content": user_string}
103
+ if attached_file:
104
+ log_entry["file_meta"] = f"Processed Input Asset Archive: {attached_file.name}"
105
+ active_log.append(log_entry)
106
+
107
+ with st.chat_message("assistant"):
108
+ try:
109
+ if user_string.lower().startswith("/draw"):
110
+ generation_prompt = user_string.replace("/draw", "").strip()
111
+ with st.spinner(f"🎨 Rendering visual matrix for: '{generation_prompt}'..."):
112
+ img_bytes = client.text_to_image(generation_prompt, model=IMAGE_MODEL)
113
+ st.image(img_bytes, caption="SparkHelix Render Output Canvas")
114
+ active_log.append({
115
+ "role": "assistant",
116
+ "content": f"Visual render completed for asset string: '{generation_prompt}'",
117
+ "img_data": img_bytes
118
+ })
119
+
120
+ elif user_string.lower().startswith("/video"):
121
+ video_prompt = user_string.replace("/video", "").strip()
122
+ with st.spinner(f"🎬 Compiling temporal animation sequences for: '{video_prompt}'..."):
123
+ placeholder_msg = f"🎬 Video Sequence Initialized: '{video_prompt}'. Free tier constraints notice: Running intensive video processing nodes requires scaling up the Space instance hardware to a GPU tier."
124
+ st.warning(placeholder_msg)
125
+ active_log.append({
126
+ "role": "assistant",
127
+ "content": "Video processing frame initialization output block.",
128
+ "vid_placeholder": placeholder_msg
129
+ })
130
+
131
+ else:
132
+ with st.spinner("Decoding multi-channel parameters..."):
133
+ search_context = ""
134
+ if len(user_string) > 10:
135
+ search_context = query_web_search(user_string)
136
+
137
+ engineered_prompt = f"System Instruction: You are SparkHelix AI. Contextual Web Data: {search_context}\nUser Input Parameters: {user_string}"
138
+ ai_reply = client.text_generation(
139
+ model=TEXT_MODEL,
140
+ prompt=engineered_prompt,
141
+ max_new_tokens=max_tokens,
142
+ temperature=creativity
143
+ )
144
+ st.markdown(ai_reply)
145
+ active_log.append({"role": "assistant", "content": ai_reply})
146
+
147
+ st.session_state.all_chats[st.session_state.active_chat] = active_log
148
+
149
+ except Exception as e:
150
+ st.error(f"Core execution pathway bottleneck flagged. Resolution: {e}")