Spaces:
Runtime error
Runtime error
File size: 11,286 Bytes
89f45ea 201f11b 89f45ea d8e6a19 89f45ea 0a66a74 201f11b 0a66a74 c4b90e4 0a66a74 c4b90e4 0a66a74 c4b90e4 0a66a74 201f11b c4b90e4 0a66a74 201f11b 0a66a74 |
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 |
import streamlit as st
import requests
import os
import sqlite3
import time
import uuid
import datetime
import hashlib
import json
import pandas as pd
# FastAPI base URL
#BASE_URL = "http://localhost:8000"
import os
API_URL=os.getenv("API_URL")
API_TOKEN=os.getenv("API_TOKEN")
BASE_URL=API_URL
#API_URL = "https://api-inference.huggingface.co/models/your-username/your-private-model"
headers = {"Authorization":f"Bearer {API_TOKEN}"}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
#data = query({"inputs": "Hello, how are you?"})
#print(data)
st.title("Generative AI Demos")
def generate_unique_hash(filename: str, uuid: str) -> str:
# Generate a UUID for the session or device
device_uuid = uuid
# Get the current date and time
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Combine filename, current time, and UUID into a single string
combined_string = f"{filename}-{current_time}-{device_uuid}"
# Generate a hash using SHA256
unique_hash = hashlib.sha256(combined_string.encode()).hexdigest()
return unique_hash
# Function to generate or retrieve a UUID from local storage
uuid_script = """
<script>
if (!localStorage.getItem('uuid')) {
localStorage.setItem('uuid', '""" + str(uuid.uuid4()) + """');
}
const uuid = localStorage.getItem('uuid');
const streamlitUUIDInput = window.parent.document.querySelector('input[data-testid="stTextInput"][aria-label="UUID"]');
if (streamlitUUIDInput) {
streamlitUUIDInput.value = uuid;
}
</script>
"""
ga_script = """
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PWP4PRW5G5"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-PWP4PRW5G5');
</script>
"""
# Add Google Analytics to the Streamlit app
st.components.v1.html(ga_script, height=0, width=0)
# Execute the JavaScript in the Streamlit app
st.components.v1.html(uuid_script, height=0, width=0)
# Store and display UUID in a non-editable text field using session state
if 'uuid' not in st.session_state:
st.session_state['uuid'] = str(uuid.uuid4())
uuid_from_js = st.session_state['uuid']
# Retrieve UUID from DOM
if uuid_from_js is None:
st.error("Unable to retrieve UUID from the browser.")
else:
# Display UUID in a non-editable text field
st.text_input("Your UUID", value=uuid_from_js, disabled=True)
# Define tabs
tab1, tab2,tab3 = st.tabs(["Review Analyzer", "Presentation Creator","Semantic Search"])
with tab1:
st.header("Review Analyzer")
uploaded_file = st.file_uploader("Upload your reviews CSV file", type=["csv"],key=2)
if uploaded_file is not None:
en1 = generate_unique_hash(uploaded_file.name, uuid_from_js)
files = {"file": (en1, uploaded_file.getvalue(), "text/csv")}
st.info("Calling model inference. Please wait...")
response = requests.post(f"{BASE_URL}/upload/", files=files, headers=headers)
if response.status_code == 200:
st.info("Processing started. Please wait...")
# Poll for completion
while True:
status_response = requests.get(f"{BASE_URL}/status/{en1}", headers=headers)
if status_response.status_code == 200 and (status_response.json()["status"] == "complete" or status_response.json()["status"] == "error"):
if status_response.json()["status"] == "complete":
st.success("File processed successfully.")
download_response = requests.get(f"{BASE_URL}/download/{en1}", headers=headers)
if download_response.status_code == 200:
st.download_button(
label="Download Processed File",
data=download_response.content,
file_name=f"processed_{en1}",
mime="text/csv"
)
break
time.sleep(10)
else:
st.error("Failed to upload file for processing.")
with tab2:
st.header("Presentation Creator")
# Input URL for presentation creation
presentation_url = st.text_input("Enter the URL for the presentation content")
if presentation_url:
#unique_id = generate_unique_hash(presentation_url, str(uuid.uuid4()))
st.info("Creating presentation. Please wait...")
# Mock payload for processing the URL
payload = {"url": presentation_url, "id": uuid_from_js}
response = requests.post(f"{BASE_URL}/presentation_creator", json=payload, headers=headers)
print("response",response)
if response.status_code == 200:
st.info("Processing started. Please wait...")
unique_id=response.json()["filename"]
# Poll for completion
print("unique id is ",unique_id,BASE_URL)
while True:
status_response = requests.get(f"{BASE_URL}/status/{unique_id}", headers=headers)
print("status_response",status_response)
if status_response.status_code == 200 and (status_response.json()["status"] == "complete" or status_response.json()["status"] == "error"):
if status_response.json()["status"] == "complete":
st.success("Presentation created successfully.")
download_response = requests.get(f"{BASE_URL}/download/{unique_id}", headers=headers)
if download_response.status_code == 200:
st.download_button(
label="Download Presentation File",
data=download_response.content,
file_name=f"presentation_{unique_id}.pptx",
mime="application/pdf"
)
else:
st.error("error in downloading the presentation file ")
else:
st.error("error in creating presentation")
break
time.sleep(10)
else:
st.error("Failed to create presentation.")
with tab3:
st.header("Semantic Search")
# Create a form for the inputs and submit button
with st.form(key='semantic_search_form'):
# Input URL for presentation creation
presentation_url = st.text_input("Enter the URL for the semantic search")
search_query = st.text_input("Enter your query")
# Submit button inside the form
submit_button = st.form_submit_button(label="Submit")
if submit_button:
if presentation_url and search_query:
#unique_id = generate_unique_hash(presentation_url, str(uuid.uuid4()))
st.info("Performing semantic search. Please wait...")
# Mock payload for processing the URL
payload = {"url": presentation_url, "id": uuid_from_js,"search_query":search_query}
response = requests.post(f"{BASE_URL}/semantic_search", json=payload, headers=headers)
print("response",response.json())
if response.status_code == 200:
st.info("Processing started. Please wait...")
unique_id=response.json()["filename"]
# Poll for completion
print("unique id is ",unique_id,BASE_URL)
while True:
status_response = requests.get(f"{BASE_URL}/status/{unique_id}", headers=headers)
print("status_response",status_response.json())
if status_response.status_code == 200 and (status_response.json()["status"] == "complete" or status_response.json()["status"] == "error"):
if status_response.json()["status"] == "complete":
st.success("Presentation created successfully.")
download_response = requests.get(f"{BASE_URL}/download/{unique_id}", headers=headers)
if download_response.status_code == 200:
#print("download_response",download_response.content)
# Load JSON data into a Python list of dictionaries
data = json.loads(download_response.content)
# Convert the list of dictionaries to a DataFrame
df = pd.DataFrame(data)
df = df["page_content"]
# Display the DataFrame in Streamlit as an interactive dataframe
#st.dataframe(df)
df = df.str.split(' ##### ', 1).str[1].str.strip()
# Alternatively, display it as a static table
st.table(df)
else:
st.error("error in downloading the presentation file ")
else:
st.error("error in creating presentation")
break
time.sleep(2)
else:
st.error("Failed to create presentation.")
else:
st.error("Please enter both a URL and a query.")
# uploaded_file = st.file_uploader("Upload your reviews CSV file", type=["csv"],key=1)
# if uploaded_file is not None:
# # Save uploaded file to FastAPI
# en1 = generate_unique_hash(uploaded_file.name, uuid_from_js)
# files = {"file": (en1, uploaded_file.getvalue(), "text/csv")}
# st.info("Calling model inference. Please wait...")
# response = requests.post(f"{BASE_URL}/upload/", files=files,headers=headers)
# print("response to file upload is ",response)
# if response.status_code == 200:
# st.info("Processing started. Please wait...")
# # Poll for completion
# while True:
# status_response = requests.get(f"{BASE_URL}/status/{en1}",headers=headers)
# if status_response.status_code == 200 and (status_response.json()["status"] == "complete" or status_response.json()["status"]=="error"):
# if status_response.json()["status"] == "complete":
# st.success("File processed successfully.")
# download_response = requests.get(f"{BASE_URL}/download/{en1}",headers=headers)
# if download_response.status_code == 200:
# st.download_button(
# label="Download Processed File",
# data=download_response.content,
# file_name=f"processed_{en1}",
# mime="text/csv"
# )
# break
# time.sleep(10)
# else:
# st.error("Failed to upload file for processing.") |