Hi professor,
Thanks for the information. I had tried to remove the session state but the issue still the same. I just want to normal upload file subsequently. Really no idea what going on.
import logging
import openai
import streamlit as st
from datetime import datetime
from PyPDF2 import PdfReader, PdfWriter
from docx import Document
from io import BytesIO
import fitz # PyMuPDF library
from langchain.adapters import openai as lc_openai
from PIL import Image, ImageEnhance
import time
import json
import requests
import base64
import os
from openai import OpenAI
logging.basicConfig(level=logging.INFO)
Streamlit Page Configuration
st.set_page_config(
page_title=“IQOQ AI Assistant”,
page_icon=“/workspaces/macsiqoq/img/bot.jpg”,
layout=“wide”,
initial_sidebar_state=“expanded”,
menu_items={
“Get help”: “GitHub - AdieLaine/Streamly: Streamly - Streamlit Assistant is designed to provide the latest updates from Streamlit, generate code snippets for Streamlit widgets, and answer questions about Streamlit's latest features, issues, and more”,
“Report a bug”: “GitHub - AdieLaine/Streamly: Streamly - Streamlit Assistant is designed to provide the latest updates from Streamlit, generate code snippets for Streamlit widgets, and answer questions about Streamlit's latest features, issues, and more”,
“About”: “”"
## Streamly Streamlit Assistant
**GitHub**: https://github.com/AdieLaine/
The AI Assistant named, Streamly, aims to provide the latest updates from Streamlit,
generate code snippets for Streamlit widgets,
and answer questions about Streamlit's latest features, issues, and more.
Streamly has been trained on the latest Streamlit updates and documentation.
"""
}
)
Streamlit Updates and Expanders
API_DOCS_URL = “API Reference - Streamlit Docs”
def long_running_task(duration):
“”"
Simulates a long-running operation.
“”"
time.sleep(duration)
return “Long-running operation completed.”
def load_and_enhance_image(image_path, enhance=False):
“”"
Load and optionally enhance an image.
Parameters:
- image_path: str, path of the image
- enhance: bool, whether to enhance the image or not
Returns:
- img: PIL.Image.Image, (enhanced) image
"""
img = Image.open(image_path)
if enhance:
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(1.8)
return img
def load_IQOQ_streamlit_updates():
“”“Load the latest Streamlit updates from a local JSON file.”“”
try:
with open(“/workspaces/macsiqoq/data_updates/streamlit_updates_IQOQ.json”, “r”) as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def get_latest_update_from_json(keyword, latest_updates):
“”"
Fetch the latest Streamlit update based on a keyword.
Parameters:
keyword (str): The keyword to search for in the Streamlit updates.
latest_updates (dict): The latest Streamlit updates data.
Returns:
str: The latest update related to the keyword, or a message if no update is found.
"""
for section in ["Highlights", "Notable Changes", "Other Changes"]:
for sub_key, sub_value in latest_updates.get(section, {}).items():
for key, value in sub_value.items():
if keyword.lower() in key.lower() or keyword.lower() in value.lower():
return f"Section: {section}\nSub-Category: {sub_key}\n{key}: {value}"
return "No updates found for the specified keyword."
def get_streamlit_api_code_version():
“”"
Get the current Streamlit API code version from the Streamlit API documentation.
Returns:
str: The current Streamlit API code version.
"""
try:
response = requests.get(API_DOCS_URL)
if response.status_code == 200:
return "1.28.0"
except requests.exceptions.RequestException as e:
print("Error connecting to the Streamlit API documentation:", str(e))
return None
def display_streamlit_updates():
“”“It displays the latest updates of the Streamlit.”“”
with st.expander(“Streamlit 1.28 Announcement”, expanded=False):
image_path = “/workspaces/macsiqoq/img/updates.jpg”
enhance = st.checkbox(“Enhance Image?”, False)
img = load_and_enhance_image(image_path, enhance)
st.image(img, caption=“Streamlit 1.28 Announcement”, use_column_width=“auto”, clamp=True, channels=“RGB”, output_format=“JPG”)
st.markdown(“For more details on this version, check out the Streamlit Forum post.”)
def img_to_base64(image_path):
“”“Convert image to base64"”"
with open(image_path, “rb”) as img_file:
return base64.b64encode(img_file.read()).decode()
@st.cache_data(show_spinner=False)
def on_chat_submit(chat_input, api_key, latest_updates, use_langchain=False):
“”"
Handle chat input submissions and interact with the OpenAI API.
Parameters:
chat_input (str): The chat input from the user.
api_key (str): The OpenAI API key.
latest_updates (dict): The latest Streamlit updates fetched from a JSON file or API.
use_langchain (bool): Whether to use LangChain OpenAI wrapper.
Returns:
None: Updates the chat history in Streamlit's session state.
"""
user_input = chat_input.strip().lower()
# Initialize the OpenAI API
model_engine = "gpt-3.5-turbo"
# Initialize the conversation history with system and assistant messages
assistant_message = ""
formatted_message = []
highlights = latest_updates.get("Highlights", {})
# Include version info in highlights if available
version_info = highlights.get("Version 1.28", {})
if version_info:
description = version_info.get("Description", "No description available.")
formatted_message.append(f"- **Version 1.28**: {description}")
for category, updates in latest_updates.items():
formatted_message.append(f"**{category}**:")
for sub_key, sub_values in updates.items():
if sub_key != "Version 1.28": # Skip the version info as it's already included
description = sub_values.get("Description", "No description available.")
documentation = sub_values.get("Documentation", "No documentation available.")
formatted_message.append(f"- **{sub_key}**: {description}")
formatted_message.append(f" - **Documentation**: {documentation}")
assistant_message += "\n".join(formatted_message)
try:
# Logic for assistant's reply
assistant_reply = ""
if use_langchain:
# LangChain OpenAI wrapper call
lc_result = lc_openai.ChatCompletion.create(
messages=assistant_message,
model=model_engine,
temperature=0
)
assistant_reply = lc_result["choices"][0]["message"]["content"]
else:
if "latest updates" in user:
# Logic for assistant's reply
assistant_reply = ""
if use_langchain:
# LangChain OpenAI wrapper call
lc_result = lc_openai.ChatCompletion.create(
messages=assistant_message,
model=model_engine,
temperature=0
)
assistant_reply = lc_result["choices"][0]["message"]["content"]
else:
if "latest updates" in user_input:
assistant_reply = "Here are the latest highlights from Streamlit:\n"
highlights = latest_updates.get("Highlights", {})
if highlights:
for version, info in highlights.items():
description = info.get("Description", "No description available.")
assistant_reply += f"- **{version}**: {description}\n"
else:
# Direct OpenAI API call
response = openai.ChatCompletion.create(
model=model_engine,
messages=assistant_message
)
assistant_reply = response.choices[0].message.content
return assistant_reply
except openai.APIConnectionError as e:
logging.error(f"Error occurred: {e}")
error_message = f"OpenAI Error: {str(e)}"
st.error(error_message)
return error_message
def generate_pdf(uploaded_files):
pass
Function to save uploaded files
def save_uploaded_file(file, upload_folder):
file = os.path.join(upload_folder, file.name)
with open(file, “wb”) as f:
f.write(file.getbuffer())
return file
def report_upload():
# Create a directory if it doesn’t exist
upload_folder = “/workspaces/macsiqoq/files_uploaded”
os.makedirs(upload_folder, exist_ok=True)
# Define the file types for each step
file_types = [
{“name”: “IQOQ in MS Word”, “file_type”: [“docx”, “pdf”]},
{“name”: “IQOQ Raw Data in MS Word”, “file_type”: [“docx”, “pdf”]},
{“name”: “Training Certs in PDF”, “file_type”: [“pdf”]}
]
# Loop through each step
uploaded_files = []
cal_cert_num = 0
for i, file_type_info in enumerate(file_types, start=1):
step_name = file_type_info["name"]
file_type = file_type_info["file_type"]
st.subheader(f"Step {i}: Upload {step_name}")
try:
file = st.file_uploader(f"Upload {step_name}:", type=file_type)
# Check if a file is uploaded
if file is not None:
st.success("File uploaded successfully!")
file = save_uploaded_file(file, upload_folder)
st.write(f"File saved at: {file}")
uploaded_files.append(file)
else:
st.warning("Please upload the file to proceed.")
break # Break loop if file is not uploaded
except Exception as e:
logging.error(f"Error occurred: {e}")
st.error(f"Error occurred: {e}")
# If all required files are uploaded
if len(uploaded_files) == len(file_types):
cal_cert_num = st.number_input("Enter the number of calibration certificates to upload:", min_value=1, step=1)
for j in range(cal_cert_num):
st.subheader(f"Step {i + j + 1}: Upload Calibration Certificate {j + 1}")
cal_cert_file = st.file_uploader(f"Upload Calibration Certificate {j + 1}:", type=["pdf"])
if cal_cert_file is not None:
uploaded_files.append(cal_cert_file)
else:
st.warning("Please upload the file to proceed.")
break # Break loop if file is not uploaded
# If all required files are uploaded including calibration certificates
if len(uploaded_files) == len(file_types) + cal_cert_num:
st.success("All files uploaded successfully!")
st.write("Now click the 'Generate Report' button to proceed.")
if st.button("Generate Report"):
generate_pdf(uploaded_files)
else:
st.warning("Please upload all required files to proceed.")
def main():
“”"
Display Streamlit updates and handle the chat interface.
“”"
# Sidebar for Mode Selection
mode = st.sidebar.radio(“Select Mode:”, options=[“Latest Updates”, “IQOQ Chatbot Assistant”, “MQ IQOQ Report Generator”], index=1)
use_langchain = st.sidebar.checkbox("Use LangChain OpenAI Adapter 
", value=False)
# Handle Chat and Update Modes:
if mode == "IQOQ Chatbot Assistant":
st.title("IQOQ AI Assistant")
chat_input = st.text_input("Ask me about IQOQ Streamlit updates:")
if st.button("Submit"):
latest_updates = load_IQOQ_streamlit_updates()
assistant_reply = on_chat_submit(chat_input, api_key, latest_updates, use_langchain)
st.write(assistant_reply)
elif mode == "MQ IQOQ Report Generator":
st.title("MQ IQOQ Report Generator")
st.markdown("""
## Introduction
Welcome to the MQ IQOQ Report Generator mode. In this mode, you can generate an MQ IQOQ report based on the provided data files.
**Bot Generator Concept**:
The bot is created by python script with the logic,conversion,arrangement in sequence concept based on the history data trained. Engineer applied the logical report overall concept under the code. **No data is stored** in the online and database.
### Steps to Generate the Report:
1. **Upload Data Files**: Upload the required data files for the report. You need to upload six files in Word or PDF format.
**First** - IQOQ in MS Word
**Second** - IQOQ Raw Data in MS Word
**Third** - Training Certs in Pdf
**Forth** - Update the number of cal cert available then upload one by one in pdf.
2. **Click the Generate Button**: Click the "Generator IQOQ Button".
3. **Report Generating**: Report is generating and it may take some time to generate
4. **View/download Report**: Once generated, view the report output by click the button "Download".
**Let's get started by uploading the data files**.
""")
# Start button
if st.button("Start"):
# Logic to start the report generation process
report_upload()
else:
display_streamlit_updates()
if name == “main”:
main()
could kindly help me out ?