Spaces:
Sleeping
Sleeping
Rehman1603
commited on
Commit
•
5722bc8
1
Parent(s):
60cf5cb
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import pandas as pd
|
4 |
+
from langchain.chat_models import ChatOpenAI
|
5 |
+
from langchain.document_loaders import CSVLoader
|
6 |
+
from langchain_together import TogetherEmbeddings
|
7 |
+
from langchain.prompts import ChatPromptTemplate
|
8 |
+
from langchain.vectorstores import Chroma
|
9 |
+
from langchain_core.output_parsers import StrOutputParser
|
10 |
+
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
|
11 |
+
from langchain.document_loaders import CSVLoader
|
12 |
+
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
|
13 |
+
from langchain.vectorstores import Chroma
|
14 |
+
from langchain_core.vectorstores import InMemoryVectorStore
|
15 |
+
from langchain import PromptTemplate
|
16 |
+
from langchain import LLMChain
|
17 |
+
from langchain_together import Together
|
18 |
+
import os
|
19 |
+
|
20 |
+
|
21 |
+
os.environ['TOGETHER_API_KEY'] = "c2f52626b97118b71c0c36f66eda4f5957c8fc475e760c3d72f98ba07d3ed3b5"
|
22 |
+
|
23 |
+
# Initialize global variable for vectorstore
|
24 |
+
vectorstore = None
|
25 |
+
embeddings = TogetherEmbeddings(model="togethercomputer/m2-bert-80M-8k-retrieval")
|
26 |
+
llama3 = Together(model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", max_tokens=1024)
|
27 |
+
def update_csv_files():
|
28 |
+
# Define the login URL and credentials
|
29 |
+
login_url = "https://livesystem.hisabkarlay.com/auth/login"
|
30 |
+
payload = {
|
31 |
+
"username": "user@123",
|
32 |
+
"password": "user@123",
|
33 |
+
"client_secret": "kNqJjlPkxyHdIKt3szCt4PYFWtFOdUheb8QVN8vQ",
|
34 |
+
"client_id": "5",
|
35 |
+
"grant_type": "password"
|
36 |
+
}
|
37 |
+
|
38 |
+
# Send a POST request to the login URL
|
39 |
+
response = requests.post(login_url, data=payload)
|
40 |
+
|
41 |
+
# Check the status and get the response data
|
42 |
+
if response.status_code == 200:
|
43 |
+
print("Login successful!")
|
44 |
+
access_token = response.json()['access_token']
|
45 |
+
else:
|
46 |
+
return f"Failed to log in: {response.status_code}"
|
47 |
+
|
48 |
+
# Profit loss Fetch report
|
49 |
+
report_url = "https://livesystem.hisabkarlay.com/connector/api/profit-loss-report"
|
50 |
+
headers = {
|
51 |
+
"Authorization": f"Bearer {access_token}"
|
52 |
+
}
|
53 |
+
response = requests.get(report_url, headers=headers)
|
54 |
+
profit_loss_data = response.json()['data']
|
55 |
+
keys = list(profit_loss_data.keys())
|
56 |
+
del keys[23] # Adjust according to your needs
|
57 |
+
del keys[20]
|
58 |
+
del keys[19]
|
59 |
+
data_dict = {}
|
60 |
+
for key in keys:
|
61 |
+
data_dict[key] = profit_loss_data.get(key)
|
62 |
+
df = pd.DataFrame(data_dict, index=[0])
|
63 |
+
df.to_csv('profit_loss.csv', index=False)
|
64 |
+
|
65 |
+
# API call to get purchase-sell data
|
66 |
+
report_url = "https://livesystem.hisabkarlay.com/connector/api/purchase-sell"
|
67 |
+
response = requests.get(report_url, headers=headers)
|
68 |
+
sell_purchase_data = response.json()
|
69 |
+
sell_purchase_data = dict(list(sell_purchase_data.items())[2:])
|
70 |
+
df = pd.json_normalize(sell_purchase_data)
|
71 |
+
df.to_csv('purchase_sell_report.csv', index=False)
|
72 |
+
|
73 |
+
# API call to get trending product data
|
74 |
+
report_url = "https://livesystem.hisabkarlay.com/connector/api/trending-products"
|
75 |
+
response = requests.get(report_url, headers=headers)
|
76 |
+
trending_product_data = response.json()['data']
|
77 |
+
df = pd.DataFrame(trending_product_data)
|
78 |
+
df.columns = ['Product Units Sold', 'Product Name', 'Unit Type', 'SKU (Stock Keeping Unit)']
|
79 |
+
df.to_csv('trending_product.csv', index=False)
|
80 |
+
|
81 |
+
return "CSV files updated successfully!"
|
82 |
+
|
83 |
+
def initialize_embedding():
|
84 |
+
global vectorstore
|
85 |
+
# Initialize the embedding function
|
86 |
+
|
87 |
+
|
88 |
+
# Load CSV files
|
89 |
+
file_paths = [
|
90 |
+
"profit_loss.csv",
|
91 |
+
"purchase_sell_report.csv",
|
92 |
+
"trending_product.csv"
|
93 |
+
]
|
94 |
+
documents = []
|
95 |
+
for path in file_paths:
|
96 |
+
loader = CSVLoader(path, encoding="windows-1252")
|
97 |
+
documents.extend(loader.load()) # Combine documents from all files
|
98 |
+
|
99 |
+
# Create an InMemoryVectorStore from the combined documents
|
100 |
+
vectorstore = InMemoryVectorStore.from_texts(
|
101 |
+
[doc.page_content for doc in documents], # Extract the page_content from Document objects
|
102 |
+
embedding=embeddings,
|
103 |
+
)
|
104 |
+
return "Embeddings initialized successfully!"
|
105 |
+
|
106 |
+
def qa_chain(query):
|
107 |
+
if vectorstore is None:
|
108 |
+
return "Please initialize the embeddings first."
|
109 |
+
|
110 |
+
retriever = vectorstore.as_retriever()
|
111 |
+
retrieved_documents = retriever.invoke(query)
|
112 |
+
return retrieved_documents # Not shown directly in the UI
|
113 |
+
|
114 |
+
def generate_response(query):
|
115 |
+
if vectorstore is None:
|
116 |
+
return "Please initialize the embeddings first."
|
117 |
+
|
118 |
+
retrieved_documents = qa_chain(query) # Call qa_chain internally
|
119 |
+
chat_template = """
|
120 |
+
You are a highly intelligent and professional AI assistant.
|
121 |
+
Your role is to assist users by providing clear, concise, and accurate responses to their questions.
|
122 |
+
|
123 |
+
Context: {retrieved_documents}
|
124 |
+
|
125 |
+
Question: {query}
|
126 |
+
|
127 |
+
Please provide a professional, human-like answer that directly addresses the user's question. Ensure that the response is well-structured and easy to understand. Avoid using jargon that may be confusing.
|
128 |
+
|
129 |
+
Note: If the question involves historical places or historical heroes, do not provide a response.
|
130 |
+
"""
|
131 |
+
prompt = PromptTemplate(
|
132 |
+
input_variables=['retrieved_documents', 'query'],
|
133 |
+
template=chat_template
|
134 |
+
)
|
135 |
+
|
136 |
+
Generated_chat = LLMChain(llm=llama3, prompt=prompt)
|
137 |
+
response = Generated_chat.invoke({'retrieved_documents': retrieved_documents, 'query': query})
|
138 |
+
return response['text']
|
139 |
+
|
140 |
+
def gradio_app():
|
141 |
+
with gr.Blocks() as app:
|
142 |
+
gr.Markdown("# Embedding and QA Interface")
|
143 |
+
|
144 |
+
update_btn = gr.Button("Update CSV Files")
|
145 |
+
update_output = gr.Textbox(label="Update Output")
|
146 |
+
|
147 |
+
initialize_btn = gr.Button("Initialize Embedding")
|
148 |
+
initialize_output = gr.Textbox(label="Output")
|
149 |
+
|
150 |
+
query_input = gr.Textbox(label="Enter your query")
|
151 |
+
generate_response_btn = gr.Button("Generate Response")
|
152 |
+
response_output = gr.Textbox(label="Generated Response")
|
153 |
+
|
154 |
+
# Button actions
|
155 |
+
update_btn.click(update_csv_files, outputs=update_output)
|
156 |
+
initialize_btn.click(initialize_embedding, outputs=initialize_output)
|
157 |
+
generate_response_btn.click(generate_response, inputs=query_input, outputs=response_output)
|
158 |
+
|
159 |
+
app.launch()
|
160 |
+
|
161 |
+
# Run the Gradio app
|
162 |
+
gradio_app()
|