File size: 9,575 Bytes
6bc060f
 
 
 
 
 
2f7af2d
caa92e8
a9d075c
e4da9af
af03d54
 
800cb10
6bc060f
 
 
 
800cb10
6bc060f
10b4193
 
9f6fbb2
 
800cb10
a9d075c
 
 
 
01bce79
6bc060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c26cc
dfc2cd8
6bc060f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c26cc
6bc060f
798591b
 
 
 
 
 
 
 
800cb10
 
 
798591b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800cb10
798591b
 
800cb10
80c26cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798591b
6bc060f
10b4193
6bc060f
798591b
10b4193
f5500c9
10b4193
f5500c9
 
 
 
6bc060f
01bce79
6bc060f
 
 
 
dfc2cd8
9f6fbb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddaaf1b
 
 
 
 
 
 
 
 
9f6fbb2
 
 
ddaaf1b
9f6fbb2
 
 
 
 
 
6bc060f
 
 
 
 
 
 
 
22fd6d6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import streamlit as st
import streamlit.components.v1 as components
import requests
import os
import time
import streamlit as st
import base64
from streamlit_mic_recorder import mic_recorder
from notion_client import Client
import pandas as pd
MODEL_NAME = "drinktoomuchsax/whisper-small-hi"
lang = "en"

from threading import Thread
os.environ["COQUI_TOS_AGREED"] = "1"
os.environ["TRAINER_TELEMETRY"]= "0"
# Constants

HF_TOKEN = os.environ.get("HF_TOKEN", None)
BASETEN_API = os.environ.get("BASETEN_API", None)
BASETEN_KEY = os.environ.get("BASETEN_KEY", None)
NOTION_KEY = os.environ.get("NOTION_API_KEY", None)
NOTION_DB_ID = os.environ.get("NOTION_DB_ID", None)

notion = Client(auth=f"{NOTION_KEY}")

database_id = f"{NOTION_DB_ID}"

st.set_page_config(layout="wide")
# Load custom CSS to integrate Bootstrap, Font Awesome, and Google Fonts
st.markdown('''
    <link href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700|Dosis:400,500,700&subset=latin,latin-ext" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Dosis', sans-serif;
        }
        h1, h2, h3 {
            font-family: 'Amatic SC', cursive;
        }
        .calculator button {
            width: 100%;
            padding: 20px;
            font-size: 24px;
            margin: 5px;
        }
    </style>
''', unsafe_allow_html=True)

# Title Section
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)



left, ml, right = st.columns([3,3,3])


with left:
    # Carousel Structure
    st.markdown('''<h3><i class="fa fa-calculator"></i> Calculator</h3>''', unsafe_allow_html=True)

    # Box 1: Calculator
    # Define the calculator layout
    buttons = [
        ['7', '8', '9', '/'],
        ['4', '5', '6', '\*'],
        ['1', '2', '3', '\-'],
        ['C', '0', '.', '\+'],
        ['=']
    ]

    # To store the calculation input
    if 'calc_input' not in st.session_state:
        st.session_state.calc_input = ""

    # Custom calculation function
    def calculate(expression):
        expression = expression.replace("\\","")
        try:
            result = eval(expression)  # placeholder for a safe eval replacement
            return str(result)
        except ZeroDivisionError:
            return "Error: Division by zero"
        except Exception:
            return "Error"

    # Display the calculator buttons
    for row in buttons:
        cols = st.columns(len(row))
        for i, btn_label in enumerate(row):
            if btn_label and cols[i].button(btn_label):
                if btn_label == '=':
                    st.session_state.calc_input = calculate(st.session_state.calc_input)
                elif btn_label == 'C':
                    st.session_state.calc_input = ""
                else:
                    st.session_state.calc_input += btn_label.replace("\\","")

    # Display the current calculation input/output
    st.text_input("Calculation", st.session_state.calc_input, key="display", disabled=True)

with ml:

    st.markdown('''<h3><i class="fa fa-image"></i> Gen Image</h3>''', unsafe_allow_html=True)

    api_key = f"{BASETEN_KEY}"
    negative_prompt = st.text_input("Negative Prompt", "blurry, text, low quality")
    positive_prompt = st.text_input("Positive Prompt", "An igloo on a snowy day, 4k, hd")
    controlnet_image_url = st.text_input("ControlNet Image URL", "https://storage.googleapis.com/logos-bucket-01/baseten_logo.png")



    # Button to trigger generation
    if st.button("Generate Prompt"):
       # Making the API request
        response = requests.post(
            "https://model-7wlx9oew.api.baseten.co/production/predict",
            headers={"Authorization": f"Api-Key {api_key}"},
            json={
                'workflow_values': {
                    'negative_prompt': negative_prompt,
                    'positive_prompt': positive_prompt,
                    'controlnet_image': controlnet_image_url
                }
            }
        )
        
        # Display the response
        if response.status_code == 200:
            result = response.json().get("result")
            if result:
                image_data = result[0].get("data")
                if image_data:
                    # Decode the base64 image data
                    image = base64.b64decode(image_data)
                    # Display the image in Streamlit
                    st.image(image, caption="Generated Image", use_column_width=True)
                else:
                    st.error("No image data found in the response.")
            else:
                st.error("No result found in the response.")
        else:
            st.error(f"Error: {response.status_code}, {response.text}")


# with rl:
#     # End of Box 2 and second Carousel Item
#     st.markdown('''<h3><i class="fa fa-pencil"></i> Transcribe </h3>''', unsafe_allow_html=True)

#     # Box 3: Form 2
#     # Audio recording using mic_recorder
#     audio = mic_recorder(
#         start_prompt="Start recording",
#         stop_prompt="Stop recording",
#         just_once=False,
#         use_container_width=False,
#         callback=None,
#         key="mic_recorder"
#     )

#     #uploaded_file = st.file_uploader("Or upload an audio file", type=["mp3", "wav", "flac", "aac"])
#     if st.button("Transcribe"):
#         if audio and "bytes" in audio:
#             st.success("Recording detected. Transcribing your recording...")
#             with open("temp_recording.wav", "wb") as f:
#                 f.write(audio["bytes"])
#             with st.spinner("Transcribing..."):
#                 #transcription = transcribe("temp_recording.wav")
#                 #need to send the data here
#                 transcription = "Under Process"
#                 print("")
#             st.text_area("Transcription", transcription, height=200)
#         else:
#             st.error("Please record audio or upload a file to transcribe.")    
with right:

    st.markdown('''<h3><i class="fa fa-pencil"></i> Chat with Mistral</h3>''', unsafe_allow_html=True)
    # Box 4: Form 3
    prompt3 = st.text_input("Enter Prompt", key="prompt3", value="Why is Sky Blue?")
    #image_url3 = st.text_input("Enter Image URL", key="image_url3")
    if st.button("Submit", key="submit3"):
        payload = {"prompt": prompt3}
        headers = {
            "Authorization": f"Api-Key {BASETEN_KEY}"
        }
        response = requests.post(f"{BASETEN_API}", headers=headers, json=payload)
        if response.status_code == 200:
            st.write(f"**Response:** {response.json()}")
        else:
            st.write("Failed to get a response")

    # End of Box 4 and fourth Carousel Item

left, middle, right = st.columns([1,3,1])

with middle:
    # Streamlit form for data input
    with st.form(key='data_entry_form'):
        name = st.text_input("Name")
        age = st.number_input("Age", min_value=0)
        location = st.text_input("Location")
        submit_button = st.form_submit_button(label='Submit')
    # Function to add data to Notion
    def add_to_notion(name, age, location):
        new_page = {
            "Name": {
                "title": [
                    {
                        "text": {
                            "content": name
                        }
                    }
                ]
            },
            "Age": {
                "number": age
            },
            "Location": {
                "rich_text": [
                    {
                        "text": {
                            "content": location
                        }
                    }
                ]
            }
        }    
        notion.pages.create(parent={"database_id": database_id}, properties=new_page)
    
    # Add data to Notion when form is submitted
    if submit_button:
        add_to_notion(name, age, location)
        st.success("Data submitted to Notion!")
    
    # Function to retrieve data from Notion
    def retrieve_data_from_notion():
        query_result = notion.databases.query(database_id=database_id)
        data = []
        for result in query_result["results"]:
            # Safely extract the "Name" property
            name = result["properties"]["Name"]["title"][0]["text"]["content"] if result["properties"]["Name"]["title"] else "No Name"
            
            # Safely extract the "Age" property
            age = result["properties"]["Age"]["number"] if result["properties"]["Age"]["number"] is not None else "No Age"
            
            # Safely extract the "Location" property
            location = result["properties"]["Location"]["rich_text"][0]["text"]["content"] if result["properties"]["Location"]["rich_text"] else "No Location"
            
            data.append({"Name": name, "Age": age, "Location": location})
        
        return pd.DataFrame(data)

    
    # Display the data in a table
    st.subheader("Stored Data")
    data_df = retrieve_data_from_notion()
    st.table(data_df)

hide_default_format = """
       <style>
       #MainMenu {visibility: hidden; }
       footer {visibility: hidden;}
       header {visibility: hidden;}
       </style>
       """
st.markdown(hide_default_format, unsafe_allow_html=True)