import gradio as gr import pandas as pd import os import warnings import torch warnings.filterwarnings("ignore") from langchain_community.document_loaders import CSVLoader from langchain_community.vectorstores import Chroma from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.embeddings import HuggingFaceEmbeddings from langchain.chains import RetrievalQA from langchain.prompts import PromptTemplate from langchain_community.llms import HuggingFacePipeline from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline # Set up environment os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.environ.get("HUGGINGFACEHUB_API_TOKEN", "") # Load Falcon LLM for Tax Optimization model_id = "tiiuae/Falcon3-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float32, device_map="cpu", low_cpu_mem_usage=True, trust_remote_code=True ) pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=800, do_sample=True, temperature=0.3, top_k=50, top_p=0.95, eos_token_id=tokenizer.eos_token_id, return_full_text=False ) llm = HuggingFacePipeline(pipeline=pipe) # Tax Optimization Prompt Template template = """ You are a US Tax Optimization Expert. Analyze the provided financial data and create personalized tax-saving recommendations. User Financial Data: {context} Query: {question} Provide specific tax optimization recommendations including: 1. Available deductions based on current contributions 2. Investment strategies to reduce taxable income 3. Specific dollar amounts for optimal contributions 4. Filing status optimization 5. State tax considerations Focus on actionable, specific recommendations using US tax code. """ PROMPT = PromptTemplate(input_variables=["context", "question"], template=template) def create_tax_report_html(user_data, recommendations, tax_savings): """Create a formatted HTML tax optimization report""" # Extract user information income = user_data.get('income', 0) filing_status = user_data.get('filing_status', 'Single') state = user_data.get('state', 'N/A') current_deductions = user_data.get('total_deductions', 0) estimated_tax = user_data.get('estimated_tax', 0) # Calculate potential savings potential_savings = tax_savings if tax_savings > 0 else 0 savings_percentage = (potential_savings / estimated_tax * 100) if estimated_tax > 0 else 0 html = f"""

💰 Tax Optimization Report

Personalized Tax-Saving Recommendations

📅 Generated on {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}
Annual Income
${income:,.2f}
Estimated Tax
${estimated_tax:,.2f}
Potential Savings 💚
${potential_savings:,.2f} ({savings_percentage:.1f}%)
Filing Status
{filing_status}

📊 Current Deductions Summary

Health Insurance ${user_data.get('health_insurance', 0):,.2f}
Retirement Contributions ${user_data.get('retirement_contrib', 0):,.2f}
Home Loan Interest ${user_data.get('home_loan', 0):,.2f}
Total Deductions ${current_deductions:,.2f}
State {state}

🤖 AI Tax Optimization Recommendations

{recommendations}

⚠️ This report is for informational purposes only. Consult a tax professional for personalized advice.

""" return html def calculate_tax_brackets(taxable_income): """Calculate federal income tax using 2024 tax brackets""" if taxable_income <= 0: return 0 # 2024 tax brackets for single filers brackets = [ (11000, 0.10), (44725, 0.12), (95375, 0.22), (182050, 0.24), (231250, 0.32), (578125, 0.35), (float('inf'), 0.37) ] tax = 0 prev_bracket = 0 for bracket_limit, rate in brackets: if taxable_income > prev_bracket: taxable_in_bracket = min(taxable_income, bracket_limit) - prev_bracket tax += taxable_in_bracket * rate prev_bracket = bracket_limit if taxable_income <= bracket_limit: break return tax def generate_tax_recommendations(income, filing_status, health_insurance, home_loan, retirement_contrib, state): """Generate tax optimization recommendations""" if not income or income <= 0: return "
❌ Please enter a valid income amount greater than $0.
" try: # Input validation income = float(income) if income else 0 health_insurance = float(health_insurance) if health_insurance else 0 home_loan = float(home_loan) if home_loan else 0 retirement_contrib = float(retirement_contrib) if retirement_contrib else 0 # Calculate current tax situation total_deductions = health_insurance + home_loan + retirement_contrib # Standard deduction for 2024 standard_deduction_amounts = { 'Single': 13850, 'Married': 27700, 'Head of Household': 20800 } standard_deduction = standard_deduction_amounts.get(filing_status, 13850) # Calculate taxable income taxable_income = max(income - total_deductions - standard_deduction, 0) # Calculate estimated tax using progressive brackets estimated_tax = calculate_tax_brackets(taxable_income) # Create user data dictionary user_data = { 'income': income, 'filing_status': filing_status, 'health_insurance': health_insurance, 'home_loan': home_loan, 'retirement_contrib': retirement_contrib, 'state': state or 'N/A', 'total_deductions': total_deductions, 'estimated_tax': estimated_tax, 'taxable_income': taxable_income, 'standard_deduction': standard_deduction } # Create a temporary dataset for RAG temp_data = pd.DataFrame([user_data]) temp_data.to_csv("temp_tax_data.csv", index=False) # Set up RAG system try: loader = CSVLoader("temp_tax_data.csv") documents = loader.load() splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50) texts = splitter.split_documents(documents) embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") chroma = Chroma.from_documents( documents=texts, collection_name="tax_data", embedding=embeddings, persist_directory="docs/tax_chroma" ) retriever = chroma.as_retriever(search_kwargs={"k": 3}) qa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", chain_type_kwargs={"prompt": PROMPT}, retriever=retriever, return_source_documents=False ) # Generate personalized query query = f"""Analyze tax optimization for: - Income: ${income:,.2f} - Filing Status: {filing_status} - Current deductions: ${total_deductions:,.2f} - Estimated tax: ${estimated_tax:,.2f} - State: {state or 'Not specified'} Provide specific recommendations to reduce tax liability.""" result = qa({"query": query}) recommendations = result.get("result", "Unable to generate recommendations at this time.") except Exception as e: recommendations = f""" **Tax Optimization Recommendations:** Based on your financial profile: • **Income**: ${income:,.2f} • **Filing Status**: {filing_status} • **Current Deductions**: ${total_deductions:,.2f} • **Estimated Tax**: ${estimated_tax:,.2f} **Key Recommendations:** 1. **Maximize Retirement Contributions** - Consider increasing 401(k) contributions to the 2024 limit of $23,000 - If over 50, catch-up contributions allow an additional $7,500 - Current contribution: ${retirement_contrib:,.2f} 2. **Health Savings Account (HSA)** - If eligible, contribute up to $4,150 for individual/$8,300 for family - Triple tax advantage: deductible, tax-free growth, tax-free withdrawals 3. **Tax-Loss Harvesting** - Review investment portfolio for opportunities to realize losses - Can offset up to $3,000 of ordinary income annually 4. **State Tax Considerations** - State: {state or 'Not specified'} - Consider state-specific deductions and credits available 5. **Filing Status Optimization** - Current status: {filing_status} - Verify this provides the best tax advantage for your situation *Note: AI recommendations unavailable due to processing limitations. These are general guidelines.* """ # Calculate potential savings (conservative estimate) # Assume user can optimize an additional $3,000-$5,000 in deductions additional_deductions = min(5000, income * 0.05) # Conservative 5% of income or $5k max marginal_tax_rate = 0.22 if taxable_income > 44725 else 0.12 # Simplified marginal rate potential_tax_savings = additional_deductions * marginal_tax_rate return create_tax_report_html(user_data, recommendations, potential_tax_savings) except Exception as e: return f"""

❌ Error Generating Report

Details: {str(e)}

Please check your inputs and try again.

""" # Custom CSS for styling custom_css = """ #component-0 { max-width: 1200px !important; margin: 0 auto !important; } .gradio-container { background: black !important; min-height: 100vh !important; } #title { text-align: center !important; color: white !important; font-size: 2.5rem !important; font-weight: 700 !important; margin-bottom: 1rem !important; text-shadow: 0 2px 4px rgba(0,0,0,0.3) !important; } #description { text-align: center !important; color: white !important; font-size: 1.1rem !important; margin-bottom: 2rem !important; opacity: 0.9 !important; } .input-container { background: rgba(255,255,255,0.95) !important; border-radius: 5px !important; padding: 5px !important; box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important; margin-bottom: 20px !important; backdrop-filter: blur(10px) !important; } .output-container { background: transparent !important; border-radius: 15px !important; overflow: hidden !important; box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important; } .gradio-button { background: linear-gradient(135deg, #16a085 0%, #2980b9 100%) !important; border: none !important; border-radius: 8px !important; padding: 12px 24px !important; font-weight: 600 !important; transition: all 0.3s ease !important; } .gradio-button:hover { transform: translateY(-2px) !important; box-shadow: 0 5px 15px rgba(0,0,0,0.3) !important; } """ # Create the Gradio interface with gr.Blocks(css=custom_css, title="💰 Tax Optimization Assistant", theme=gr.themes.Soft()) as iface: gr.HTML('
💰 AI-Powered Tax Optimization Assistant
') gr.HTML('
Enter your financial information to get personalized tax-saving recommendations powered by AI
') # Sidebar for inputs with gr.Sidebar(elem_classes=["input-container"]): gr.Markdown("## 📥 Your Financial Information") income_input = gr.Number( label="💵 Annual Gross Income ($)", placeholder="e.g., 75000", info="Enter your total gross annual income", minimum=0, value=0 ) filing_status_input = gr.Radio( choices=["Single", "Married", "Head of Household"], label="👤 Filing Status", value="Single", info="Select your tax filing status" ) health_insurance_input = gr.Number( label="🏥 Health Insurance Premiums ($)", value=0, minimum=0, info="Annual health insurance premiums you pay" ) home_loan_input = gr.Number( label="🏠 Home Loan Interest ($)", value=0, minimum=0, info="Annual mortgage interest payments" ) retirement_input = gr.Number( label="💼 Retirement Contributions ($)", value=0, minimum=0, info="401(k), IRA, and other retirement plan contributions" ) state_input = gr.Textbox( label="📍 State of Residence", placeholder="e.g., CA, NY, TX, FL", info="Enter your state abbreviation (optional)", max_lines=1 ) with gr.Row(): generate_btn = gr.Button("🚀 Generate Tax Report", variant="primary", scale=2) clear_btn = gr.Button("🔄 Clear All", variant="secondary", scale=1) # Output section with gr.Column(elem_classes=["output-container"]): output = gr.HTML( label="💰 Your Tax Optimization Report", value="
📋 Your personalized tax optimization report will appear here after you click 'Generate Tax Report'
" ) # Example section with gr.Accordion("📚 Example Usage", open=False): gr.Markdown(""" ### How to Use This Tool: 1. **Enter Your Income**: Input your gross annual salary 2. **Select Filing Status**: Choose Single, Married, or Head of Household 3. **Add Deductions**: Include current health insurance, mortgage interest, and retirement contributions 4. **Specify State**: Enter your state for state-specific recommendations 5. **Generate Report**: Click the button to get AI-powered recommendations ### Sample Input: - Annual Income: $75,000 - Filing Status: Single - Health Insurance: $2,400 - Home Loan Interest: $8,000 - Retirement Contributions: $6,000 - State: CA **The AI will analyze your situation and provide specific, actionable tax-saving strategies!** """) # Event handlers generate_btn.click( fn=generate_tax_recommendations, inputs=[income_input, filing_status_input, health_insurance_input, home_loan_input, retirement_input, state_input], outputs=output, show_progress=True ) clear_btn.click( fn=lambda: [0, "Single", 0, 0, 0, "", "
📋 Your personalized tax optimization report will appear here after you click 'Generate Tax Report'
"], outputs=[income_input, filing_status_input, health_insurance_input, home_loan_input, retirement_input, state_input, output] ) # Allow Enter key submission income_input.submit( fn=generate_tax_recommendations, inputs=[income_input, filing_status_input, health_insurance_input, home_loan_input, retirement_input, state_input], outputs=output ) # Launch the app if __name__ == "__main__": iface.launch( share=True, show_error=True )