d3dname commited on
Commit
6bc060f
·
verified ·
1 Parent(s): b3153cc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -0
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import requests
4
+ import torch
5
+ from TTS.api import TTS
6
+ import os
7
+ import time
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
+ import streamlit as st
11
+ from threading import Thread
12
+ os.environ["COQUI_TOS_AGREED"] = "1"
13
+ os.environ["TRAINER_TELEMETRY"]= "0"
14
+ # Constants
15
+ MODEL_LIST = ["mistralai/Mistral-Nemo-Instruct-2407"]
16
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
17
+ MODEL = os.environ.get("MODEL_ID", "mistralai/Mistral-Nemo-Instruct-2407")
18
+ # Set the device to GPU or CPU
19
+ device = "cuda" if torch.cuda.is_available() else "cpu"
20
+
21
+ # Load the model and tokenizer
22
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
23
+ model = AutoModelForCausalLM.from_pretrained(
24
+ MODEL,
25
+ torch_dtype=torch.bfloat16,
26
+ device_map="auto",
27
+ ignore_mismatched_sizes=True
28
+ ).to(device)
29
+
30
+ # CSS styles
31
+ CSS = """
32
+ <style>
33
+ h1 {
34
+ text-align: center;
35
+ }
36
+ </style>
37
+ """
38
+
39
+
40
+ # Function to handle chat
41
+ def stream_chat(message, history, temperature=0.3, max_new_tokens=1024, top_p=1.0, top_k=20, penalty=1.2):
42
+ conversation = []
43
+ for prompt, answer in history:
44
+ conversation.extend([
45
+ {"role": "user", "content": prompt},
46
+ {"role": "assistant", "content": answer},
47
+ ])
48
+
49
+ conversation.append({"role": "user", "content": message})
50
+
51
+ input_text = tokenizer.apply_chat_template(conversation, tokenize=False)
52
+ inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
53
+ streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
54
+
55
+ generate_kwargs = dict(
56
+ input_ids=inputs,
57
+ max_new_tokens=max_new_tokens,
58
+ do_sample=temperature != 0,
59
+ top_p=top_p,
60
+ top_k=top_k,
61
+ temperature=temperature,
62
+ streamer=streamer,
63
+ pad_token_id=10,
64
+ )
65
+
66
+ with torch.no_grad():
67
+ thread = Thread(target=model.generate, kwargs=generate_kwargs)
68
+ thread.start()
69
+
70
+ buffer = ""
71
+ for new_text in streamer:
72
+ buffer += new_text
73
+ yield buffer
74
+
75
+ #st.set_page_config(layout="wide")
76
+ # Load custom CSS to integrate Bootstrap, Font Awesome, and Google Fonts
77
+ st.markdown('''
78
+ <link href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700|Dosis:400,500,700&subset=latin,latin-ext" rel="stylesheet">
79
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
80
+ <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
81
+ <style>
82
+ body {
83
+ font-family: 'Dosis', sans-serif;
84
+ }
85
+ h1, h2, h3 {
86
+ font-family: 'Amatic SC', cursive;
87
+ }
88
+ .calculator button {
89
+ width: 100%;
90
+ padding: 20px;
91
+ font-size: 24px;
92
+ margin: 5px;
93
+ }
94
+ </style>
95
+ ''', unsafe_allow_html=True)
96
+
97
+ # Title Section
98
+ st.markdown('<h1 class="display-4 text-center">My Streamlit Application</h1><p class="lead text-center">Integrating Streamlit with Bootstrap Carousel</p>', unsafe_allow_html=True)
99
+
100
+
101
+
102
+ left, right = st.columns(2)
103
+ buff, col, buff2 = st.columns([1,3,1])
104
+
105
+ with left:
106
+ # Carousel Structure
107
+ st.markdown('''<h3><i class="fa fa-calculator"></i> Calculator</h3>''', unsafe_allow_html=True)
108
+
109
+ # Box 1: Calculator
110
+ # Define the calculator layout
111
+ buttons = [
112
+ ['7', '8', '9', '/'],
113
+ ['4', '5', '6', '\*'],
114
+ ['1', '2', '3', '\-'],
115
+ ['C', '0', '.', '\+'],
116
+ ['=']
117
+ ]
118
+
119
+ # To store the calculation input
120
+ if 'calc_input' not in st.session_state:
121
+ st.session_state.calc_input = ""
122
+
123
+ # Custom calculation function
124
+ def calculate(expression):
125
+ expression = expression.replace("\\","")
126
+ try:
127
+ result = eval(expression) # placeholder for a safe eval replacement
128
+ return str(result)
129
+ except ZeroDivisionError:
130
+ return "Error: Division by zero"
131
+ except Exception:
132
+ return "Error"
133
+
134
+ # Display the calculator buttons
135
+ for row in buttons:
136
+ cols = st.columns(len(row))
137
+ for i, btn_label in enumerate(row):
138
+ if btn_label and cols[i].button(btn_label):
139
+ if btn_label == '=':
140
+ st.session_state.calc_input = calculate(st.session_state.calc_input)
141
+ elif btn_label == 'C':
142
+ st.session_state.calc_input = ""
143
+ else:
144
+ st.session_state.calc_input += btn_label.replace("\\","")
145
+
146
+ # Display the current calculation input/output
147
+ st.text_input("Calculation", st.session_state.calc_input, key="display", disabled=True)
148
+
149
+
150
+
151
+ # End of Box 1 and first Carousel Item
152
+ st.markdown('''<h3><i class="fa fa-pencil"></i> Form 1</h3>''', unsafe_allow_html=True)
153
+
154
+ # Box 2: Form 1
155
+ # Chat history
156
+ if 'history' not in st.session_state:
157
+ st.session_state['history'] = []
158
+
159
+ # Chat input
160
+ user_input = st.text_input("Your Message:", "")
161
+
162
+ # Chat parameters
163
+ with st.expander("⚙️ Parameters"):
164
+ temperature = st.slider("Temperature", 0.0, 1.0, 0.3)
165
+ max_new_tokens = st.slider("Max new tokens", 128, 8192, 1024)
166
+ top_p = st.slider("Top p", 0.0, 1.0, 1.0)
167
+ top_k = st.slider("Top k", 1, 20, 20)
168
+ penalty = st.slider("Repetition penalty", 0.0, 2.0, 1.2)
169
+
170
+ # Handle the chat logic
171
+ if st.button("Send"):
172
+ if user_input:
173
+ response = stream_chat(user_input, st.session_state['history'], temperature, max_new_tokens, top_p, top_k, penalty)
174
+ st.session_state['history'].append((user_input, next(response)))
175
+ for new_text in response:
176
+ st.session_state['history'][-1] = (user_input, new_text)
177
+ st.experimental_rerun()
178
+
179
+ # Display chat history
180
+ for prompt, answer in st.session_state['history']:
181
+ st.write(f"**User:** {prompt}")
182
+ st.write(f"**Mistral-Nemo:** {answer}")
183
+
184
+
185
+ with right:
186
+ # End of Box 2 and second Carousel Item
187
+ st.markdown('''<h3><i class="fa fa-pencil"></i> Form 2</h3>''', unsafe_allow_html=True)
188
+
189
+ # Box 3: Form 2
190
+ prompt2 = st.text_input("Enter Prompt", key="prompt2")
191
+ image_url2 = st.text_input("Enter Image URL", key="image_url2")
192
+ if st.button("Submit Form 2", key="submit2"):
193
+ payload = {"prompt": prompt2, "image_url": image_url2}
194
+ response = requests.post("https://d3ndnam3-hf.space/api", json=payload)
195
+ if response.status_code == 200:
196
+ st.write(f"**Response:** {response.json().get('response', 'No response')}")
197
+ else:
198
+ st.write("Failed to get a response")
199
+
200
+ # End of Box 3 and third Carousel Item
201
+ st.markdown('''<h3><i class="fa fa-pencil"></i> Form 3</h3>''', unsafe_allow_html=True)
202
+
203
+ # Box 4: Form 3
204
+ prompt3 = st.text_input("Enter Prompt", key="prompt3")
205
+ image_url3 = st.text_input("Enter Image URL", key="image_url3")
206
+ if st.button("Submit Form 3", key="submit3"):
207
+ payload = {"prompt": prompt3, "image_url": image_url3}
208
+ response = requests.post("https://d3ndnam3-hf.space/api", json=payload)
209
+ if response.status_code == 200:
210
+ st.write(f"**Response:** {response.json().get('response', 'No response')}")
211
+ else:
212
+ st.write("Failed to get a response")
213
+
214
+ # End of Box 4 and fourth Carousel Item
215
+ st.markdown(''' ''', unsafe_allow_html=True)
216
+ hide_default_format = """
217
+ <style>
218
+ #MainMenu {visibility: hidden; }
219
+ footer {visibility: hidden;}
220
+ header {visibility: hidden;}
221
+ </style>
222
+ """
223
+ st.markdown(hide_default_format, unsafe_allow_html=True)