import streamlit as st
from sentence_transformers import SentenceTransformer
import pandas as pd
import numpy as np
import os
# Load your retrieval model
retrieval_model_path = "model_jatin//"
retrieval_model = SentenceTransformer(retrieval_model_path)

# Load and prepare your data
data = pd.read_csv('sales_portal.txt', sep="\t", encoding='cp1252', header=None)
headers = data.iloc[0]
new_df = pd.DataFrame(data.values[1:], columns=headers)
new_df.rename(columns={' Query': 'user_query', 'Response': 'answer'}, inplace=True)
# new_df = new_df[:5]
# Add image_path and pdf_path columns (replace with actual paths)
new_df['image_path'] = 'NlpSql//images//1.PNG'
new_df['pdf_path'] = 'NlpSql//images//Tech&Talk_Newsletter_Feb_2024.pdf'


def get_most_similar_question(userText):
    new_df['user_query'] = new_df['user_query'].str.lower()
    question_list = new_df["user_query"].to_list()
    question_embeddings = retrieval_model.encode(question_list)
    user_text_embedding = retrieval_model.encode([userText.lower()])

    # Calculate similarity scores
    similarity_scores = np.inner(user_text_embedding, question_embeddings).flatten()
    top_match_idx = np.argmax(similarity_scores)
    
    if similarity_scores[top_match_idx] == 0:
        return "Sorry, no similar questions were found for your query."

    matched_row = new_df.iloc[top_match_idx]
    answer = matched_row['answer']
    image_path = matched_row['image_path']
    pdf_path = matched_row['pdf_path']
    
    print('answer',matched_row['answer'])
    print('image_path','NlpSql/images/1.PNG')
    print('pdf_path',matched_row['pdf_path'])
    results = {
        "answer": answer,
        "image": image_path,
        "pdf": pdf_path
    }

    return results

# Streamlit app interface
st.title("Sales Portal Chatbot")

user_input = st.text_input("Ask your question:")
if st.button("Submit"):
    response = get_most_similar_question(user_input)
    
    if isinstance(response, str):
        st.write(response)
    else:
        if response['answer']:
            print('response',response['answer'])
            st.write(response['answer'])
        
        if response['image']:
            if os.path.exists(response['image']):
                print('response',response['image'])
                from PIL import Image
                from numpy import asarray


                # load the image and convert into
                # numpy array
                img = Image.open(response['image'])

                # asarray() class is used to convert
                # PIL images into NumPy arrays
                numpydata = asarray(img)

                # <class 'numpy.ndarray'>
                print(type(numpydata))

                #  shape
                print(numpydata.shape)
                st.image(numpydata, caption='Related Image')
            else:
                st.write("Image not found or path is invalid.")
            
        if response['pdf']:
            if os.path.exists(response['pdf']):
                with open(response['pdf'], 'rb') as file:
                    btn = st.download_button(
                        label="Download related PDF",
                        data=file,
                        file_name=response['pdf'].split('/')[-1],
                        mime="application/pdf"
                    )
            else:
                st.write("PDF not found or path is invalid.")


always giving image not found or path is invalid