Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -152,134 +152,12 @@ def calculations():
|
|
152 |
st.success(f"Total (A): {total_A:.2f}")
|
153 |
st.success(f"Creditors (After Margin): {total_B:.2f}")
|
154 |
st.success(f"Drawing Power (DP): {dp:.2f}")
|
155 |
-
|
156 |
-
def run_model1_chat():
|
157 |
-
st.header("Model 1 Chat Interface")
|
158 |
-
if 'chat_history' not in st.session_state:
|
159 |
-
st.session_state['chat_history'] = []
|
160 |
-
user_input = st.text_input("You:", key="model1_input")
|
161 |
-
if st.button("Send", key='model1_send'):
|
162 |
-
if user_input:
|
163 |
-
st.session_state.chat_history.append(("User", user_input))
|
164 |
-
try:
|
165 |
-
chat_completion = client.chat.completions.create(
|
166 |
-
messages=[
|
167 |
-
{'role': 'user', 'content': user_input}
|
168 |
-
],
|
169 |
-
model="gemma2-9b-it",
|
170 |
-
stream=False,
|
171 |
-
temperature=0.0
|
172 |
-
)
|
173 |
-
response = chat_completion.choices[0].message.content.strip()
|
174 |
-
st.session_state.chat_history.append(("Model", response))
|
175 |
-
except Exception as e:
|
176 |
-
st.error(f"An error occurred: {e}")
|
177 |
-
st.error("Please check your API key and model availability.")
|
178 |
-
for speaker, message in st.session_state.chat_history:
|
179 |
-
if speaker == "User":
|
180 |
-
st.markdown(f"**You:** {message}")
|
181 |
-
else:
|
182 |
-
st.markdown(f"**Model 1:** {message}")
|
183 |
-
|
184 |
-
|
185 |
-
def retrieve_relevant_financial_statements(query, index, statements, model, top_k=10, max_tokens=1500):
|
186 |
-
query_embedding = model.encode([query], convert_to_numpy=True)
|
187 |
-
distances, indices = index.search(query_embedding.astype('float32'), top_k)
|
188 |
-
retrieved_statements = []
|
189 |
-
total_tokens = 0
|
190 |
-
for idx in indices[0]:
|
191 |
-
statement = statements[idx]['statement']
|
192 |
-
token_count = len(statement.split())
|
193 |
-
if total_tokens + token_count > max_tokens:
|
194 |
-
break
|
195 |
-
retrieved_statements.append(statements[idx])
|
196 |
-
total_tokens += token_count
|
197 |
-
return retrieved_statements
|
198 |
-
|
199 |
-
|
200 |
-
def model2_financial_data():
|
201 |
-
st.header("Financial Data Assistant (Model 2)")
|
202 |
-
financial_index_path = os.path.join( 'financial_index.faiss')
|
203 |
-
financial_statements_path = os.path.join( 'financial_statements.pkl')
|
204 |
-
if not os.path.exists(financial_index_path):
|
205 |
-
st.error("Financial FAISS index not found.")
|
206 |
-
st.stop()
|
207 |
-
financial_index = faiss.read_index(financial_index_path)
|
208 |
-
if not os.path.exists(financial_statements_path):
|
209 |
-
st.error("Financial statements data not found.")
|
210 |
-
st.stop()
|
211 |
-
with open(financial_statements_path, 'rb') as f:
|
212 |
-
financial_statements = pickle.load(f)
|
213 |
-
user_query = st.text_area("Ask a question about Indian state-wise financial details (1980-2015):", key='model2_input')
|
214 |
-
|
215 |
-
if st.button("Get Answer", key='model2_button'):
|
216 |
-
if user_query:
|
217 |
-
import re
|
218 |
-
metrics_list = [
|
219 |
-
'aggregate expenditure', 'capital expenditure', 'gross fiscal deficits',
|
220 |
-
'nominal gsdp series', 'own tax revenues', 'revenue deficits',
|
221 |
-
'revenue expenditure', 'social sector expenditure'
|
222 |
-
]
|
223 |
-
metrics_pattern = '|'.join(metrics_list)
|
224 |
-
metric_regex = re.compile(rf'\b({metrics_pattern})\b', re.IGNORECASE)
|
225 |
-
metric_match = metric_regex.search(user_query)
|
226 |
-
if metric_match:
|
227 |
-
query_metric = metric_match.group(1).strip().title()
|
228 |
-
else:
|
229 |
-
query_metric = None
|
230 |
-
states_list = list(set(s['state'] for s in financial_statements))
|
231 |
-
states_pattern = '|'.join(states_list)
|
232 |
-
state_regex = re.compile(rf'\b({states_pattern})\b', re.IGNORECASE)
|
233 |
-
state_match = state_regex.search(user_query)
|
234 |
-
if state_match:
|
235 |
-
query_state = state_match.group(1).strip()
|
236 |
-
else:
|
237 |
-
query_state = None
|
238 |
-
year_regex = re.compile(r'(\d{4}(?:-\d{2})?)')
|
239 |
-
year_match = year_regex.search(user_query)
|
240 |
-
if year_match:
|
241 |
-
query_year = year_match.group(1)
|
242 |
-
if len(query_year) == 4:
|
243 |
-
query_year = f"{query_year}-{str(int(query_year[-2:])+1).zfill(2)}"
|
244 |
-
elif len(query_year) == 7:
|
245 |
-
pass
|
246 |
-
else:
|
247 |
-
query_year = None
|
248 |
-
if query_state and query_year:
|
249 |
-
data = {}
|
250 |
-
for s in financial_statements:
|
251 |
-
if (
|
252 |
-
s['state'].lower() == query_state.lower() and
|
253 |
-
s['year'] == query_year
|
254 |
-
):
|
255 |
-
if query_metric:
|
256 |
-
if s['metric_type'].lower() == query_metric.lower():
|
257 |
-
data[s['metric_type']] = s['value']
|
258 |
-
break
|
259 |
-
else:
|
260 |
-
data[s['metric_type']] = s['value']
|
261 |
-
if data:
|
262 |
-
if query_metric:
|
263 |
-
value = data.get(query_metric)
|
264 |
-
if value is not None:
|
265 |
-
st.write(f"The {query_metric} of {query_state} in {query_year} is {value}")
|
266 |
-
else:
|
267 |
-
st.write(f"{query_metric} data not found for {query_state} in {query_year}.")
|
268 |
-
else:
|
269 |
-
st.write(f"Financial data for **{query_state}** in **{query_year}**:")
|
270 |
-
df = pd.DataFrame(list(data.items()), columns=['Metric', 'Value'])
|
271 |
-
st.table(df)
|
272 |
-
else:
|
273 |
-
st.write("Data not found for the specified state, year, or metric.")
|
274 |
-
else:
|
275 |
-
st.write("Could not understand the query. Please specify the state and year.")
|
276 |
-
|
277 |
def main():
|
278 |
st.set_page_config(page_title="Finance Assistant", page_icon="💸", layout="wide")
|
279 |
st.title("💸 Finance Assistant")
|
280 |
option = st.radio(
|
281 |
"Choose a Functionality",
|
282 |
-
("Calculation Methodology", "Circular Compliance", "Industry Classification"
|
283 |
)
|
284 |
if option == "Calculation Methodology":
|
285 |
calculations()
|
@@ -287,9 +165,5 @@ def main():
|
|
287 |
circular_compliance()
|
288 |
elif option == "Industry Classification":
|
289 |
industry_classification()
|
290 |
-
elif option == "Model 1":
|
291 |
-
run_model1_chat()
|
292 |
-
elif option == "Model 2":
|
293 |
-
model2_financial_data()
|
294 |
if __name__ == "__main__":
|
295 |
main()
|
|
|
152 |
st.success(f"Total (A): {total_A:.2f}")
|
153 |
st.success(f"Creditors (After Margin): {total_B:.2f}")
|
154 |
st.success(f"Drawing Power (DP): {dp:.2f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
def main():
|
156 |
st.set_page_config(page_title="Finance Assistant", page_icon="💸", layout="wide")
|
157 |
st.title("💸 Finance Assistant")
|
158 |
option = st.radio(
|
159 |
"Choose a Functionality",
|
160 |
+
("Calculation Methodology", "Circular Compliance", "Industry Classification")
|
161 |
)
|
162 |
if option == "Calculation Methodology":
|
163 |
calculations()
|
|
|
165 |
circular_compliance()
|
166 |
elif option == "Industry Classification":
|
167 |
industry_classification()
|
|
|
|
|
|
|
|
|
168 |
if __name__ == "__main__":
|
169 |
main()
|