Utkarsh Verma commited on
Commit
1ff88ce
Β·
1 Parent(s): 4531016

Changes in UI

Browse files
Files changed (2) hide show
  1. app.py +83 -35
  2. templates/index.html +116 -100
app.py CHANGED
@@ -10,6 +10,7 @@ HF_API_KEY = os.getenv("HF_API_KEY") # Store in environment variable
10
  API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
11
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
12
 
 
13
  @app.route('/')
14
  def home():
15
  return render_template('index.html')
@@ -17,57 +18,104 @@ def home():
17
  @app.route('/chat', methods=['POST'])
18
  def chat():
19
  user_message = request.json.get("message")
20
-
21
  if not user_message:
22
- return jsonify({"error": "Empty message received"})
23
 
24
  try:
25
- formatted_prompt = f"User: {user_message}\nBot:"
26
  payload = {
27
- "inputs": formatted_prompt,
28
- "parameters": {
29
- "temperature": 0.5, # πŸ”₯ Controls randomness (lower = more deterministic)
30
- "top_p": 0.9, # 🎯 Focus on high-probability words
31
- "max_new_tokens": 50, # ⏳ Limits response length
32
- "stop_sequences": ["User:", "You:", "user:"] # β›” Stops response at natural points
 
33
  }
34
- }
35
  response = requests.post(API_URL, headers=headers, json=payload)
36
  data = response.json()
37
- # print(response.status_code) # Debugging: Print the HTTP status
38
- # print(response.json()) # Debugging: Print the API response
39
 
40
- # if response.status_code == 200:
41
- # return response.json()[0]['generated_text']
42
- # else:
43
- # return f"Error: {response.status_code} - {response.json()}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
 
46
 
47
- if "error" in data:
48
- return jsonify({"reply": f"Error: {data['error']}"})
49
 
50
- # raw_output = data[0]['generated_text'] if isinstance(data, list) else data.get('generated_text', "No response")
51
- # reply = raw_output.split("Bot:")[-1].strip()
52
 
53
 
54
- # return jsonify({"reply": reply})
55
 
56
- raw_output = data[0]['generated_text'] if isinstance(data, list) else data.get('generated_text', "No response")
57
- # Clean up output
58
- if "Bot:" in raw_output:
59
- reply = raw_output.split("Bot:")[-1].strip()
60
- else:
61
- reply = raw_output.strip()
62
 
63
- for trailing in ["User", "You", "User:", "You:"]:
64
- if reply.endswith(trailing):
65
- reply = reply.rsplit(trailing, 1)[0].strip()
66
 
67
- return jsonify({"reply": reply})
68
 
69
- except Exception as e:
70
- return jsonify({"reply": f"Error: {str(e)}"})
71
 
72
- if __name__ == '__main__':
73
- app.run(host='0.0.0.0', port=7860)
 
10
  API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
11
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
12
 
13
+
14
  @app.route('/')
15
  def home():
16
  return render_template('index.html')
 
18
  @app.route('/chat', methods=['POST'])
19
  def chat():
20
  user_message = request.json.get("message")
21
+
22
  if not user_message:
23
+ return jsonify({"reply": "\u26a0\ufe0f No message provided."})
24
 
25
  try:
 
26
  payload = {
27
+ "inputs": user_message,
28
+ "parameters": {
29
+ "temperature": 0.5,
30
+ "top_p": 0.9,
31
+ "max_new_tokens": 100,
32
+ "stop": ["User:", "You:", "Bot:"]
33
+ }
34
  }
35
+
36
  response = requests.post(API_URL, headers=headers, json=payload)
37
  data = response.json()
 
 
38
 
39
+ if "error" in data:
40
+ return jsonify({"reply": f"\u274c Error: {data['error']}"})
41
+
42
+ # Extract response safely
43
+ if isinstance(data, list) and 'generated_text' in data[0]:
44
+ bot_reply = data[0]['generated_text']
45
+ elif 'generated_text' in data:
46
+ bot_reply = data['generated_text']
47
+ else:
48
+ bot_reply = "\ud83e\udde0 Sorry, I didn't understand that."
49
+
50
+ # Clean extra prompt echoes like "User:"
51
+ cleaned_reply = bot_reply.replace("User:", "").replace("You:", "").replace("Bot:", "").strip()
52
+ return jsonify({"reply": cleaned_reply})
53
+
54
+ except Exception as e:
55
+ return jsonify({"reply": f"\ud83d\udea8 Server Error: {str(e)}"})
56
+
57
+ if __name__ == '__main__':
58
+ app.run(host='0.0.0.0', port=7860, debug=True)
59
+
60
+
61
+ # @app.route('/')
62
+ # def home():
63
+ # return render_template('index.html')
64
+
65
+ # @app.route('/chat', methods=['POST'])
66
+ # def chat():
67
+ # user_message = request.json.get("message")
68
+
69
+ # if not user_message:
70
+ # return jsonify({"error": "Empty message received"})
71
+
72
+ # try:
73
+ # formatted_prompt = f"User: {user_message}\nBot:"
74
+ # payload = {
75
+ # "inputs": formatted_prompt,
76
+ # "parameters": {
77
+ # "temperature": 0.5, # πŸ”₯ Controls randomness (lower = more deterministic)
78
+ # "top_p": 0.9, # 🎯 Focus on high-probability words
79
+ # "max_new_tokens": 50, # ⏳ Limits response length
80
+ # "stop_sequences": ["User:", "You:", "user:"] # β›” Stops response at natural points
81
+ # }
82
+ # }
83
+ # response = requests.post(API_URL, headers=headers, json=payload)
84
+ # data = response.json()
85
+ # # print(response.status_code) # Debugging: Print the HTTP status
86
+ # # print(response.json()) # Debugging: Print the API response
87
+
88
+ # # if response.status_code == 200:
89
+ # # return response.json()[0]['generated_text']
90
+ # # else:
91
+ # # return f"Error: {response.status_code} - {response.json()}"
92
 
93
 
94
 
95
+ # if "error" in data:
96
+ # return jsonify({"reply": f"Error: {data['error']}"})
97
 
98
+ # # raw_output = data[0]['generated_text'] if isinstance(data, list) else data.get('generated_text', "No response")
99
+ # # reply = raw_output.split("Bot:")[-1].strip()
100
 
101
 
102
+ # # return jsonify({"reply": reply})
103
 
104
+ # raw_output = data[0]['generated_text'] if isinstance(data, list) else data.get('generated_text', "No response")
105
+ # # Clean up output
106
+ # if "Bot:" in raw_output:
107
+ # reply = raw_output.split("Bot:")[-1].strip()
108
+ # else:
109
+ # reply = raw_output.strip()
110
 
111
+ # for trailing in ["User", "You", "User:", "You:"]:
112
+ # if reply.endswith(trailing):
113
+ # reply = reply.rsplit(trailing, 1)[0].strip()
114
 
115
+ # return jsonify({"reply": reply})
116
 
117
+ # except Exception as e:
118
+ # return jsonify({"reply": f"Error: {str(e)}"})
119
 
120
+ # if __name__ == '__main__':
121
+ # app.run(host='0.0.0.0', port=7860)
templates/index.html CHANGED
@@ -6,151 +6,167 @@
6
  <title>AI Chatbot</title>
7
  <style>
8
  body {
9
- font-family: 'Segoe UI', sans-serif;
10
  margin: 0;
 
 
 
 
 
 
 
 
11
  background-color: #121212;
12
- color: #fff;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  }
14
- h1 {
15
- text-align: center;
16
- padding: 1rem;
 
17
  }
 
18
  #chat-box {
19
- background-color: #1e1e1e;
20
- border: 1px solid #333;
21
- border-radius: 10px;
22
- padding: 1rem;
23
- height: 80vh;
24
  overflow-y: auto;
25
- margin: 0 auto;
26
- width: 90%;
27
- max-width: 900px;
 
 
 
 
28
  }
29
- .chat-wrapper {
 
30
  display: flex;
31
- justify-content: center;
32
- align-items: center;
33
- gap: 10px;
34
- margin: 1rem auto;
35
- width: 90%;
36
- max-width: 900px;
37
  }
38
- input[type="text"] {
39
- flex: 1;
40
- padding: 0.8rem;
41
- border: none;
42
- border-radius: 10px;
43
- font-size: 1rem;
44
- background-color: #2c2c2c;
45
- color: #fff;
46
  }
47
- button {
48
- padding: 0.8rem 1rem;
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  border: none;
50
- border-radius: 10px;
51
- background-color: #00bcd4;
52
- color: #fff;
53
- font-weight: bold;
54
  cursor: pointer;
55
- transition: background-color 0.3s ease;
56
  }
57
- button:hover {
58
- background-color: #0097a7;
 
 
 
 
 
59
  }
60
- .typing {
61
- font-style: italic;
62
- opacity: 0.7;
 
63
  }
64
  </style>
65
  </head>
66
  <body>
67
- <h1>πŸ€– AI Chatbot</h1>
 
 
 
 
 
 
 
 
 
68
  <div id="chat-box"></div>
69
 
70
- <div class="chat-wrapper">
71
- <input type="text" id="user-input" placeholder="Type a message..." onkeypress="handleKeyPress(event)" />
72
  <button id="send-btn" onclick="sendMessage()">Send</button>
73
- <button id="mic-btn" onclick="startListening()">🎀</button>
74
- <button id="clear-btn" onclick="clearChat()">πŸ—‘οΈ Clear</button>
75
  </div>
76
 
77
  <script>
78
- const chatBox = document.getElementById("chat-box");
79
-
80
- function handleKeyPress(event) {
81
- if (event.key === "Enter") {
82
- sendMessage();
83
- }
84
  }
85
 
86
  async function sendMessage() {
87
- let userInput = document.getElementById("user-input").value;
88
- if (!userInput.trim()) return;
 
 
 
 
 
89
 
90
- appendMessage("You", userInput);
91
  document.getElementById("user-input").value = "";
92
- appendTyping();
93
 
94
- let response = await fetch("/chat", {
95
  method: "POST",
96
  headers: { "Content-Type": "application/json" },
97
- body: JSON.stringify({ message: userInput }),
98
  });
99
 
100
- let data = await response.json();
101
- removeTyping();
102
 
103
- let reply = data.reply || "Error in response";
104
- appendMessage("Bot", reply);
105
- saveChat();
106
  }
107
 
108
- function appendMessage(sender, text) {
109
- let msg = document.createElement("p");
110
- msg.innerHTML = `<b>${sender}:</b> ${text}`;
111
- chatBox.appendChild(msg);
112
- chatBox.scrollTop = chatBox.scrollHeight;
113
- }
114
-
115
- function appendTyping() {
116
- let typing = document.createElement("p");
117
- typing.className = "typing";
118
- typing.id = "typing";
119
- typing.innerText = "Bot is typing...";
120
- chatBox.appendChild(typing);
121
- chatBox.scrollTop = chatBox.scrollHeight;
122
- }
123
-
124
- function removeTyping() {
125
- let typing = document.getElementById("typing");
126
- if (typing) typing.remove();
127
- }
128
-
129
- function startListening() {
130
- const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
131
- recognition.lang = "en-US";
132
- recognition.start();
133
-
134
- recognition.onresult = function (event) {
135
- document.getElementById("user-input").value = event.results[0][0].transcript;
136
- };
137
  }
138
 
139
  function clearChat() {
140
- chatBox.innerHTML = "";
141
- localStorage.removeItem("chatHistory");
142
  }
143
 
144
- function saveChat() {
145
- localStorage.setItem("chatHistory", chatBox.innerHTML);
 
146
  }
147
 
148
- function loadChat() {
149
- let saved = localStorage.getItem("chatHistory");
150
- if (saved) chatBox.innerHTML = saved;
 
 
 
 
 
 
151
  }
152
-
153
- window.onload = loadChat;
154
  </script>
 
155
  </body>
156
  </html>
 
6
  <title>AI Chatbot</title>
7
  <style>
8
  body {
9
+ font-family: Arial, sans-serif;
10
  margin: 0;
11
+ height: 100vh;
12
+ display: flex;
13
+ flex-direction: column;
14
+ background-color: #f4f4f4;
15
+ transition: background-color 0.3s, color 0.3s;
16
+ }
17
+
18
+ body.dark-mode {
19
  background-color: #121212;
20
+ color: white;
21
+ }
22
+
23
+ header {
24
+ display: flex;
25
+ justify-content: space-between;
26
+ align-items: center;
27
+ padding: 10px 20px;
28
+ background-color: #333;
29
+ color: white;
30
+ }
31
+
32
+ header h1 {
33
+ margin: 0;
34
+ font-size: 1.5em;
35
  }
36
+
37
+ .controls {
38
+ display: flex;
39
+ gap: 10px;
40
  }
41
+
42
  #chat-box {
43
+ flex-grow: 1;
44
+ padding: 20px;
 
 
 
45
  overflow-y: auto;
46
+ border-top: 1px solid #ccc;
47
+ border-bottom: 1px solid #ccc;
48
+ background-color: #fff;
49
+ }
50
+
51
+ body.dark-mode #chat-box {
52
+ background-color: #1e1e1e;
53
  }
54
+
55
+ #input-container {
56
  display: flex;
57
+ padding: 10px;
58
+ background-color: #f9f9f9;
59
+ border-top: 1px solid #ccc;
 
 
 
60
  }
61
+
62
+ body.dark-mode #input-container {
63
+ background-color: #1a1a1a;
 
 
 
 
 
64
  }
65
+
66
+ #user-input {
67
+ flex-grow: 1;
68
+ padding: 10px;
69
+ font-size: 1em;
70
+ border: 1px solid #ccc;
71
+ border-radius: 4px;
72
+ }
73
+
74
+ #send-btn {
75
+ margin-left: 10px;
76
+ padding: 10px 15px;
77
+ font-size: 1em;
78
+ background-color: #4CAF50;
79
+ color: white;
80
  border: none;
81
+ border-radius: 4px;
 
 
 
82
  cursor: pointer;
 
83
  }
84
+
85
+ #send-btn:hover {
86
+ background-color: #45a049;
87
+ }
88
+
89
+ .message {
90
+ margin: 10px 0;
91
  }
92
+
93
+ .message strong {
94
+ display: inline-block;
95
+ width: 60px;
96
  }
97
  </style>
98
  </head>
99
  <body>
100
+
101
+ <header>
102
+ <h1>AI Chatbot</h1>
103
+ <div class="controls">
104
+ <button onclick="toggleMode()">πŸŒ“ Theme</button>
105
+ <button onclick="clearChat()">πŸ—‘οΈ Clear</button>
106
+ <button onclick="exportChat()">πŸ“ Export</button>
107
+ </div>
108
+ </header>
109
+
110
  <div id="chat-box"></div>
111
 
112
+ <div id="input-container">
113
+ <input type="text" id="user-input" placeholder="Type a message..." onkeypress="handleEnter(event)">
114
  <button id="send-btn" onclick="sendMessage()">Send</button>
 
 
115
  </div>
116
 
117
  <script>
118
+ function handleEnter(e) {
119
+ if (e.key === 'Enter') sendMessage();
 
 
 
 
120
  }
121
 
122
  async function sendMessage() {
123
+ const userInput = document.getElementById("user-input").value.trim();
124
+ const chatBox = document.getElementById("chat-box");
125
+
126
+ if (!userInput) return;
127
+
128
+ chatBox.innerHTML += `<div class="message"><strong>You:</strong> ${userInput}</div>`;
129
+ scrollToBottom();
130
 
 
131
  document.getElementById("user-input").value = "";
 
132
 
133
+ const response = await fetch("/chat", {
134
  method: "POST",
135
  headers: { "Content-Type": "application/json" },
136
+ body: JSON.stringify({ message: userInput })
137
  });
138
 
139
+ const data = await response.json();
140
+ const reply = data.reply || "Error in response";
141
 
142
+ chatBox.innerHTML += `<div class="message"><strong>Bot:</strong> ${reply}</div>`;
143
+ scrollToBottom();
 
144
  }
145
 
146
+ function toggleMode() {
147
+ document.body.classList.toggle("dark-mode");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  }
149
 
150
  function clearChat() {
151
+ document.getElementById("chat-box").innerHTML = "";
 
152
  }
153
 
154
+ function scrollToBottom() {
155
+ const chatBox = document.getElementById("chat-box");
156
+ chatBox.scrollTop = chatBox.scrollHeight;
157
  }
158
 
159
+ function exportChat() {
160
+ const chat = document.getElementById("chat-box").innerText;
161
+ const blob = new Blob([chat], { type: "text/plain" });
162
+ const url = URL.createObjectURL(blob);
163
+ const a = document.createElement("a");
164
+ a.href = url;
165
+ a.download = "chat_history.txt";
166
+ a.click();
167
+ URL.revokeObjectURL(url);
168
  }
 
 
169
  </script>
170
+
171
  </body>
172
  </html>