DrishtiSharma commited on
Commit
85c7288
Β·
verified Β·
1 Parent(s): a2a85d1

Create fixed_font_issue.py

Browse files
Files changed (1) hide show
  1. mylab/fixed_font_issue.py +358 -0
mylab/fixed_font_issue.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import sqlite3
4
+ import tempfile
5
+ from fpdf import FPDF
6
+ import os
7
+ import re
8
+ import json
9
+ from pathlib import Path
10
+ import plotly.express as px
11
+ from datetime import datetime, timezone
12
+ from crewai import Agent, Crew, Process, Task
13
+ from crewai.tools import tool
14
+ from langchain_groq import ChatGroq
15
+ from langchain_openai import ChatOpenAI
16
+ from langchain.schema.output import LLMResult
17
+ from langchain_community.tools.sql_database.tool import (
18
+ InfoSQLDatabaseTool,
19
+ ListSQLDatabaseTool,
20
+ QuerySQLCheckerTool,
21
+ QuerySQLDataBaseTool,
22
+ )
23
+ from langchain_community.utilities.sql_database import SQLDatabase
24
+ from datasets import load_dataset
25
+ import tempfile
26
+
27
+ st.title("SQL-RAG Using CrewAI πŸš€")
28
+ st.write("Analyze datasets using natural language queries powered by SQL and CrewAI.")
29
+
30
+ # Initialize LLM
31
+ llm = None
32
+
33
+ # Model Selection
34
+ model_choice = st.radio("Select LLM", ["GPT-4o", "llama-3.3-70b"], index=0, horizontal=True)
35
+
36
+ # API Key Validation and LLM Initialization
37
+ groq_api_key = os.getenv("GROQ_API_KEY")
38
+ openai_api_key = os.getenv("OPENAI_API_KEY")
39
+
40
+ if model_choice == "llama-3.3-70b":
41
+ if not groq_api_key:
42
+ st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
43
+ llm = None
44
+ else:
45
+ llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
46
+ elif model_choice == "GPT-4o":
47
+ if not openai_api_key:
48
+ st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
49
+ llm = None
50
+ else:
51
+ llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
52
+
53
+ # Initialize session state for data persistence
54
+ if "df" not in st.session_state:
55
+ st.session_state.df = None
56
+ if "show_preview" not in st.session_state:
57
+ st.session_state.show_preview = False
58
+
59
+ # Dataset Input
60
+ input_option = st.radio("Select Dataset Input:", ["Use Hugging Face Dataset", "Upload CSV File"])
61
+
62
+ if input_option == "Use Hugging Face Dataset":
63
+ dataset_name = st.text_input("Enter Hugging Face Dataset Name:", value="Einstellung/demo-salaries")
64
+ if st.button("Load Dataset"):
65
+ try:
66
+ with st.spinner("Loading dataset..."):
67
+ dataset = load_dataset(dataset_name, split="train")
68
+ st.session_state.df = pd.DataFrame(dataset)
69
+ st.session_state.show_preview = True # Show preview after loading
70
+ st.success(f"Dataset '{dataset_name}' loaded successfully!")
71
+ except Exception as e:
72
+ st.error(f"Error: {e}")
73
+
74
+ elif input_option == "Upload CSV File":
75
+ uploaded_file = st.file_uploader("Upload CSV File:", type=["csv"])
76
+ if uploaded_file:
77
+ try:
78
+ st.session_state.df = pd.read_csv(uploaded_file)
79
+ st.session_state.show_preview = True # Show preview after loading
80
+ st.success("File uploaded successfully!")
81
+ except Exception as e:
82
+ st.error(f"Error loading file: {e}")
83
+
84
+ # Show Dataset Preview Only After Loading
85
+ if st.session_state.df is not None and st.session_state.show_preview:
86
+ st.subheader("πŸ“‚ Dataset Preview")
87
+ st.dataframe(st.session_state.df.head())
88
+
89
+ # Function to create TXT file
90
+ def create_text_report_with_viz_temp(report, conclusion, visualizations):
91
+ content = f"### Analysis Report\n\n{report}\n\n### Visualizations\n"
92
+
93
+ for i, fig in enumerate(visualizations, start=1):
94
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
95
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
96
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
97
+
98
+ content += f"\n{i}. {fig_title}\n"
99
+ content += f" - X-axis: {x_axis}\n"
100
+ content += f" - Y-axis: {y_axis}\n"
101
+
102
+ if fig.data:
103
+ trace_types = set(trace.type for trace in fig.data)
104
+ content += f" - Chart Type(s): {', '.join(trace_types)}\n"
105
+ else:
106
+ content += " - No data available in this visualization.\n"
107
+
108
+ content += f"\n\n\n{conclusion}"
109
+
110
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode='w', encoding='utf-8') as temp_txt:
111
+ temp_txt.write(content)
112
+ return temp_txt.name
113
+
114
+
115
+ # Function to create PDF with report text and visualizations
116
+ def create_pdf_report_with_viz(report, conclusion, visualizations):
117
+ pdf = FPDF()
118
+ pdf.set_auto_page_break(auto=True, margin=15)
119
+ pdf.add_page()
120
+ pdf.set_font("Arial", size=12)
121
+
122
+ # Title
123
+ pdf.set_font("Arial", style="B", size=18)
124
+ pdf.cell(0, 10, "πŸ“Š Analysis Report", ln=True, align="C")
125
+ pdf.ln(10)
126
+
127
+ # Report Content
128
+ pdf.set_font("Arial", style="B", size=14)
129
+ pdf.cell(0, 10, "Analysis", ln=True)
130
+ pdf.set_font("Arial", size=12)
131
+ pdf.multi_cell(0, 10, report)
132
+
133
+ pdf.ln(10)
134
+ pdf.set_font("Arial", style="B", size=14)
135
+ pdf.cell(0, 10, "Conclusion", ln=True)
136
+ pdf.set_font("Arial", size=12)
137
+ pdf.multi_cell(0, 10, conclusion)
138
+
139
+ # Add Visualizations
140
+ pdf.add_page()
141
+ pdf.set_font("Arial", style="B", size=16)
142
+ pdf.cell(0, 10, "πŸ“ˆ Visualizations", ln=True)
143
+ pdf.ln(5)
144
+
145
+ with tempfile.TemporaryDirectory() as temp_dir:
146
+ for i, fig in enumerate(visualizations, start=1):
147
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
148
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
149
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
150
+
151
+ # Save each visualization as a PNG image
152
+ img_path = os.path.join(temp_dir, f"viz_{i}.png")
153
+ fig.write_image(img_path)
154
+
155
+ # Insert Title and Description
156
+ pdf.set_font("Arial", style="B", size=14)
157
+ pdf.multi_cell(0, 10, f"{i}. {fig_title}")
158
+ pdf.set_font("Arial", size=12)
159
+ pdf.multi_cell(0, 10, f"X-axis: {x_axis} | Y-axis: {y_axis}")
160
+ pdf.ln(3)
161
+
162
+ # Embed Visualization
163
+ pdf.image(img_path, w=170)
164
+ pdf.ln(10)
165
+
166
+ # Save PDF
167
+ temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
168
+ pdf.output(temp_pdf.name)
169
+
170
+ return temp_pdf
171
+
172
+ def escape_markdown(text):
173
+ # Ensure text is a string
174
+ text = str(text)
175
+ # Escape Markdown characters: *, _, `, ~
176
+ escape_chars = r"(\*|_|`|~)"
177
+ return re.sub(escape_chars, r"\\\1", text)
178
+
179
+ # SQL-RAG Analysis
180
+ if st.session_state.df is not None:
181
+ temp_dir = tempfile.TemporaryDirectory()
182
+ db_path = os.path.join(temp_dir.name, "data.db")
183
+ connection = sqlite3.connect(db_path)
184
+ st.session_state.df.to_sql("salaries", connection, if_exists="replace", index=False)
185
+ db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
186
+
187
+ @tool("list_tables")
188
+ def list_tables() -> str:
189
+ """List all tables in the database."""
190
+ return ListSQLDatabaseTool(db=db).invoke("")
191
+
192
+ @tool("tables_schema")
193
+ def tables_schema(tables: str) -> str:
194
+ """Get the schema and sample rows for the specified tables."""
195
+ return InfoSQLDatabaseTool(db=db).invoke(tables)
196
+
197
+ @tool("execute_sql")
198
+ def execute_sql(sql_query: str) -> str:
199
+ """Execute a SQL query against the database and return the results."""
200
+ return QuerySQLDataBaseTool(db=db).invoke(sql_query)
201
+
202
+ @tool("check_sql")
203
+ def check_sql(sql_query: str) -> str:
204
+ """Validate the SQL query syntax and structure before execution."""
205
+ return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
206
+
207
+ # Agents for SQL data extraction and analysis
208
+ sql_dev = Agent(
209
+ role="Senior Database Developer",
210
+ goal="Extract data using optimized SQL queries.",
211
+ backstory="An expert in writing optimized SQL queries for complex databases.",
212
+ llm=llm,
213
+ tools=[list_tables, tables_schema, execute_sql, check_sql],
214
+ )
215
+
216
+ data_analyst = Agent(
217
+ role="Senior Data Analyst",
218
+ goal="Analyze the data and produce insights.",
219
+ backstory="A seasoned analyst who identifies trends and patterns in datasets.",
220
+ llm=llm,
221
+ )
222
+
223
+ report_writer = Agent(
224
+ role="Technical Report Writer",
225
+ goal="Write a structured report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
226
+ backstory="Specializes in detailed analytical reports without conclusions.",
227
+ llm=llm,
228
+ )
229
+
230
+ conclusion_writer = Agent(
231
+ role="Conclusion Specialist",
232
+ goal="Summarize findings into a clear and concise 3-5 line Conclusion highlighting only the most important insights.",
233
+ backstory="An expert in crafting impactful and clear conclusions.",
234
+ llm=llm,
235
+ )
236
+
237
+ # Define tasks for report and conclusion
238
+ extract_data = Task(
239
+ description="Extract data based on the query: {query}.",
240
+ expected_output="Database results matching the query.",
241
+ agent=sql_dev,
242
+ )
243
+
244
+ analyze_data = Task(
245
+ description="Analyze the extracted data for query: {query}.",
246
+ expected_output="Key Insights and Analysis without any Introduction or Conclusion.",
247
+ agent=data_analyst,
248
+ context=[extract_data],
249
+ )
250
+
251
+ write_report = Task(
252
+ description="Write the analysis report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
253
+ expected_output="Markdown-formatted report excluding Conclusion.",
254
+ agent=report_writer,
255
+ context=[analyze_data],
256
+ )
257
+
258
+ write_conclusion = Task(
259
+ description="Summarize the key findings in 3-5 impactful lines, highlighting the maximum, minimum, and average salaries."
260
+ "Emphasize significant insights on salary distribution and influential compensation trends for strategic decision-making.",
261
+ expected_output="Markdown-formatted Conclusion section with key insights and statistics.",
262
+ agent=conclusion_writer,
263
+ context=[analyze_data],
264
+ )
265
+
266
+
267
+
268
+ # Separate Crews for report and conclusion
269
+ crew_report = Crew(
270
+ agents=[sql_dev, data_analyst, report_writer],
271
+ tasks=[extract_data, analyze_data, write_report],
272
+ process=Process.sequential,
273
+ verbose=True,
274
+ )
275
+
276
+ crew_conclusion = Crew(
277
+ agents=[data_analyst, conclusion_writer],
278
+ tasks=[write_conclusion],
279
+ process=Process.sequential,
280
+ verbose=True,
281
+ )
282
+
283
+ # Tabs for Query Results and Visualizations
284
+ tab1, tab2 = st.tabs(["πŸ” Query Insights + Viz", "πŸ“Š Full Data Viz"])
285
+
286
+ # Query Insights + Visualization
287
+ with tab1:
288
+ query = st.text_area("Enter Query:", value="Provide insights into the salary of a Principal Data Scientist.")
289
+ if st.button("Submit Query"):
290
+ with st.spinner("Processing query..."):
291
+ # Step 1: Generate the analysis report
292
+ report_inputs = {"query": query + " Provide detailed analysis but DO NOT include Conclusion."}
293
+ report_result = crew_report.kickoff(inputs=report_inputs)
294
+
295
+ # Step 2: Generate only the concise conclusion
296
+ conclusion_inputs = {"query": query + " Provide ONLY the most important insights in 3-5 concise lines."}
297
+ conclusion_result = crew_conclusion.kickoff(inputs=conclusion_inputs)
298
+
299
+ # Step 3: Display the report
300
+ #st.markdown("### Analysis Report:")
301
+ st.markdown(report_result if report_result else "⚠️ No Report Generated.")
302
+
303
+ # Step 4: Generate Visualizations
304
+ visualizations = []
305
+
306
+ fig_salary = px.box(st.session_state.df, x="job_title", y="salary_in_usd",
307
+ title="Salary Distribution by Job Title")
308
+ visualizations.append(fig_salary)
309
+
310
+ fig_experience = px.bar(
311
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
312
+ x="experience_level", y="salary_in_usd",
313
+ title="Average Salary by Experience Level"
314
+ )
315
+ visualizations.append(fig_experience)
316
+
317
+ fig_employment = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
318
+ title="Salary Distribution by Employment Type")
319
+ visualizations.append(fig_employment)
320
+
321
+ # Step 5: Insert Visual Insights
322
+ st.markdown("### Visual Insights")
323
+ for fig in visualizations:
324
+ st.plotly_chart(fig, use_container_width=True)
325
+
326
+ # Step 6: Display Concise Conclusion
327
+ #st.markdown("#### Conclusion")
328
+
329
+ safe_conclusion = escape_markdown(conclusion_result if conclusion_result else "⚠️ No Conclusion Generated.")
330
+ st.markdown(safe_conclusion)
331
+
332
+ # Full Data Visualization Tab
333
+ with tab2:
334
+ st.subheader("πŸ“Š Comprehensive Data Visualizations")
335
+
336
+ fig1 = px.histogram(st.session_state.df, x="job_title", title="Job Title Frequency")
337
+ st.plotly_chart(fig1)
338
+
339
+ fig2 = px.bar(
340
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
341
+ x="experience_level", y="salary_in_usd",
342
+ title="Average Salary by Experience Level"
343
+ )
344
+ st.plotly_chart(fig2)
345
+
346
+ fig3 = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
347
+ title="Salary Distribution by Employment Type")
348
+ st.plotly_chart(fig3)
349
+
350
+ temp_dir.cleanup()
351
+ else:
352
+ st.info("Please load a dataset to proceed.")
353
+
354
+
355
+ # Sidebar Reference
356
+ with st.sidebar:
357
+ st.header("πŸ“š Reference:")
358
+ st.markdown("[SQL Agents w CrewAI & Llama 3 - Plaban Nayak](https://github.com/plaban1981/Agents/blob/main/SQL_Agents_with_CrewAI_and_Llama_3.ipynb)")