Spaces:
Sleeping
Sleeping
| 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""" | |
| <div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 900px; margin: 0 auto;"> | |
| <!-- Header Section --> | |
| <div style="background: linear-gradient(135deg, #16a085 0%, #2980b9 100%); color: white; padding: 25px; border-radius: 12px; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"> | |
| <h1 style="margin: 0 0 10px 0; font-size: 28px; font-weight: 600;">π° Tax Optimization Report</h1> | |
| <h2 style="margin: 0; font-size: 18px; font-weight: 400; opacity: 0.9;">Personalized Tax-Saving Recommendations</h2> | |
| <div style="margin-top: 15px; font-size: 14px; opacity: 0.8;"> | |
| π Generated on {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')} | |
| </div> | |
| </div> | |
| <!-- Key Metrics Grid --> | |
| <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px;"> | |
| <!-- Annual Income Card --> | |
| <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-left: 4px solid #3b82f6;"> | |
| <div style="color: #6b7280; font-size: 14px; margin-bottom: 5px;">Annual Income</div> | |
| <div style="font-size: 24px; font-weight: 700; color: #1f2937;">${income:,.2f}</div> | |
| </div> | |
| <!-- Current Tax Card --> | |
| <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-left: 4px solid #ef4444;"> | |
| <div style="color: #6b7280; font-size: 14px; margin-bottom: 5px;">Estimated Tax</div> | |
| <div style="font-size: 18px; font-weight: 600; color: #1f2937;">${estimated_tax:,.2f}</div> | |
| </div> | |
| <!-- Potential Savings Card --> | |
| <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-left: 4px solid #10b981;"> | |
| <div style="color: #6b7280; font-size: 14px; margin-bottom: 5px;">Potential Savings π</div> | |
| <div style="font-size: 18px; font-weight: 600; color: #10b981;"> | |
| ${potential_savings:,.2f} ({savings_percentage:.1f}%) | |
| </div> | |
| </div> | |
| <!-- Filing Status Card --> | |
| <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-left: 4px solid #f59e0b;"> | |
| <div style="color: #6b7280; font-size: 14px; margin-bottom: 5px;">Filing Status</div> | |
| <div style="font-size: 18px; font-weight: 600; color: #1f2937;">{filing_status}</div> | |
| </div> | |
| </div> | |
| <!-- Current Deductions Table --> | |
| <div style="background: white; border-radius: 10px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 25px;"> | |
| <h3 style="margin: 0 0 20px 0; color: #1f2937; font-size: 20px; font-weight: 600; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px;"> | |
| π Current Deductions Summary | |
| </h3> | |
| <table style="width: 100%; border-collapse: collapse;"> | |
| <tr style="border-bottom: 1px solid #e5e7eb;"> | |
| <td style="padding: 12px 0; font-weight: 600; color: #374151; width: 40%;">Health Insurance</td> | |
| <td style="padding: 12px 0; color: #6b7280;">${user_data.get('health_insurance', 0):,.2f}</td> | |
| </tr> | |
| <tr style="border-bottom: 1px solid #e5e7eb;"> | |
| <td style="padding: 12px 0; font-weight: 600; color: #374151;">Retirement Contributions</td> | |
| <td style="padding: 12px 0; color: #6b7280;">${user_data.get('retirement_contrib', 0):,.2f}</td> | |
| </tr> | |
| <tr style="border-bottom: 1px solid #e5e7eb;"> | |
| <td style="padding: 12px 0; font-weight: 600; color: #374151;">Home Loan Interest</td> | |
| <td style="padding: 12px 0; color: #6b7280;">${user_data.get('home_loan', 0):,.2f}</td> | |
| </tr> | |
| <tr style="border-bottom: 1px solid #e5e7eb;"> | |
| <td style="padding: 12px 0; font-weight: 600; color: #374151;">Total Deductions</td> | |
| <td style="padding: 12px 0; color: #6b7280; font-weight: 600;">${current_deductions:,.2f}</td> | |
| </tr> | |
| <tr> | |
| <td style="padding: 12px 0; font-weight: 600; color: #374151;">State</td> | |
| <td style="padding: 12px 0; color: #6b7280;">{state}</td> | |
| </tr> | |
| </table> | |
| </div> | |
| <!-- AI Recommendations Section --> | |
| <div style="background: white; border-radius: 10px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);"> | |
| <h3 style="margin: 0 0 20px 0; color: #1f2937; font-size: 20px; font-weight: 600; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px;"> | |
| π€ AI Tax Optimization Recommendations | |
| </h3> | |
| <div style="background: #f8fafc; border-radius: 8px; padding: 20px; border-left: 4px solid #16a085;"> | |
| <div style="white-space: pre-wrap; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; line-height: 1.6; color: #374151;">{recommendations}</div> | |
| </div> | |
| </div> | |
| <!-- Footer --> | |
| <div style="text-align: center; margin-top: 25px; padding: 20px; color: #6b7280; font-size: 14px; border-top: 1px solid #e5e7eb;"> | |
| <p style="margin: 0;">β οΈ This report is for informational purposes only. Consult a tax professional for personalized advice.</p> | |
| </div> | |
| </div> | |
| """ | |
| 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 "<div style='color: red; padding: 20px; text-align: center; font-family: Arial;'>β Please enter a valid income amount greater than $0.</div>" | |
| 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""" | |
| <div style='color: red; padding: 20px; font-family: Arial; background: #fee; border: 1px solid #fcc; border-radius: 8px; max-width: 600px; margin: 20px auto;'> | |
| <h3>β Error Generating Report</h3> | |
| <p><strong>Details:</strong> {str(e)}</p> | |
| <p>Please check your inputs and try again.</p> | |
| </div> | |
| """ | |
| # 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('<div id="title">π° AI-Powered Tax Optimization Assistant</div>') | |
| gr.HTML('<div id="description">Enter your financial information to get personalized tax-saving recommendations powered by AI</div>') | |
| # 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="<div style='text-align: center; padding: 40px; color: #fff; font-family: Arial;'>π Your personalized tax optimization report will appear here after you click 'Generate Tax Report'</div>" | |
| ) | |
| # 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, "", "<div style='text-align: center; padding: 40px; color: #fff; font-family: Arial;'>π Your personalized tax optimization report will appear here after you click 'Generate Tax Report'</div>"], | |
| 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 | |
| ) | |