# -*- coding: utf-8 -*-
"""RAG_example.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1cuFKFmydzhQXy3hl25bDONFANJp7eOcA
"""

from google.colab import userdata
from langchain_openai import ChatOpenAI
from langchain.chat_models import init_chat_model
from langchain_classic.chains import ConversationalRetrievalChain
import os

# set the openai key and define the LLM
os.environ['OPENAI_API_KEY'] = userdata.get('openai')
llm = init_chat_model("o4-mini-high", model_provider="openai")

# parse and load the PDF document
docs = []
path = "/content/"
from langchain_community.document_loaders import PyPDFLoader, TextLoader
import pypdf
for pdf in os.listdir(path):
  if pdf.endswith(".pdf"):
    loader = PyPDFLoader(path+pdf)
    docs.extend(loader.load())

from langchain_text_splitters import CharacterTextSplitter
text_splitter= CharacterTextSplitter(chunk_size=5, chunk_overlap=0)
split_docs = text_splitter.split_documents(docs)

# load the document into a knowledge base
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings # Updated import
faiss_index = FAISS.from_documents(split_docs, OpenAIEmbeddings())
faiss_index.save_local("civil law")

# load and saved embeddings
embeddings = OpenAIEmbeddings()
loaded_vectors= FAISS.load_local("civil law", embeddings, allow_dangerous_deserialization=True)

# create RAG chain

from langchain_openai import ChatOpenAI # Updated import

QA= ConversationalRetrievalChain.from_llm(ChatOpenAI(), retriever=loaded_vectors.as_retriever()) # Updated argument name

chat_history = []

REWRITE_PROMPT = (
    "You are a smart instructor of Spinning Indoor Cycling Programs with the following teaching styles and personality description: \n"
    "Coach Ash: A female instructor. My teaching style is raw, real, and high-energy. My classes aren’t about frills - they’re about grit, sweat, and walking out stronger than you came in. I’ll push you past what you thought possible, while keeping it motivating, uplifting, and empowering.\n"
    "Use a professional, friendly, and instructor-like tone, to answer the question:\n"
    "{question}\n"
)

def rag(query):
  response = QA({"question":query, "chat_history":chat_history})
  chat_history.append((query, response['answer']))

  return response['answer']

def RAG(query):
  prompt = REWRITE_PROMPT.format(question=query)
  response = QA({"question":prompt, "chat_history":chat_history})
  chat_history.append((query, response['answer']))

  return response['answer']

"""1.	Coach Ash: A female instructor. My teaching style is raw, real, and high-energy. My classes aren’t about frills - they’re about grit, sweat, and walking out stronger than you came in. I’ll push you past what you thought possible, while keeping it motivating, uplifting, and empowering.

2.	Coach Javi: A male instructor. My teaching style is rhythm ride – we ride together to the beat of the music. I came from Mexico, and my class is full of Fuego energy, haha.

3.	Coach Claire: A female instructor. My teaching style is more fun and happy. I hope everyone can enjoy the workout with me. Also, if you are interested in hip-hop music and popular culture, feel free to join my class.

4.	Coach Ally: A female instructor. My teaching style is motivating and enthusiastic with a strong sense of curiosity for personal growth with personal growth of myself and community I foster. I am open-minded, approachable, and always eager to learn new things about the fitness and the world around me. Building strong connections and fostering a sense of belonging within the Hustl community has been one of my greatest joys.

5.	Coach Xin: A male instructor. My teaching style is calm, focused on the details, but with various music genres. My class ensures everyone can genuinely improve after every single practice with me. Also, I am a frenetic fan of fitness and willing to motivate you to improve your level. I hope everyone could not only improve your body fitness but also enjoy the workout.

6. Coach Jordan: A male instructor. My teaching style is true rhythm riding. I’m with you, doing the workout, the whole time. Catch that beat. Add a bit of choreo. Find new strength and connection to your body while you ride. Cardio doesn’t have to be a chore, so I say: we might as well make it a party!
"""

from google.colab import drive
drive.mount('/content/drive')

!pip install --upgrade langchain langchain-community langchain-openai langchain-text-splitters faiss-cpu pypdf

rag("For a 45-minutes Spinning training class, how to arrange aerobic and anarobic training?")

rag("How to present your ride in the Spinning class?")

RAG("Why can we not do the upper body movement in Spinning class?")

RAG("During the Sprint, why can we not add zero resistance?")

RAG("Coach, I am a 185cm tall and 85kg male, and i want to improve my cardio through Spinning. Could you help me design a training plan?")

RAG("During the Spinning workout, why we cannot add too much resistance during the Climb riding? I want to improve my leg strength")

RAG("Is Spinning suitable for improving the leg strength?")

RAG("Besides Spinning, what else workout I could do for improving my leg strength?")

RAG("Is Spinning suitable for improving core and upper body?")

RAG("Before we start the workout, how to properly set up a bike?")

RAG("To decide whether to join in the Spinning program, what should we prepare or consult to the physician?")

RAG("Is Spinning suitable for senior people and children?")

RAG("I have cardiovescular disease, can't I join in the Spinning program?")