Rudert commited on
Commit
bf515d7
ยท
verified ยท
1 Parent(s): 95dff6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -145
app.py CHANGED
@@ -1,179 +1,136 @@
1
  import streamlit as st
2
  from g4f.client import Client
3
  import sqlite3
4
- import google.generativeai as genai
5
- # import pyttsx3
6
  import pyperclip
7
  import os
8
 
9
- api_key = os.getenv("Gemini_api")
 
 
 
 
10
 
11
 
12
-
13
-
14
- st.set_page_config(page_title="DarkGPT",
15
- page_icon="๐Ÿค–",
16
- initial_sidebar_state="expanded"
17
- )
18
-
19
 
20
  def local_css(file_name):
21
- with open(file_name) as f:
22
- st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
23
-
 
 
24
 
25
  local_css("style.css")
26
 
27
- # Create a connection to the database
28
- conn = sqlite3.connect('chat_history.db')
29
- c = conn.cursor()
 
 
 
 
 
30
 
31
- # Create table if not exists
32
- try:
33
- c.execute('''CREATE TABLE IF NOT EXISTS chat_history
34
- (conversation_id INTEGER, role TEXT, content TEXT)''')
35
- conn.commit()
36
- except Exception as e:
37
- st.error(f"An error occurred: {e}")
38
 
 
 
 
 
39
 
40
 
41
- # Streamlit app
42
  def main():
43
- try:
44
- if "chat_history" not in st.session_state:
45
- st.session_state.chat_history = []
46
-
47
- if "conversation_id" not in st.session_state:
48
- st.session_state.conversation_id = 1
49
-
50
- models = {
51
- "๐Ÿš€ Airoboros 70B": "airoboros-70b",
52
- "๐Ÿ‘‘ Gemini 1.0": "gemini-1.0-pro",
53
- "๐Ÿงจ Gemini 1.0 Pro ": "gemini-1.0-pro-001",
54
- "โšก Gemini 1.0 pro latest": "gemini-1.0-pro-latest",
55
- "๐Ÿ”ฎ Gemini Pro": "gemini-pro",
56
- }
57
-
58
- columns = st.columns(3) # Split the layout into three columns
59
- with columns[0]:
60
- st.header("DarkGPT")
61
-
62
- with columns[2]:
63
-
64
- selected_model_display_name = st.selectbox("Select Model", list(models.keys()), index=0)
65
- selected_model = models[selected_model_display_name]
66
-
67
- with columns[1]:
68
- pass
69
- # if st.button("summarize"):
70
- # st.switch_page('pages/summarize.py')
71
-
72
-
73
- # Sidebar (left side) - New chat button
74
- if st.sidebar.button("โœจ New Chat", key="new_chat_button"):
75
- st.session_state.chat_history.clear()
76
- st.session_state.conversation_id += 1
77
-
78
- # Sidebar (left side) - Display saved chat
79
- st.sidebar.write("Chat History")
80
- c.execute("SELECT DISTINCT conversation_id FROM chat_history")
81
- conversations = c.fetchall()
82
- for conv_id in reversed(conversations):
83
- c.execute("SELECT content FROM chat_history WHERE conversation_id=? AND role='bot' LIMIT 1",
84
- (conv_id[0],))
85
- first_bot_response = c.fetchone()
86
- if first_bot_response:
87
- if st.sidebar.button(" ".join(first_bot_response[0].split()[0:5])):
88
- display_conversation(conv_id[0])
89
-
90
- # Sidebar (left side) - Clear Chat History button
91
- if st.sidebar.button("Clear Chat History โœ–๏ธ"):
92
- st.session_state.chat_history.clear()
93
- c.execute("DELETE FROM chat_history")
94
- conn.commit()
95
-
96
- # Main content area (center)
97
- st.markdown("---")
98
-
99
- user_input = st.chat_input("Ask Anything ...")
100
-
101
- if user_input:
102
- if selected_model == "airoboros-70b":
103
  try:
104
- client = Client()
105
  response = client.chat.completions.create(
106
- model=models[selected_model_display_name],
107
- messages=[{"role": "user", "content": user_input}],
 
 
108
  )
109
  bot_response = response.choices[0].message.content
 
110
 
111
- st.session_state.chat_history.append({"role": "user", "content": user_input})
112
- st.session_state.chat_history.append({"role": "bot", "content": bot_response})
113
 
114
- # Store chat in the database
115
- for chat in st.session_state.chat_history:
116
- c.execute("INSERT INTO chat_history VALUES (?, ?, ?)",
117
- (st.session_state.conversation_id, chat["role"], chat["content"]))
 
 
118
  conn.commit()
119
 
120
- # Display chat history
121
- for index, chat in enumerate(st.session_state.chat_history):
122
- with st.chat_message(chat["role"]):
123
- if chat["role"] == "user":
124
- st.markdown(chat["content"])
125
- elif chat["role"] == "bot":
126
- st.markdown(chat["content"])
127
-
128
-
129
- except Exception as e:
130
- st.error(f"An error occurred: {e}")
131
-
132
- else:
133
- try:
134
- # GEMINI Replace with your Gemini Api key
135
- GOOGLE_API_KEY = api_key
136
- genai.configure(api_key=GOOGLE_API_KEY)
137
- model = genai.GenerativeModel(selected_model)
138
- prompt = user_input
139
- response = model.generate_content(prompt)
140
- bot_response = response.candidates[0].content.parts[0].text
141
-
142
- st.session_state.chat_history.append({"role": "user", "content": user_input})
143
- st.session_state.chat_history.append({"role": "bot", "content": bot_response})
144
-
145
- # Store chat in the database
146
- for chat in st.session_state.chat_history:
147
- c.execute("INSERT INTO chat_history VALUES (?, ?, ?)",
148
- (st.session_state.conversation_id, chat["role"], chat["content"]))
149
- conn.commit()
150
-
151
- for index, chat in enumerate(st.session_state.chat_history):
152
- with st.chat_message(chat["role"]):
153
- if chat["role"] == "user":
154
- st.markdown(chat["content"])
155
- elif chat["role"] == "bot":
156
- st.markdown(chat["content"])
157
-
158
  except Exception as e:
159
- st.error(f"An error occurred: {e}")
160
-
161
-
162
-
163
 
164
 
165
- except Exception as e:
166
- st.error(f"An error occurred: {e}")
 
167
 
168
 
169
- def display_conversation(conversation_id):
170
- c.execute("SELECT * FROM chat_history WHERE conversation_id=?", (conversation_id,))
171
- chats = c.fetchall()
172
- st.markdown(f"### Conversation")
173
- for chat in chats:
174
- st.markdown(f"{chat[1]}")
175
- st.markdown(f"{chat[2]}")
176
 
177
 
178
  if __name__ == "__main__":
179
- main()
 
1
  import streamlit as st
2
  from g4f.client import Client
3
  import sqlite3
 
 
4
  import pyperclip
5
  import os
6
 
7
+ # --- KONFIGURASI GROQ (via environment variable) ---
8
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Set di .env atau environment
9
+ if not GROQ_API_KEY:
10
+ st.error("GROQ_API_KEY tidak ditemukan! Tambahkan di environment atau .env")
11
+ st.stop()
12
 
13
 
14
+ conn = sqlite3.connect('chat_history.db', check_same_thread=False)
15
+ c = conn.cursor()
16
+ c.execute('''CREATE TABLE IF NOT EXISTS chat_history
17
+ (conversation_id INTEGER, role TEXT, content TEXT)''')
18
+ conn.commit()
 
 
19
 
20
  def local_css(file_name):
21
+ try:
22
+ with open(file_name) as f:
23
+ st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
24
+ except FileNotFoundError:
25
+ st.warning("style.css tidak ditemukan. Mengabaikan custom CSS.")
26
 
27
  local_css("style.css")
28
 
29
+ # --- MODEL LIST (via g4f + Groq) ---
30
+ models = {
31
+ "๐Ÿค– Qwen 2.5 Coder (72B)": "qwen2.5-coder-32b",
32
+ "๐Ÿš€ LLaMA 3.1 70B": "llama-3.1-70b-versatile",
33
+ "โšก LLaMA 3.1 8B": "llama-3.1-8b-instant",
34
+ "๐Ÿง  Qwen 2.5 72B": "qwen2.5-72b-instruct",
35
+ "โš™๏ธ Mixtral 8x7B": "mixtral-8x7b-32768",
36
+ }
37
 
 
 
 
 
 
 
 
38
 
39
+ client = Client(
40
+ provider="groq",
41
+ api_key=GROQ_API_KEY
42
+ )
43
 
44
 
 
45
  def main():
46
+ st.set_page_config(page_title="DarkGPT", page_icon="๐Ÿค–", initial_sidebar_state="expanded")
47
+
48
+ # Inisialisasi session state
49
+ if "chat_history" not in st.session_state:
50
+ st.session_state.chat_history = []
51
+ if "conversation_id" not in st.session_state:
52
+ st.session_state.conversation_id = 1
53
+
54
+ # Header + Model Selector
55
+ col1, col2, col3 = st.columns([1, 1, 1])
56
+ with col1:
57
+ st.header("DarkGPT")
58
+ with col3:
59
+ selected_model_name = st.selectbox("Pilih Model", list(models.keys()), index=0)
60
+ selected_model = models[selected_model_name]
61
+
62
+ # Sidebar: New Chat
63
+ if st.sidebar.button("โœจ New Chat"):
64
+ st.session_state.chat_history = []
65
+ st.session_state.conversation_id += 1
66
+ st.rerun()
67
+
68
+ # Sidebar: Load History
69
+ st.sidebar.write("### Chat History")
70
+ c.execute("SELECT DISTINCT conversation_id FROM chat_history ORDER BY conversation_id DESC")
71
+ for (conv_id,) in c.fetchall():
72
+ c.execute("SELECT content FROM chat_history WHERE conversation_id = ? AND role = 'bot' LIMIT 1", (conv_id,))
73
+ first_msg = c.fetchone()
74
+ if first_msg:
75
+ preview = " ".join(first_msg[0].split()[:6]) + "..."
76
+ if st.sidebar.button(preview, key=f"load_{conv_id}"):
77
+ load_conversation(conv_id)
78
+
79
+ # Sidebar: Clear All
80
+ if st.sidebar.button("๐Ÿ—‘๏ธ Clear All History"):
81
+ c.execute("DELETE FROM chat_history")
82
+ conn.commit()
83
+ st.session_state.chat_history = []
84
+ st.rerun()
85
+
86
+ # Chat Input
87
+ st.markdown("---")
88
+ if user_input := st.chat_input("Ketik pesan..."):
89
+ with st.chat_message("user"):
90
+ st.markdown(user_input)
91
+
92
+ # Simpan user message
93
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
94
+
95
+ # Generate response
96
+ with st.chat_message("assistant"):
97
+ with st.spinner("Thinking..."):
 
 
 
 
 
 
 
 
98
  try:
 
99
  response = client.chat.completions.create(
100
+ model=selected_model,
101
+ messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.chat_history],
102
+ temperature=0.7,
103
+ max_tokens=2048
104
  )
105
  bot_response = response.choices[0].message.content
106
+ st.markdown(bot_response)
107
 
108
+ # Simpan bot response
109
+ st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
110
 
111
+ # Simpan ke DB
112
+ for msg in st.session_state.chat_history[-2:]: # hanya 2 pesan terakhir
113
+ c.execute(
114
+ "INSERT INTO chat_history VALUES (?, ?, ?)",
115
+ (st.session_state.conversation_id, msg["role"], msg["content"])
116
+ )
117
  conn.commit()
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  except Exception as e:
120
+ st.error(f"Error: {str(e)}")
 
 
 
121
 
122
 
123
+ for msg in st.session_state.chat_history[:-2]:
124
+ with st.chat_message(msg["role"]):
125
+ st.markdown(msg["content"])
126
 
127
 
128
+ def load_conversation(conv_id):
129
+ c.execute("SELECT role, content FROM chat_history WHERE conversation_id = ? ORDER BY rowid", (conv_id,))
130
+ st.session_state.chat_history = [{"role": r, "content": c} for r, c in c.fetchall()]
131
+ st.session_state.conversation_id = conv_id
132
+ st.rerun()
 
 
133
 
134
 
135
  if __name__ == "__main__":
136
+ main()