import subprocess
def analyze_with_ollama(immediate, mannequin=”mistral”):
“””Ship immediate to Ollama and get response”””
cmd = [
“ollama”, “run”, model,
f”{prompt}”
]
outcome = subprocess.run(cmd, capture_output=True, textual content=True)
return outcome.stdout
def load_and_summarize_data(file_path):
“””Load dataset and generate a abstract for LLM context”””
df = pd.read_csv(file_path) # or pd.read_excel() for Excel recordsdata
data_context = f”””
Columns: {‘, ‘.be a part of(df.columns)}
Pattern row: {dict(df.iloc[0])}
Numeric columns: {df.select_dtypes(embody=’quantity’).columns.tolist()}
“””
return df, data_context
def generate_pivot_code(data_context):
“””Ask LLM to generate pivot desk code”””
pivot_prompt = f”””Analyze this dataset and create pandas pivot desk code. Knowledge context: {data_context}
Return ONLY legitimate Python code with pd.pivot_table() that will be most insightful.
Enclose code in “`python“` blocks.”””
llm_response = analyze_with_ollama(pivot_prompt)
# Extract code from response
strive:
code_block = llm_response.break up(““`python”)[1].break up(““`”)[0]
besides IndexError:
code_block = llm_response # Fallback to full response if code block not discovered
return code_block
def execute_pivot_code(code_block, df):
“””Execute the generated pivot desk code safely”””
strive:
local_vars = {‘df’: df}
exec(code_block, globals(), local_vars)
pivot_df = local_vars.get(‘pivot_table’)
return pivot_df
besides Exception as e:
return f”Code execution failed: {str(e)}”
def analyze_pivot_table(pivot_df):
“””Ask LLM to investigate the pivot desk and supply insights”””
analysis_prompt = f”””Analyze this pivot desk:
{pivot_df.head().to_markdown()}
Present 3 key insights in bullet factors.”””
return analyze_with_ollama(analysis_prompt)
def auto_pivot_analysis(file_path):
“””Automate your entire pivot desk evaluation course of”””
print(“Loading dataset…”)
df, data_context = load_and_summarize_data(file_path)
print(“Producing pivot desk code utilizing LLM…”)
pivot_code = generate_pivot_code(data_context)
print(f”Generated code:n{pivot_code}”)
print(“Executing pivot desk code…”)
pivot_df = execute_pivot_code(pivot_code, df)
if isinstance(pivot_df, str): # Verify if execution failed
print(pivot_df)
return
print(“Analyzing pivot desk with LLM…”)
insights = analyze_pivot_table(pivot_df)
print(“nPivot Evaluation Outcomes:”)
print(insights)
if __name__ == “__main__”:
outcome = auto_pivot_analysis(“sales_data.csv”) # Exchange together with your file path