# -*- coding: utf-8 -*-
import random
import streamlit as st
from langchain.llms import OpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
#from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
import openai
# from playsound import playsound
from gtts import gTTS
from PyPDF2 import PdfReader
from utils import text_to_docs
from langchain import PromptTemplate, LLMChain
#import os
#from io import StringIO
#from langchain.embeddings.openai import OpenAIEmbeddings
#from langchain.chains.summarize import load_summarize_chain
#import os
#import pyaudio
#import wave
#import langchain
#from langchain.document_loaders import UnstructuredPDFLoader
#from io import BytesIO
# import streamlit.components.v1 as components
#from st_custom_components import st_audiorec, text_to_docs


#import sounddevice as sd
#from scipy.io.wavfile import write
from usellm import Message, Options, UseLLM

llm = OpenAI(model_name='text-davinci-003', temperature=0.2, max_tokens=512, openai_api_key=st.secrets["api_key"])

def record_audio(filename):
    duration=5
    sample_rate = 44100
    # Record audio
    audio_data = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=6)
    st.write('Recording started. Speak into the microphone...')
    # Wait for recording to complete
    sd.wait()
    # Save the recorded audio to a WAV file
    write(filename, sample_rate, audio_data)

    st.write(f'Recording saved as {filename}')
    
def transcribe_audio(filename):
    with open(filename, "rb") as audio_file:
        transcript = openai.Audio.transcribe("whisper-1", filename)
        return transcript["text"]


st.title("Suspicious Activity Reporting")
st.subheader('Evidence Processor')

model_name = "sentence-transformers/all-MiniLM-L6-v2"

@st.cache_data
def usellm(prompt):

    service = UseLLM(service_url="https://usellm.org/api/llm")
    messages = [
      Message(role="system", content="You are a fraud analyst"),
      Message(role="user", content=f"{prompt}"),
      ]
    options = Options(messages=messages)
    response = service.chat(options)
    return response.content


@st.cache_resource
def embed(model_name):
    hf_embeddings = HuggingFaceEmbeddings(model_name=model_name)
    
    return hf_embeddings

# @st.cache_resource
# def chain(_llm):
#     chain = load_summarize_chain(llm=_llm, chain_type="map_reduce")
# chain = load_summarize_chain(llm=llm, chain_type="map_reduce")

hf_embeddings = embed(model_name) 

# File Upload
file = st.file_uploader("Upload a file")

st.write(file)
text_splitter = RecursiveCharacterTextSplitter(
    # Set a really small chunk size, just to show.
    chunk_size = 1500,
    chunk_overlap  = 100,
    length_function = len,
    separators=["\n\n", "\n", " ", ""]
)
#text_splitter = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=100, chunk_overlap=0)
#texts = ''
@st.cache_data
def embedding_store(file):
    # save file
    pdf_reader = PdfReader(file)
    text = ""
    for page in pdf_reader.pages:
        text += page.extract_text()
    #st.write(text)
    texts =  text_splitter.split_text(text)
    docs = text_to_docs(texts)
    #st.write(texts)
    docsearch = FAISS.from_documents(docs, hf_embeddings)
    return docs, docsearch

# Submit Button
if st.button("Submit"):
    if file is not None:
        # File handling logic
        st.write("File Uploaded...")
        _, docsearch = embedding_store(file)
        queries ="Any fraud encountered in the passed document?\
        if any."
        contexts = docsearch.similarity_search(queries, k=1)
        prompts = f"Give concise answer to the below questions as truthfully as possible as per given context only,\n\n\
              Context: {contexts}\n\
              Response (in readable bullet points): "
              

        response = usellm(prompts)
        # Print the assistant's response
        # st.subheader("Few informative points in the uploaded document are as follows:")
        # st.write(response)

#st.write("Uploaded File Contents:")
if file is not None:
    docs, docsearch = embedding_store(file)
#docs = text_to_docs(texts)
#st.write(docs)
#summary = chain.run(docs)
#st.write(summary)
#st.header("Speech and Text Input")
# Speech Input
# st.subheader("Speech Input")
# wav_audio_data = st_audiorec()

# if wav_audio_data is not None: 
#     st.audio(wav_audio_data, format='audio/wav')
#     audio_text = transcribe_audio(wav_audio_data)
#     st.write(audio_text)
    
# if st.button("Voice Input"):
#     rand = random.randint(1, 10000)*random.randint(10001,20000)
#     audio_filename = f"recorded_audio{rand}.wav"
   
#     record_audio(filename=audio_filename)
#     aud = transcribe_audio(audio_filename)
#     st.write(aud)

# Text Input
st.subheader("Ask Questions")
query = st.text_input('your queries will go here...')

def LLM_Response():
    llm_chain = LLMChain(prompt=prompt, llm=llm)
    response = llm_chain.run({"query":query, "context":context})
    return response


        
if query:
    # Text input handling logic
    #st.write("Text Input:")
    #st.write(text_input)
    context = docsearch.similarity_search(query, k=5)
    prompt = f"Act as a financial analyst and give concise answer to below Question as truthfully as possible, with given Context\n\n\
              Question: {query}\n\
              Context: {context}\n\
              Response: "

    #prompt = PromptTemplate(template=prompt, input_variables=["query", "context"])
    response = usellm(prompt) #LLM_Response()
    st.write(response)
    # language = 'en'
    # Create a gTTS object
    # tts = gTTS(text=response, lang=language)
    
    # Save the audio file
    # rand = random.randint(1, 10000)*random.randint(10001,20000)
    # audio_file = f'output{rand}.mp3'
    # tts.save(audio_file)
    # playsound(audio_file)

langchain.LLMChain langchain.embeddings.HuggingFaceEmbeddings langchain.text_splitter.RecursiveCharacterTextSplitter langchain.llms.OpenAI langchain.vectorstores.FAISS.from_documents
[((1047, 1159), 'langchain.llms.OpenAI', 'OpenAI', ([], {'model_name': '"""text-davinci-003"""', 'temperature': '(0.2)', 'max_tokens': '(512)', 'openai_api_key': "st.secrets['api_key']"}), "(model_name='text-davinci-003', temperature=0.2, max_tokens=512,\n    openai_api_key=st.secrets['api_key'])\n", (1053, 1159), False, 'from langchain.llms import OpenAI\n'), ((1791, 1832), 'streamlit.title', 'st.title', (['"""Suspicious Activity Reporting"""'], {}), "('Suspicious Activity Reporting')\n", (1799, 1832), True, 'import streamlit as st\n'), ((1834, 1868), 'streamlit.subheader', 'st.subheader', (['"""Evidence Processor"""'], {}), "('Evidence Processor')\n", (1846, 1868), True, 'import streamlit as st\n'), ((2673, 2706), 'streamlit.file_uploader', 'st.file_uploader', (['"""Upload a file"""'], {}), "('Upload a file')\n", (2689, 2706), True, 'import streamlit as st\n'), ((2710, 2724), 'streamlit.write', 'st.write', (['file'], {}), '(file)\n', (2718, 2724), True, 'import streamlit as st\n'), ((2742, 2869), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': '(1500)', 'chunk_overlap': '(100)', 'length_function': 'len', 'separators': "['\\n\\n', '\\n', ' ', '']"}), "(chunk_size=1500, chunk_overlap=100,\n    length_function=len, separators=['\\n\\n', '\\n', ' ', ''])\n", (2772, 2869), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter\n'), ((3468, 3487), 'streamlit.button', 'st.button', (['"""Submit"""'], {}), "('Submit')\n", (3477, 3487), True, 'import streamlit as st\n'), ((4989, 5018), 'streamlit.subheader', 'st.subheader', (['"""Ask Questions"""'], {}), "('Ask Questions')\n", (5001, 5018), True, 'import streamlit as st\n'), ((5028, 5073), 'streamlit.text_input', 'st.text_input', (['"""your queries will go here..."""'], {}), "('your queries will go here...')\n", (5041, 5073), True, 'import streamlit as st\n'), ((1343, 1402), 'streamlit.write', 'st.write', (['"""Recording started. Speak into the microphone..."""'], {}), "('Recording started. Speak into the microphone...')\n", (1351, 1402), True, 'import streamlit as st\n'), ((1554, 1596), 'streamlit.write', 'st.write', (['f"""Recording saved as {filename}"""'], {}), "(f'Recording saved as {filename}')\n", (1562, 1596), True, 'import streamlit as st\n'), ((1982, 2030), 'usellm.UseLLM', 'UseLLM', ([], {'service_url': '"""https://usellm.org/api/llm"""'}), "(service_url='https://usellm.org/api/llm')\n", (1988, 2030), False, 'from usellm import Message, Options, UseLLM\n'), ((2189, 2215), 'usellm.Options', 'Options', ([], {'messages': 'messages'}), '(messages=messages)\n', (2196, 2215), False, 'from usellm import Message, Options, UseLLM\n'), ((2352, 2396), 'langchain.embeddings.HuggingFaceEmbeddings', 'HuggingFaceEmbeddings', ([], {'model_name': 'model_name'}), '(model_name=model_name)\n', (2373, 2396), False, 'from langchain.embeddings import HuggingFaceEmbeddings\n'), ((3135, 3150), 'PyPDF2.PdfReader', 'PdfReader', (['file'], {}), '(file)\n', (3144, 3150), False, 'from PyPDF2 import PdfReader\n'), ((3316, 3335), 'utils.text_to_docs', 'text_to_docs', (['texts'], {}), '(texts)\n', (3328, 3335), False, 'from utils import text_to_docs\n'), ((3375, 3416), 'langchain.vectorstores.FAISS.from_documents', 'FAISS.from_documents', (['docs', 'hf_embeddings'], {}), '(docs, hf_embeddings)\n', (3395, 3416), False, 'from langchain.vectorstores import FAISS\n'), ((5114, 5146), 'langchain.LLMChain', 'LLMChain', ([], {'prompt': 'prompt', 'llm': 'llm'}), '(prompt=prompt, llm=llm)\n', (5122, 5146), False, 'from langchain import PromptTemplate, LLMChain\n'), ((5779, 5797), 'streamlit.write', 'st.write', (['response'], {}), '(response)\n', (5787, 5797), True, 'import streamlit as st\n'), ((1704, 1750), 'openai.Audio.transcribe', 'openai.Audio.transcribe', (['"""whisper-1"""', 'filename'], {}), "('whisper-1', filename)\n", (1727, 1750), False, 'import openai\n'), ((2056, 2113), 'usellm.Message', 'Message', ([], {'role': '"""system"""', 'content': '"""You are a fraud analyst"""'}), "(role='system', content='You are a fraud analyst')\n", (2063, 2113), False, 'from usellm import Message, Options, UseLLM\n'), ((2122, 2163), 'usellm.Message', 'Message', ([], {'role': '"""user"""', 'content': 'f"""{prompt}"""'}), "(role='user', content=f'{prompt}')\n", (2129, 2163), False, 'from usellm import Message, Options, UseLLM\n'), ((3555, 3583), 'streamlit.write', 'st.write', (['"""File Uploaded..."""'], {}), "('File Uploaded...')\n", (3563, 3583), True, 'import streamlit as st\n')]