[text] exl

Viewer

  1. # from langchain.indexes import VectorstoreIndexCreator
  2. # from langchain.chains import RetrievalQA
  3. # from langchain.llms import OpenAI
  4. # import os
  5.  
  6. # os.environ["OPENAI_API_KEY"] = "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"
  7.  
  8. # loader = CSVLoader(file_path='Consolidated Chatgpt commentary_Nifty 50_Pilot1 - Copy.csv',encoding='utf-8')
  9.  
  10. # index_creator = VectorstoreIndexCreator()
  11. # docsearch = index_creator.from_loaders([loader])
  12.  
  13. # chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0.7,model_name='gpt-3.5-turbo'), chain_type="stuff", retriever=docsearch.vectorstore.as_retriever(), input_key="question")
  14.  
  15.  
  16. # query = "on which date change dod was highest"
  17. # response = chain({"question": query})
  18.  
  19. # print(response['result'])
  20.  
  21.  
  22. import os 
  23. import ast
  24. from langchain.llms import OpenAI
  25. from langchain.document_loaders import TextLoader
  26. from langchain.document_loaders import PyPDFLoader
  27. from langchain.indexes import VectorstoreIndexCreator
  28. import streamlit as st
  29. from streamlit_chat import message
  30. import pandas as pd
  31. from langchain.agents import create_pandas_dataframe_agent
  32. from langchain.chat_models import ChatOpenAI
  33. from langchain.llms import OpenAI
  34. from langchain.agents import create_csv_agent
  35. from langchain.agents.agent_types import AgentType
  36. from fpdf import FPDF
  37. import spacy
  38.  
  39. import matplotlib.pyplot as plt
  40. import seaborn as sns
  41. from langchain.text_splitter import CharacterTextSplitter,RecursiveCharacterTextSplitter
  42. from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
  43. from langchain.vectorstores import FAISS
  44. from langchain.chat_models import ChatOpenAI
  45. from langchain.memory import ConversationBufferMemory
  46. from langchain.chains import ConversationalRetrievalChain
  47. import openai
  48. import tiktoken
  49.  
  50.  
  51. os.environ["OPENAI_API_KEY"] = "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"
  52. openai.api_key="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"
  53. def summarize_text(chunk):
  54.     response = openai.Completion.create(
  55.         engine='text-davinci-003',
  56.         prompt=chunk,
  57.         max_tokens=500,  # Adjust as per your desired summary length
  58.         temperature=0.3,  # Controls the randomness of the output (0.0 - 1.0)
  59.         n = 1  # Number of completions to generate
  60.     )
  61.     return response.choices[0].text.strip()
  62.  
  63. def text_to_chunks(text):
  64.     nlp = spacy.load("en_core_web_sm")
  65.     chunks = [[]]
  66.     chunk_total_words = 0
  67.  
  68.     sentences = nlp(text)
  69.  
  70.     for sentence in sentences.sents:
  71.         chunk_total_words += len(sentence.text.split(" "))
  72.  
  73.         if chunk_total_words > 2000:
  74.             chunks.append([])
  75.             chunk_total_words = len(sentence.text.split(" "))
  76.  
  77.         chunks[len(chunks)-1].append(sentence.text)
  78.  
  79.     return chunks
  80.  
  81. def num_tokens_from_string(string: str, encoding_name: str) -> int:
  82.     encoding = tiktoken.get_encoding(encoding_name)
  83.     num_tokens = len(encoding.encode(string))
  84.     return num_tokens
  85.  
  86.  
  87. def get_text_chunks(text):
  88.     text_splitter = RecursiveCharacterTextSplitter(
  89.         
  90.         chunk_size=2000,
  91.         chunk_overlap=200,
  92.         length_function=len
  93.     )
  94.     chunks = text_splitter.split_text(text)
  95.     return chunks
  96.  
  97.  
  98.  
  99.  
  100. def get_vectorstore(text_chunks):
  101.     embeddings = OpenAIEmbeddings()
  102.     vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
  103.     return vectorstore
  104.  
  105.  
  106. def get_conversation_chain(vectorstore):
  107.     llm = ChatOpenAI(temperature=0.5,model_name='gpt-3.5-turbo')
  108.     memory = ConversationBufferMemory(
  109.         memory_key='chat_history', return_messages=True)
  110.     conversation_chain = ConversationalRetrievalChain.from_llm(
  111.         llm=llm,
  112.         # chain_type= "map_reduce",
  113.         chain_type= "refine",
  114.  
  115.         retriever=vectorstore.as_retriever(),
  116.         memory=memory
  117.     )
  118.     return conversation_chain
  119.  
  120. def get_python_repl_ast(data):
  121.   """Get the python_repl_ast data from the list of data.
  122.  
  123.   Args:
  124.     data: The list of data.
  125.  
  126.   Returns:
  127.     The python_repl_ast data.
  128.   """
  129.  
  130.   
  131.   return data.split("tool_input")[1].split("=")[1].split(",")[0].replace('"','')
  132.  
  133. model_id = "gpt-3.5-turbo"
  134. # df = pd.read_csv('CustomeCSV.csv')
  135.  
  136. # print(df.loc[df['City'] == 'Bengaluru', 'Company'])
  137. # llm = OpenAI(temperature=0,model_name="gpt-3.5-turbo")
  138.  
  139. # agent = create_pandas_dataframe_agent(
  140. #     llm,
  141. #     df,
  142. #     verbose=True
  143. # )
  144. # agent.run("Give me top 100 company name having more than 5 investors. Result should be in a tabular format with three rows Company Name,no of investor,City")
  145.  
  146. # print(df[df['No. of Investors'] > 5].head(100)[['Company', 'No. of Investors', 'City']])
  147. # csv_agent = create_csv_agent(ChatOpenAI(temperature=0), 'CustomeCSV.csv', verbose=True,return_intermediate_steps=True,  agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)
  148. # # data=csv_agent.run("You need to provide date,commentarty,change where change has positive value. Result should be in a table format.")
  149. # response = csv_agent({"input":"First convert column Date into datetime format.Please fetch and consolidate the values of 'Nifty Closing', 'Commentary, from  date 03/8/2023 to 5/24/2023'. Post that please summarise the value in 3 to 4 lines and mention the opening and closing price of nifty along with dates"})
  150. # if "df" in str(response["output"]) and len(str(response["output"]))<20:
  151. #     print(eval(response["output"]))
  152. # else:
  153. #     print(response["output"])
  154. #     # print(response["intermediate_steps"])
  155. #     data=str(response["intermediate_steps"])
  156. #     df = pd.read_csv('CustomeCSV.csv')
  157. #     try:
  158. #         print(eval(data.split("tool_input=")[1].split(", log=")[0].replace('"','')))
  159. #     except Exception as e:
  160. #         print("")
  161.  
  162.  
  163.  
  164.  
  165. df = pd.read_csv('CustomeCSV.csv')
  166. # print(df)
  167. from_date='03/06/2023'
  168. to_date='05/25/2023'
  169. df['Date'] = pd.to_datetime(df['Date'])  
  170. opening_price=df[df['Date']==from_date]['NIFTY Closing'].values
  171. closing_price=df[df['Date']==to_date]['NIFTY Closing'].values
  172.  
  173. df.set_index('Date', inplace=True)
  174. filtered_df = df.loc[from_date:to_date]
  175. min_value = filtered_df['Change'].min()
  176. max_value = filtered_df['Change'].max()
  177. avg_value = round(filtered_df['Change'].mean(), 2)
  178.  
  179. df = pd.read_csv('CustomeCSV.csv')
  180. df['Date'] = pd.to_datetime(df['Date'])  
  181. summarising="The opening price for Nifty on date {0} was {1} and closing price for Nifty on date {2} was {3}. Maximum change between date {0} and {2} was {4} and lowest change was {5} with average change value {6}".format(from_date,opening_price,to_date,closing_price,max_value,min_value,avg_value)
  182. df=df[df['Date'].between(from_date, to_date)][['Date','Change', 'NIFTY Closing', 'NIFTY Commentary', 'Top 3 Gainers', 'Top 3 Losers']]
  183.  
  184.  
  185. text_all=''
  186. summary=""
  187. for index, row in df.iterrows():
  188.     # print(row['Date'])
  189.     text_all=text_all+"\n\n"+str(row['Date'])+ " "+str('NIFTY Closing')+" "+str(row['Change'])+ " "+str('NIFTY Commentary')+" "+" "+str(row['Top 3 Gainers'])+ " "+" "+str(row['Top 3 Losers'])
  190.     # text_all="\n"+str(row['Date'])+ " "+str('NIFTY Closing')+" "+str(row['Change'])+ " "+str('NIFTY Commentary')+" "+" "+str(row['Top 3 Gainers'])+ " "+" "+str(row['Top 3 Losers'])
  191.     # summary=summary+"\n "+summarize_text("summarise the sentence with necessary key points in short and it should contains date closing price change in value"+str(text_all))
  192.     
  193. # print(len(text_all))
  194. # print(text_to_chunks(text_all))
  195.  
  196. # for row in text_to_chunks(text_all):
  197. #     print("-"*50)
  198. #     # print(row)
  199. #     # print(num_tokens_from_string(str(row), "cl100k_base"))
  200. #     summary=summary+" "+summarize_text("Summarise the points in 1 to 3 lines:\n "+str(row))
  201. #     # print(summarize_text("Summarise the points in 1 to 3 lines:\n "+str(row)))
  202.  
  203. # print(summarising)
  204. # print(summary)
  205. # # print(get_text_chunks(text_all))
  206.  
  207. text_chunks=get_text_chunks(text_all)
  208. vectorstore=get_vectorstore(text_chunks)
  209. response=get_conversation_chain(vectorstore)
  210. result = response({"question": "Summarise the content in details"})
  211. data="\n"+ str(result['answer'])
  212. # data="\n"+ str(summary)
  213.  
  214. print(summarising + str(data))
  215.  
  216.  
  217.  
  218.  
  219.  
  220.  
  221.  
  222. # import csv
  223. # import os
  224. # import openai
  225. # from langchain.embeddings.openai import OpenAIEmbeddings
  226. # from langchain.chat_models import ChatOpenAI
  227. # from langchain.chains import ConversationalRetrievalChain
  228. # from langchain.vectorstores import FAISS
  229. # from langchain.vectorstores.base import Document
  230. # from langchain.memory import ConversationBufferMemory
  231. # from langchain.llms import OpenAI
  232.  
  233. # os.environ["OPENAI_API_KEY"] = "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"
  234.  
  235.  
  236. # def read_csv_into_vector_document(file, text_cols):
  237. #     with open(file, newline='',encoding='utf-8') as csv_file:
  238. #         csv_reader = csv.DictReader(csv_file)
  239. #         text_data = []
  240. #         for row in csv_reader:
  241. #             text = ' '.join([row[col] for col in text_cols])
  242. #             text_data.append(text)
  243. #         return [Document(page_content=text) for text in text_data]
  244.  
  245.  
  246.  
  247.  
  248. # data = read_csv_into_vector_document("Consolidated Chatgpt commentary_Nifty 50_Pilot1 - Copy.csv", ["Date", "NIFTY Closing", "change dod","NIFTY Commentary","Top 3 Gainers","Top 3 Losers"])
  249. # embeddings = OpenAIEmbeddings()
  250. # vectors = FAISS.from_documents(data, embeddings)
  251. # memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
  252. # chain = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0.5) , vectors.as_retriever(), memory=memory)
  253. # result = chain({"question": "What is this data all about"})
  254. # print(result['answer'])
  255.  
  256.  
  257. #pip install streamlit langchain openai faiss-cpu tiktoken
  258.  
  259. # import streamlit as st
  260. # from streamlit_chat import message
  261. # from langchain.embeddings.openai import OpenAIEmbeddings
  262. # from langchain.chat_models import ChatOpenAI
  263. # from langchain.chains import ConversationalRetrievalChain
  264. # from langchain.document_loaders.csv_loader import CSVLoader
  265. # from langchain.vectorstores import FAISS
  266. # import tempfile
  267. # import os
  268. # from langchain.memory import ConversationBufferMemory
  269. # from langchain.llms import OpenAI
  270.  
  271. # from langchain.vectorstores import Chroma 
  272.  
  273. # os.environ["OPENAI_API_KEY"] = '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'
  274.  
  275.  
  276. # # loader = CSVLoader(file_path="Consolidated Chatgpt commentary_Nifty 50_Pilot1.csv", encoding="utf-8")
  277. # loader = CSVLoader(file_path="CustomeCSV.csv", encoding="utf-8")
  278.  
  279. # data = loader.load()
  280. # # embeddings = OpenAIEmbeddings()
  281. # # vectors = FAISS.from_documents(data, embeddings)
  282. # # memory = ConversationBufferMemory(
  283. # #         memory_key='chat_history', return_messages=True)
  284. # # response = ConversationalRetrievalChain.from_llm(llm = ChatOpenAI(temperature=0,model_name='gpt-3.5-turbo', openai_api_key="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"),
  285. # #                                                                       retriever=vectors.as_retriever(),memory=memory)
  286.  
  287.  
  288. # # # print(data[:500])
  289. # embeddings = OpenAIEmbeddings()
  290. # vectordb = Chroma.from_documents(data, embedding=embeddings, 
  291. #                                  persist_directory=".")
  292. # vectordb.persist()
  293. # memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
  294. # response = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0.2,model_name='gpt-3.5-turbo') , vectordb.as_retriever(), memory=memory)
  295.  
  296.  
  297.  
  298. # result = response({"question": """
  299. #                              Your task is to summarise NIFTY Commentary in 100 words from date 3/8/2023 to 3/22/2023
  300. #                    """})
  301. # print(len(result))
  302.  
  303. # print("----------------------------------------")
  304.  
  305. # print(result['answer'])
  306.  
  307.  

Editor

You can edit this paste and save as new:


File Description
  • exl
  • Paste Code
  • 09 May-2024
  • 11.51 Kb
You can Share it: