### Clone Repository and Install Dependencies (Bash) Source: https://github.com/sachinbhute/businesssathi/blob/main/README.md Instructions for cloning the project repository and installing necessary Python dependencies using pip. Ensure Python 3.11+ is installed. ```bash git clone cd Buildathon pip install -r requirements.txt ``` -------------------------------- ### Configure Environment Variables (Env) Source: https://github.com/sachinbhute/businesssathi/blob/main/README.md Example environment variables for configuring AI providers like OpenAI and Google Gemini. These are optional; the app works with mock data if keys are not provided. ```env # OpenAI Configuration (optional) OPENAI_API_KEY=your_openai_api_key_here OPENAI_MODEL=gpt-4o-mini # Google Gemini Configuration (optional) GEMINI_API_KEY=your_gemini_api_key_here GEMINI_MODEL=gemini-1.5-flash # AI Provider Selection (optional) # Set to "openai", "gemini", or "auto" (default: auto selects best available) AI_PROVIDER=auto ``` -------------------------------- ### Load Sample Demo Data with Pandas Source: https://context7.com/sachinbhute/businesssathi/llms.txt Loads pre-built demo data scenarios into Pandas DataFrames for testing and demonstration purposes. It shows how to load different scenarios like 'Normal Week', 'Weekend Boost', 'Slow Week', and 'High Value Orders', and then prints the number of transactions for each. It also includes an example of computing KPIs from the loaded data. ```python from app.streamlit_app import load_sample_data # Load different demo scenarios normal_week_df = load_sample_data("Normal Week") print(f"Normal Week: {len(normal_week_df)} transactions") weekend_boost_df = load_sample_data("Weekend Boost") print(f"Weekend Boost: {len(weekend_boost_df)} transactions") slow_week_df = load_sample_data("Slow Week") print(f"Slow Week: {len(slow_week_df)} transactions") high_value_df = load_sample_data("High Value Orders") print(f"High Value Orders: {len(high_value_df)} transactions") # Output: # Normal Week: 200 transactions # Weekend Boost: 245 transactions # Slow Week: 41 transactions # High Value Orders: 95 transactions # Analyze loaded data kpis = compute_kpis(normal_week_df) print(f"Total Revenue: ₹{kpis['total_revenue']:,.2f}") print(f"Top Product: {kpis['top_product']}") ``` -------------------------------- ### Dockerfile for AI Business Saathi Source: https://context7.com/sachinbhute/businesssathi/llms.txt This Dockerfile outlines the steps to build a Docker image for the AI Business Saathi application. It includes installing dependencies, copying application files, generating sample data, exposing necessary ports, setting environment variables, and defining the command to run the application. ```dockerfile COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN python scripts/generate_sample_data.py EXPOSE 8501 ENV PYTHONUNBUFFERED=1 CMD ["streamlit", "run", "app/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"] ``` -------------------------------- ### Transcribe Audio with AI Client Source: https://context7.com/sachinbhute/businesssathi/llms.txt This snippet demonstrates how to transcribe audio using an AI client. It shows how to get the transcript and a boolean indicating if the real API was used. It also includes an example of handling potential transcription errors gracefully by using a mock transcript if the API is unavailable. ```python # Transcribe audio transcript, used_real_api = client.transcribe_audio(audio_bytes, filename='business_summary.wav') print(f"Transcript: {transcript}") print(f"Used real API: {used_real_api}") # Output: # Transcript: "Today we sold 50 packets of chips, 30 liters of milk, and revenue was around 5000 rupees..." # Used real API: True # Handle transcription errors gracefully try: transcript, success = client.transcribe_audio(audio_bytes) if not success: print("Using mock transcript due to API unavailability") except Exception as e: print(f"Transcription error: {e}") ``` -------------------------------- ### Launch Streamlit Application Source: https://context7.com/sachinbhute/businesssathi/llms.txt This snippet shows how to run the complete Streamlit application. It includes the necessary import statement and the standard Python entry point `if __name__ == '__main__':`. It also provides instructions for running the application via the command line and lists the application's key features. ```python # Save as app_launcher.py from app.streamlit_app import main import streamlit as st # Run the application if __name__ == "__main__": main() # Or use command line: # streamlit run app/streamlit_app.py --server.port 8501 # Application features: # - Sidebar data input (CSV upload, manual entry, sample data) # - Real-time KPI dashboard with metrics cards # - Interactive charts (top products bar chart, daily revenue line chart) # - Bilingual AI insights (English and Hindi) # - PDF report generation with embedded charts # - CSV data export # - Session state management for transactions and insights ``` -------------------------------- ### Docker Commands for AI Business Saathi Source: https://context7.com/sachinbhute/businesssathi/llms.txt These commands demonstrate how to build and run the AI Business Saathi Docker image. It includes options for building the image, running it with environment variables (API keys), and running it using a .env file. The application will be accessible at http://localhost:8501. ```bash # Build Docker image docker build -t ai-business-saathi . # Run with environment variables docker run -p 8501:8501 \ -e GEMINI_API_KEY=your_gemini_key_here \ -e OPENAI_API_KEY=your_openai_key_here \ ai-business-saathi # Run with .env file docker run -p 8501:8501 --env-file .env ai-business-saathi # Access application at http://localhost:8501 ``` -------------------------------- ### Docker Deployment Commands (Bash) Source: https://github.com/sachinbhute/businesssathi/blob/main/README.md Instructions for building the Docker image and running the AI Business Saathi application as a container. The application will be exposed on port 8501. ```bash # Build the Docker image docker build -t ai-business-saathi . # Run the container docker run -p 8501:8501 ai-business-saathi ``` -------------------------------- ### Run Streamlit Application (Bash) Source: https://github.com/sachinbhute/businesssathi/blob/main/README.md Commands to run the Streamlit application. It can be launched using a dedicated startup script or directly with the streamlit command. The application will be accessible at http://localhost:8501. ```bash # Option 1: Use the startup script (recommended) python run_app.py # Option 2: Run directly with Streamlit streamlit run app/streamlit_app.py ``` -------------------------------- ### Generate Sample Data (Python) Source: https://github.com/sachinbhute/businesssathi/blob/main/README.md A Python script to generate sample data for the retail analytics dashboard. This is useful for testing and demonstrations. ```python python scripts/generate_sample_data.py ``` -------------------------------- ### Configure Environment Variables for AI Source: https://context7.com/sachinbhute/businesssathi/llms.txt This section details how to set up environment variables for AI providers like OpenAI and Google Gemini. It shows how to create a `.env` file with API keys and model configurations, and then how to load these variables into a Python script using the `dotenv` library and access them using `os.getenv`. ```bash # Create .env file cat > .env << 'EOF' # OpenAI Configuration (optional) OPENAI_API_KEY=sk-your-openai-api-key-here OPENAI_MODEL=gpt-4o-mini # Google Gemini Configuration (optional) GEMINI_API_KEY=your-gemini-api-key-here GEMINI_MODEL=gemini-1.5-flash # AI Provider Selection (optional) # Options: "openai", "gemini", or "auto" (default: auto) AI_PROVIDER=auto EOF ``` ```python # Load environment in Python from dotenv import load_dotenv import os load_dotenv() # Access configuration openai_key = os.getenv('OPENAI_API_KEY') gemini_key = os.getenv('GEMINI_API_KEY') provider = os.getenv('AI_PROVIDER', 'auto') print(f"Provider: {provider}") print(f"OpenAI configured: {bool(openai_key)}") print(f"Gemini configured: {bool(gemini_key)}") ``` -------------------------------- ### Dockerfile for Application Deployment Source: https://context7.com/sachinbhute/businesssathi/llms.txt This Dockerfile sets up the environment for deploying the Python application. It specifies a Python 3.11 slim base image and sets the working directory to '/app'. This is a foundational step for containerizing the application and managing its dependencies. ```dockerfile # Dockerfile FROM python:3.11-slim WORKDIR /app ``` -------------------------------- ### Initialize Multi-Provider AI Client (Python) Source: https://context7.com/sachinbhute/businesssathi/llms.txt Initializes a unified AI client that supports multiple AI providers, including OpenAI and Google Gemini. It allows for automatic provider selection based on availability or explicit specification of the provider and model. Requires API keys to be set as environment variables. ```python from app.ai.client_factory import AIClient, AIProvider import os # Auto-select best available provider (prefers Gemini, falls back to OpenAI) client = AIClient(provider=AIProvider.AUTO) # Or explicitly specify provider openai_client = AIClient( provider=AIProvider.OPENAI, api_key=os.getenv('OPENAI_API_KEY'), model='gpt-4o-mini' ) gemini_client = AIClient( provider=AIProvider.GEMINI, api_key=os.getenv('GEMINI_API_KEY'), model='gemini-1.5-flash' ) ``` -------------------------------- ### Transcribe Audio File using AI Source: https://context7.com/sachinbhute/businesssathi/llms.txt This code snippet demonstrates how to transcribe an audio file using an AI service, specifically supporting OpenAI Whisper or Gemini. It initializes the `AIClient`, reads an audio file in binary mode, and prepares it for transcription. The actual transcription call is not shown but would follow the file reading. ```python from app.ai.client_factory import AIClient, AIProvider # Initialize client client = AIClient(provider=AIProvider.OPENAI) # Read audio file with open('business_summary.wav', 'rb') as f: audio_bytes = f.read() ``` -------------------------------- ### Generate Sample Retail Transaction Data (Python) Source: https://context7.com/sachinbhute/businesssathi/llms.txt This Python script utilizes the `generate_shop_data` function to create realistic retail transaction datasets. It allows for customization of the number of days, transactions per day, and inclusion of weekend boosts. The generated data can be saved to a CSV file or used directly. The script also references pre-built sample data files included in the project. ```python from scripts.generate_sample_data import generate_shop_data import pandas as pd # Generate custom sample data transactions = generate_shop_data( num_days=7, transactions_per_day=20, weekend_boost=True ) # Save to CSV transactions.to_csv('custom_sample.csv', index=False) print(f"Generated {len(transactions)} transactions") # Or run the script directly from command line: # python scripts/generate_sample_data.py # This creates 4 pre-built scenarios: # - sample_data/shop_sample.csv (Normal Week: ~200 transactions) # - sample_data/demo_weekend_boost.csv (Weekend Boost: ~245 transactions) # - sample_data/demo_slow_week.csv (Slow Week: ~41 transactions) # - sample_data/demo_high_value.csv (High Value: ~95 transactions) # Sample data includes: # - 15 different products across 6 categories # - Realistic pricing (₹15-₹136 per unit) # - Quantity variations (1-5 units per transaction) # - Discounts (0, ₹5, ₹10, ₹15) # - Payment methods (Cash, Card, UPI, Wallet) ``` -------------------------------- ### Check Provider Availability and List Available Providers Source: https://context7.com/sachinbhute/businesssathi/llms.txt This snippet shows how to check the availability status of the AI provider and list all available AI providers using the `AIClient`. It requires an initialized `AIClient` instance. ```python status = client.availability_status() print(status) providers = AIClient.get_available_providers() print(providers) ``` -------------------------------- ### Error Handling for AI Insights and KPIs Source: https://context7.com/sachinbhute/businesssathi/llms.txt This snippet implements robust error handling for processing transactions and generating AI insights. It prioritizes computing KPIs, which have no external dependencies. If AI insights generation fails due to unavailability (e.g., `RuntimeError`), it provides fallback mock insights and continues execution, ensuring the application remains functional. ```python from app.ai.client_factory import AIClient, AIProvider from app.utils.data_utils import compute_kpis import pandas as pd def process_transactions_safely(df: pd.DataFrame): """Process transactions with comprehensive error handling.""" try: # Compute KPIs (always works, no external dependencies) kpis = compute_kpis(df) print(f"✓ KPIs computed: Revenue ₹{kpis['total_revenue']:,.2f}") # Try to generate AI insights try: client = AIClient(provider=AIProvider.AUTO) data_json = build_json_for_ai(df, kpis) prompt = build_insights_prompt(data_json) insights = client.generate_business_insights(prompt) print("✓ AI insights generated successfully") return kpis, insights except RuntimeError as e: # AI unavailable, return KPIs only print(f"⚠ AI insights unavailable: {e}") print("⚠ Continuing with KPIs only (mock insights)") insights = { 'executive_summary_en': 'AI insights temporarily unavailable', 'executive_summary_hi': 'एआई सुझाव अभी उपलब्ध नहीं हैं', 'recommendations': ['Please check your API configuration'], 'recommendations_hi': ['कृपया अपनी एपीआई सेटिंग्स जांचें'] } return kpis, insights except Exception as e: print(f"❌ Error processing transactions: {e}") return {}, {} # Usage df = load_sample_data("Normal Week") kpis, insights = process_transactions_safely(df) ``` -------------------------------- ### Generate PDF Business Report Source: https://context7.com/sachinbhute/businesssathi/llms.txt This Python script generates a professional PDF business report containing KPIs, charts, and AI-generated insights. It utilizes pandas for data handling, utility functions for KPI computation and plotting, and the `make_pdf_report` function to create the PDF. The report can be saved to a file or used for download. ```python from app.utils.data_utils import compute_kpis, plot_top_products_bar, plot_daily_revenue_line, make_pdf_report import pandas as pd # Prepare data df = pd.DataFrame([ {'product': 'Lays Classic 50g', 'revenue': 26.31, 'day': '2025-09-05', 'quantity': 1, 'unit_price': 26.31, 'discount': 0, 'category': 'Snacks'}, {'product': 'Milk 1L', 'revenue': 122.26, 'day': '2025-09-05', 'quantity': 2, 'unit_price': 61.13, 'discount': 0, 'category': 'Dairy'} ]) # Compute metrics kpis = compute_kpis(df) # Generate charts top_products_png = plot_top_products_bar(df) daily_rev_png = plot_daily_revenue_line(df) # Mock insights (normally from AI) insights = { 'executive_summary_en': 'Your business shows strong performance with consistent revenue growth.', 'executive_summary_hi': 'आपका बिजनेस अच्छा चल रहा है और बिक्री बढ़ रही है।', 'recommendations': [ 'Focus on dairy products for higher margins', 'Stock popular items like Milk 1L adequately', 'Consider loyalty programs for repeat customers' ] } # Generate PDF pdf_bytes = make_pdf_report(kpis, top_products_png, daily_rev_png, insights) # Save to file with open('business_report.pdf', 'wb') as f: f.write(pdf_bytes) # Or in Streamlit, use download button # st.download_button( # label="Download PDF Report", # data=pdf_bytes, # file_name="business_report.pdf", # mime="application/pdf" # ) ``` -------------------------------- ### Generate Visualization Charts (Python) Source: https://context7.com/sachinbhute/businesssathi/llms.txt Creates data visualizations, specifically a bar chart for top products and a line chart for daily revenue trends. These charts are generated using matplotlib and returned as PNG byte streams, suitable for direct display in web applications like Streamlit. ```python from app.utils.data_utils import plot_top_products_bar, plot_daily_revenue_line import pandas as pd # Sample data df = pd.DataFrame([ {'product': 'Lays Classic 50g', 'revenue': 26.31, 'day': '2025-09-05'}, {'product': 'Milk 1L', 'revenue': 122.26, 'day': '2025-09-05'}, {'product': 'Maggi 2-Minute Noodles', 'revenue': 136.82, 'day': '2025-09-05'}, {'product': 'Coca Cola 500ml', 'revenue': 136.74, 'day': '2025-09-06'} ]) # Generate top products bar chart (returns PNG bytes) top_products_chart = plot_top_products_bar(df, top_n=5) with open('top_products.png', 'wb') as f: f.write(top_products_chart) # Generate daily revenue line chart (returns PNG bytes) daily_revenue_chart = plot_daily_revenue_line(df) with open('daily_revenue.png', 'wb') as f: f.write(daily_revenue_chart) # Use in Streamlit # st.image(top_products_chart, use_column_width=True) ``` -------------------------------- ### Generate AI Business Insights from Transaction Data Source: https://context7.com/sachinbhute/businesssathi/llms.txt This Python code generates bilingual business insights and recommendations from transaction data. It uses pandas for data manipulation, AIClient for AI processing, and custom utility functions for prompt building and KPI computation. The output includes executive summaries, recommendations, KPI commentary, risks, and opportunities in both English and Hindi. ```python from app.ai.client_factory import AIClient, AIProvider from app.ai.prompts import build_insights_prompt from app.utils.data_utils import build_json_for_ai, compute_kpis import pandas as pd # Prepare transaction data df = pd.DataFrame([ {'date': '2025-09-05', 'day': '2025-09-05', 'product': 'Lays Classic 50g', 'quantity': 1, 'unit_price': 26.31, 'discount': 0, 'revenue': 26.31, 'category': 'Snacks', 'payment_method': 'Card'}, {'date': '2025-09-05', 'day': '2025-09-05', 'product': 'Milk 1L', 'quantity': 2, 'unit_price': 61.13, 'discount': 0, 'revenue': 122.26, 'category': 'Dairy', 'payment_method': 'UPI'} ]) # Compute KPIs kpis = compute_kpis(df) # Build compact JSON payload for AI data_json = build_json_for_ai(df, kpis, max_rows=50) # Build prompt prompt = build_insights_prompt(data_json) # Generate insights client = AIClient(provider=AIProvider.GEMINI) insights = client.generate_business_insights(prompt, temperature=0.2) print(insights) ``` -------------------------------- ### Load and Normalize Transaction Data (Python) Source: https://context7.com/sachinbhute/businesssathi/llms.txt Loads transaction data from a CSV file or a Pandas DataFrame and normalizes it into a standard format. It handles flexible column mapping and ensures consistency for further analysis. The output includes columns like date, product, quantity, and revenue. ```python from app.utils.data_utils import load_transactions_from_csv, normalize_transactions import pandas as pd # Load from CSV file bytes with open('sample_data/shop_sample.csv', 'rb') as f: file_bytes = f.read() df = load_transactions_from_csv(file_bytes) # Or normalize existing DataFrame with flexible columns raw_df = pd.DataFrame([ {'order_date': '2025-09-05', 'sku': 'Lays Classic 50g', 'qty': 1, 'price': 26.31, 'disc': 0, 'payment': 'Card'}, {'order_date': '2025-09-05', 'sku': 'Milk 1L', 'qty': 2, 'price': 61.13, 'disc': 0, 'payment': 'UPI'} ]) normalized_df = normalize_transactions(raw_df) # Normalized output columns: date, day, product, category, quantity, unit_price, discount, revenue, payment_method print(normalized_df.head()) # Output: # date day product category quantity unit_price discount revenue payment_method # 0 2025-09-05 2025-09-05 Lays Classic 50g Snacks 1 26.31 0.0 26.31 Card # 1 2025-09-05 2025-09-05 Milk 1L Dairy 2 61.13 0.0 122.26 UPI ``` -------------------------------- ### Compute KPIs from Transaction Data (Python) Source: https://context7.com/sachinbhute/businesssathi/llms.txt Calculates key performance indicators from normalized transaction data. This includes total revenue, total orders, average order value, and identifies top-performing products and categories. The function takes a Pandas DataFrame as input and returns a dictionary of KPIs. ```python from app.utils.data_utils import compute_kpis import pandas as pd # Sample transaction data df = pd.DataFrame([ {'date': '2025-09-05', 'product': 'Lays Classic 50g', 'quantity': 1, 'unit_price': 26.31, 'discount': 0, 'category': 'Snacks', 'payment_method': 'Card'}, {'date': '2025-09-05', 'product': 'Milk 1L', 'quantity': 2, 'unit_price': 61.13, 'discount': 0, 'category': 'Dairy', 'payment_method': 'UPI'}, {'date': '2025-09-05', 'product': 'Maggi 2-Minute Noodles', 'quantity': 1, 'unit_price': 136.82, 'discount': 0, 'category': 'Food', 'payment_method': 'Wallet'} ]) df['revenue'] = (df['quantity'] * df['unit_price']) - df['discount'] df['day'] = pd.to_datetime(df['date']).dt.date kpis = compute_kpis(df) print(kpis) # Output: # { # 'total_revenue': 285.39, # 'total_orders': 3, # 'avg_order_value': 95.13, # 'top_product': 'Maggi 2-Minute Noodles', # 'top_category': 'Food' # } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.