teststreamlit / app.py
d3dname's picture
Update app.py
80c26cc verified
Raw
History Blame Contribute Delete
9.58 kB
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)