# Using flask to make an api
# import necessary libraries and functions
from flask import Flask, jsonify, request, render_template


from pydantic import BaseModel
from ast import literal_eval
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")


import langchain
from langchain.vectorstores import FAISS
from langchain.embeddings.openai import OpenAIEmbeddings



# creating a Flask app
app = Flask(__name__)
  
# on the terminal type: curl http://127.0.0.1:5000/
# returns hello world when we use GET.
# returns the data that we send when we use POST.
@app.route('/related', methods = ['GET', 'POST'])
def home():
    if(request.method == 'GET'):
  
        data = "its up"
        return jsonify({'data': data})
    if(request.method == 'POST'):
  

        temp= request.get_json()
        print(temp)
        vector = temp["ve"]
        ticker = temp["ticker"]

        embeddings = OpenAIEmbeddings(openai.api_key)
        print(str(ticker))
        new_db = FAISS.load_local(str(ticker), embeddings)
        ar = literal_eval(vector)
        docs_and_scores = new_db.similarity_search_by_vector(ar)
        size = len(docs_and_scores)
        data = ""
        for i in range(0,size):
            data+=(docs_and_scores[i].page_content + "\n\n")


        print(data)


        return jsonify({'data': data})

def relatedwords(ticker, vembeddings):
    
    embeddings = OpenAIEmbeddings()
    print(str(ticker))
    new_db = FAISS.load_local(ticker, embeddings)
        # ar = literal_eval(vector)
    docs_and_scores = new_db.similarity_search_by_vector(vembeddings)
    size = len(docs_and_scores)
    data = ""
    for i in range(0,size):
        data+=(docs_and_scores[i].page_content + "\n\n")


    print(data)


    return data
  

def completion(context):
    completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    temperature = 0,
    messages=[
        {
          "role": "system",
          "content": "You are a financial assistant that VERY ACCURATELY and CONCISELY answers queries using publicly filled annual reports of publicly traded companies. Use the CONTEXT provided to form your answer. Keep your answer under 5 sentences. Be accurate, helpful, concise, and clear, while performing accurate mathematical calculations."
        },
        {
          "role": "user",
          "content": context
        }
    ]
    )

    return (completion.choices[0].message["content"])



def embeddingsgenerate(embeddingsof):
    
    embeddings = openai.Embedding.create(
        model="text-embedding-ada-002",
        input=embeddingsof
    )
    return embeddings["data"][0]["embedding"]


@app.route('/generate_embeddings', methods= ['GET', 'POST'])
def get_embeddings():
    if(request.method == 'GET'):
  
        data = "its up"
        return jsonify({'data': data})
    if(request.method == 'POST'):
        data = request.get_json()
        texts = data['texts']
        embeddings = openai.Encodings.create(texts)
        return jsonify({'embeddings': embeddings})



@app.route('/<path_name>',methods=['GET', 'POST'])
def answer_question(path_name):

    urlforprice = ("https://s.tradingview.com/embed-widget/symbol-info/?locale=en&colorTheme=dark&symbol=BSE:"+path_name)
    if request.method == 'POST':
        # User submitted a question, so process it and get an answer from OpenAI
        question = request.form['question']
        # openai_api_key = request.form['openai_api_key']
        prompt = f"{question}"

        embeddings_recieved = embeddingsgenerate(question)

        context = relatedwords(path_name, embeddings_recieved)

        questionforgpt = "CONTEXT\n\n" + context + "\nQUESTION\n" + prompt

        answerfromgpt = completion(questionforgpt)
        print(answerfromgpt)
        
        return render_template('chat.html', path_name=path_name, questionasked=prompt, urlforprice=urlforprice, embeddings_recieved = context, answer_received = answerfromgpt)

    else:
        answer = "not yet used"
        # Render the answer on an HTML template
        return render_template('chat.html', path_name=path_name, answer=answer,urlforprice=urlforprice)
  

@app.route('/',methods=['GET'])
def homepage():
    return render_template('home.html')


# driver function
if __name__ == '__main__':
  
    app.run(debug = True)



langchain.vectorstores.FAISS.load_local langchain.embeddings.openai.OpenAIEmbeddings
[((235, 262), 'os.getenv', 'os.getenv', (['"""OPENAI_API_KEY"""'], {}), "('OPENAI_API_KEY')\n", (244, 262), False, 'import os\n'), ((412, 427), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (417, 427), False, 'from flask import Flask, jsonify, request, render_template\n'), ((1396, 1414), 'langchain.embeddings.openai.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (1412, 1414), False, 'from langchain.embeddings.openai import OpenAIEmbeddings\n'), ((1451, 1487), 'langchain.vectorstores.FAISS.load_local', 'FAISS.load_local', (['ticker', 'embeddings'], {}), '(ticker, embeddings)\n', (1467, 1487), False, 'from langchain.vectorstores import FAISS\n'), ((1807, 2295), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': '"""gpt-3.5-turbo"""', 'temperature': '(0)', 'messages': "[{'role': 'system', 'content':\n    'You are a financial assistant that VERY ACCURATELY and CONCISELY answers queries using publicly filled annual reports of publicly traded companies. Use the CONTEXT provided to form your answer. Keep your answer under 5 sentences. Be accurate, helpful, concise, and clear, while performing accurate mathematical calculations.'\n    }, {'role': 'user', 'content': context}]"}), "(model='gpt-3.5-turbo', temperature=0, messages\n    =[{'role': 'system', 'content':\n    'You are a financial assistant that VERY ACCURATELY and CONCISELY answers queries using publicly filled annual reports of publicly traded companies. Use the CONTEXT provided to form your answer. Keep your answer under 5 sentences. Be accurate, helpful, concise, and clear, while performing accurate mathematical calculations.'\n    }, {'role': 'user', 'content': context}])\n", (1835, 2295), False, 'import openai\n'), ((2502, 2577), 'openai.Embedding.create', 'openai.Embedding.create', ([], {'model': '"""text-embedding-ada-002"""', 'input': 'embeddingsof'}), "(model='text-embedding-ada-002', input=embeddingsof)\n", (2525, 2577), False, 'import openai\n'), ((4211, 4239), 'flask.render_template', 'render_template', (['"""home.html"""'], {}), "('home.html')\n", (4226, 4239), False, 'from flask import Flask, jsonify, request, render_template\n'), ((709, 732), 'flask.jsonify', 'jsonify', (["{'data': data}"], {}), "({'data': data})\n", (716, 732), False, 'from flask import Flask, jsonify, request, render_template\n'), ((785, 803), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (801, 803), False, 'from flask import Flask, jsonify, request, render_template\n'), ((906, 938), 'langchain.embeddings.openai.OpenAIEmbeddings', 'OpenAIEmbeddings', (['openai.api_key'], {}), '(openai.api_key)\n', (922, 938), False, 'from langchain.embeddings.openai import OpenAIEmbeddings\n'), ((1038, 1058), 'ast.literal_eval', 'literal_eval', (['vector'], {}), '(vector)\n', (1050, 1058), False, 'from ast import literal_eval\n'), ((1310, 1333), 'flask.jsonify', 'jsonify', (["{'data': data}"], {}), "({'data': data})\n", (1317, 1333), False, 'from flask import Flask, jsonify, request, render_template\n'), ((2806, 2829), 'flask.jsonify', 'jsonify', (["{'data': data}"], {}), "({'data': data})\n", (2813, 2829), False, 'from flask import Flask, jsonify, request, render_template\n'), ((2879, 2897), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (2895, 2897), False, 'from flask import Flask, jsonify, request, render_template\n'), ((2949, 2979), 'openai.Encodings.create', 'openai.Encodings.create', (['texts'], {}), '(texts)\n', (2972, 2979), False, 'import openai\n'), ((2995, 3030), 'flask.jsonify', 'jsonify', (["{'embeddings': embeddings}"], {}), "({'embeddings': embeddings})\n", (3002, 3030), False, 'from flask import Flask, jsonify, request, render_template\n'), ((3792, 3957), 'flask.render_template', 'render_template', (['"""chat.html"""'], {'path_name': 'path_name', 'questionasked': 'prompt', 'urlforprice': 'urlforprice', 'embeddings_recieved': 'context', 'answer_received': 'answerfromgpt'}), "('chat.html', path_name=path_name, questionasked=prompt,\n    urlforprice=urlforprice, embeddings_recieved=context, answer_received=\n    answerfromgpt)\n", (3807, 3957), False, 'from flask import Flask, jsonify, request, render_template\n'), ((4059, 4152), 'flask.render_template', 'render_template', (['"""chat.html"""'], {'path_name': 'path_name', 'answer': 'answer', 'urlforprice': 'urlforprice'}), "('chat.html', path_name=path_name, answer=answer,\n    urlforprice=urlforprice)\n", (4074, 4152), False, 'from flask import Flask, jsonify, request, render_template\n')]