<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeetlimbachiya on Medium]]></title>
        <description><![CDATA[Stories by Jeetlimbachiya on Medium]]></description>
        <link>https://medium.com/@jeetlimbachiya1999?source=rss-99398f512698------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rjG9_xiDiNw-XMHz.jpg</url>
            <title>Stories by Jeetlimbachiya on Medium</title>
            <link>https://medium.com/@jeetlimbachiya1999?source=rss-99398f512698------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:54:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeetlimbachiya1999/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Price prediction]]></title>
            <link>https://medium.com/@jeetlimbachiya1999/price-prediction-965cda8450d7?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/965cda8450d7</guid>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 10:29:28 GMT</pubDate>
            <atom:updated>2026-11-02T05:25:44.008Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Freight, Fuel &amp; accessories Charge Prediction System</strong></p><p><strong>Executive Summary &amp; Project Overview</strong></p><p>This project is an <strong>automated Machine Learning (ML) pricing engine</strong> built for <strong>freight logistics</strong>.</p><p>In freight shipping, quoting a price manually can be slow, inconsistent, and error-prone. This system automates price estimation by connecting directly to a SQL Server database, extracting historical shipment invoices, cleaning and preprocessing the data, training high-performance <strong>XGBoost Machine Learning models</strong>, and serving real-time predictions through a secure <strong>FastAPI Web Service</strong>.</p><p>To prevent “price inflation” (where standard shipments are overcharged because historical records contained expensive add-on services), the architecture separates pricing into three independent, itemized components:</p><ol><li><strong>Base Freight Charge Model</strong> (FrieghtCharge_model.py): Predicts standard linehaul transport costs based strictly on physical shipment characteristics.</li><li><strong>Fuel Surcharge Model</strong> (FuelCharge_model.py): Predicts dynamic fuel surcharges based on lane, distance, and weight.</li><li><strong>Hazmat Surcharge Model</strong> (HazmatCharge_model.py): Predicts hazardous material handling fees when hazmat services are requested.</li></ol><p><strong>System Architecture &amp; Data Flow</strong></p><p><strong>Detailed File-by-File Explanation</strong></p><p><strong>1. DB_connection.py — Database Connector</strong></p><p><strong>Purpose</strong></p><p>DB_connection.py acts as the bridge between the Python application and the Microsoft SQL Server database. It manages secure database connections and executes SQL queries to extract historical shipment records.</p><p><strong>Key Concepts &amp; Configuration</strong></p><ul><li><strong>Database Driver</strong>: Uses SQLAlchemy combined with pyodbc to communicate with SQL Server.</li><li><strong>Credentials (.env)</strong>: Connection details (server host, port, username, password, database name, and table) are loaded securely from a .env file via python-dotenv.</li><li><strong>Date Threshold (DATE_THRESHOLD)</strong>: Uses a date watermark (“20181231595959”) to filter and fetch records created from 2019 onward, ignoring obsolete historical pricing rules.</li><li><strong>Engine Caching (@lru_cache)</strong>: Caches the database connection engine so the application doesn’t waste time reopening database connections repeatedly.</li></ul><p><strong>Key Functions Inside DB_connection.py:</strong></p><ol><li><strong>get_engine()</strong>: Reads DATABASE_URL from the .env file, initializes the SQLAlchemy engine, and enables pool_pre_ping=True to automatically recover broken database connections.</li><li><strong>fetch_training_data()</strong>: Executes a SQL query to fetch all general LTL shipment records created after the date threshold. It retrieves tracking IDs, creation dates, weights, pallet counts, mileage distances, pickup/destination addresses, ZIP codes, freight charges, fuel charges, and accessorial flags.</li><li><strong>fetch_hazmat_training_csv()</strong>: Executes a specialized SQL query joining tbl_TrakingInfo (v), tbl_ProPricingTotals (t), and ProBillingSnapshot (j), and applies CROSS APPLY dbo.ExtractAccessorials(v.BillingAccessorialsXml) to parse XML accessorial data specifically for Hazmat shipments (a.IsHazmat = 1).</li><li><strong>fetch_latest_records()</strong>: A lightweight helper function that retrieves the top 10 newest database rows to test database connectivity without loading full datasets.</li></ol><p><strong>2. CSV_maker.py — Data Cleaning &amp; Dataset Generator</strong></p><p><strong>Purpose</strong></p><p>Raw data from a database contains noise, missing values (NULL / NaN), invalid zeroes, and unformatted address text. CSV_maker.py cleans raw database records, extracts clean 5-digit US ZIP codes from address text, enforces business limit filters, and outputs standardized, standalone CSV files for each model.</p><p><strong>Key Concepts &amp; Regular Expressions</strong></p><ul><li><strong>ZIP Code Extractor (ZIP_PATTERN)</strong>: Uses the regular expression r’(?&lt;!\d)(\d{5})(?:-\d{4})?(?!\d)’ to locate 5-digit US postal ZIP codes inside complex address text strings (e.g., extracting “08810” from “150 DOCKS CORNER ROAD | DAYTON NJ 08810 | United States”).</li><li><strong>extract_last_zip()</strong>: Extracts the last valid 5-digit ZIP code from pickup and destination address strings, automatically handling missing addresses.</li></ul><p><strong>Three Independent Dataset Cleaning Pipelines:</strong></p><ol><li><strong>Freight Charge Dataset (training_dataset.csv)</strong>:</li></ol><ul><li>Function: preprocess_training_data()</li><li>Target: FreightCharge</li><li>Filters applied: Coerces numeric columns, extracts pickup_zip and destination_zip, drops missing values (NULL/NaN), and keeps only shipments where weight &gt; 0, Pallets &gt; 0, MileageDistance &gt; 0, and FreightCharge &gt; 0.</li></ul><p><strong>2. Fuel Charge Dataset (fuel_training_dataset.csv)</strong>:</p><ul><li>Function: preprocess_fuel_training_data() / create_fuel_training_csv()</li><li>Target: FuelCharge</li><li>Filters applied: Operates independently of Freight Charge. Keeps rows with valid FuelCharge &gt; 0, weight &gt; 0, Pallets &gt; 0, MileageDistance &gt; 0, and valid 5-digit ZIPs.</li></ul><p><strong>3. Hazmat Charge Dataset (hazmatcharge_training_dataset.csv)</strong>:</p><ul><li>Function: preprocess_hazmat_training_data() / create_hazmat_training_csv()</li><li>Target: HazmatAmount</li><li>Filters applied: Cleans Hazmat records fetched via fetch_hazmat_training_csv(). Validates 5-digit PickUpZip and DestinationZip, and enforces weight &gt; 0, Pallets &gt; 0, Distance &gt; 0, and HazmatAmount &gt; 0.</li></ul><p><strong>4. FrieghtCharge_model.py — Base Freight Charge ML Model</strong></p><p><strong>Purpose</strong></p><p>Trains, evaluates, and manages the XGBoost Machine Learning model for predicting the core <strong>Freight Charge</strong>.</p><p><strong>Model Configuration &amp; Pipeline:</strong></p><ul><li><strong>Input Features (Predictors)</strong>:</li><li>Continuous Numeric: weight (lbs), Pallets (count), MileageDistance (miles).</li><li>Categorical Text: pickup_zip (origin ZIP string), destination_zip (destination ZIP string).</li><li><strong>Target Variable</strong>: FreightCharge ($).</li><li><strong>Feature Engineering &amp; Preprocessing</strong>:</li><li><strong>StandardScaler</strong>: Normalizes numeric features (weight, Pallets, MileageDistance) so large numbers don’t overpower the model.</li><li><strong>OneHotEncoder(handle_unknown=”ignore”)</strong>: Converts categorical ZIP code strings into binary category indicators while preserving leading zeroes (e.g., “08810”).</li><li><strong>TransformedTargetRegressor</strong>: Transforms the target variable using np.log1p during model fitting and applies np.expm1 during predictions. This prevents the model from ever outputting negative price predictions.</li><li><strong>XGBoost Hyperparameters</strong>: n_estimators=8000, max_depth=10, learning_rate=0.1, objective=”reg:squarederror”.</li></ul><p><strong>Client Constraints Filter</strong></p><p>Filters out invalid or out-of-range shipments before training:</p><ul><li>weight must be between 1 and 49,000 lbs.</li><li>Pallets must be between 1 and 30pallets.</li><li>MileageDistance must be between 1 and 6,500 miles.</li></ul><p><strong>Chronological Validation &amp; Model Promotion Gate</strong></p><p>To ensure the model genuinely improves over time and isn’t just memorizing data:</p><ol><li>Data is sorted chronologically by TrakingInfoID.</li><li>The latest <strong>25,000 records</strong> are held out as a strict validation set (VALIDATION_SIZE = 25,000).</li><li>Both the new candidate model and the existing production model are evaluated on this <strong>identical 25,000-row holdout set</strong> using R2R²R2 Score (Coefficient of Determination) and RMSE (Root Mean Squared Error).</li><li>The candidate model is saved with a timestamped filename (e.g., FrieghtCharge_05102026_122107.pkl and FrieghtCharge_05102026_122107_metadata.json).</li><li><strong>Quality Gate</strong>: The system updates production_model.json to point to the new model <strong>ONLY if its R2 score is higher</strong> than the current production champion.</li></ol><p><strong>5. FuelCharge_model.py — Fuel Surcharge ML Model</strong></p><p><strong>Purpose</strong></p><p>Trains and evaluates an independent XGBoost model to predict <strong>Fuel Surcharges</strong> based on lane and physical shipment traits.</p><p><strong>Key Features &amp; Differences:</strong></p><ul><li><strong>Input Features</strong>: weight, Pallets, MileageDistance, pickup_zip, destination_zip.</li><li><strong>Target Variable</strong>: FuelCharge ($).</li><li><strong>Model Pipeline</strong>: StandardScaler + OneHotEncoder + TransformedTargetRegressor(log1p/expm1) + xgb.XGBRegressor(n_estimators=8500, max_depth=10, learning_rate=0.1).</li><li><strong>Chronological Holdout</strong>: Uses the latest <strong>5,000 records</strong> (VALIDATION_SIZE = 5,000) for model validation.</li><li><strong>Independent Promotion Pointer</strong>: Evaluates candidate models on the holdout set and promotes the winner into fuelcharge_production_model.json.</li></ul><p><strong>6. HazmatCharge_model.py — Hazmat Surcharge ML Model</strong></p><p><strong>Purpose</strong></p><p>Trains and evaluates an independent XGBoost model to predict <strong>Hazmat Surcharges</strong> for shipments carrying hazardous materials.</p><p><strong>Key Features &amp; Differences:</strong></p><ul><li><strong>Input Features</strong>: weight, Pallets, Distance, IsHazmat, PickUpZip, DestinationZip.</li><li><strong>Target Variable</strong>: HazmatAmount ($).</li><li><strong>Model Pipeline</strong>: StandardScaler on numeric features + OneHotEncoder on IsHazmat and ZIP codes + TransformedTargetRegressor.</li><li><strong>Chronological Holdout</strong>: Uses the latest <strong>100 records</strong> (VALIDATION_SIZE = 100) for validation.</li><li><strong>Independent Promotion Pointer</strong>: Promotes winning models into hazmatcharge_production_model.json.</li></ul><p><strong>7. api.py — FastAPI Web Server &amp; Production Endpoints</strong></p><p><strong>Purpose</strong></p><p>api.py is the operational heart of the system. It runs a FastAPI web server that loads the active production models at startup, accepts prediction requests, handles incremental database syncs, and triggers retraining.</p><p><strong>Security &amp; Concurrency</strong></p><ul><li><strong>Bearer Token Authorization (HTTPBearer)</strong>: Every API endpoint requires an Authorization: Bearer &lt;API_BEARER_TOKEN&gt; header. Requests without a valid token are rejected with 401 Unauthorized.</li><li><strong>Thread Safety (RLock)</strong>: Employs re-entrant thread locks (model_lock, fuel_model_lock, hazmat_model_lock, csv_lock, training_lock) so that prediction requests and background retraining jobs never corrupt memory or files when running simultaneously.</li><li><strong>Application Lifespan (@asynccontextmanager lifespan)</strong>: At startup, the server reads production_model.json, fuelcharge_production_model.json, and hazmatcharge_production_model.json to load the active champion models into memory before taking live web traffic.</li></ul><p><strong>Complete API Endpoint &amp; Parameter Reference</strong></p><p><strong>1. GET /predict</strong></p><p>Predicts the baseline <strong>Freight Charge</strong> for a single shipment.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/predict</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*u2a0nQ-3Kow5tW9Qfv99Dw.png" /></figure><ul><li><strong>Required Query Parameters</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*TuUPQ2hoTnJnI1VX5WgOcw.png" /></figure><ul><li>Example Request:</li></ul><p><strong>GET </strong><a href="http://127.0.0.1:8012/predict_frieght?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245"><strong>http://127.0.0.1:8002/predict?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245</strong></a></p><ul><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“Answer”: 1450.25</p><p>}</p><p><strong>2. GET /predict_fuel</strong></p><p>Predicts the <strong>Fuel Surcharge</strong> for a single shipment.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/predict_fuel</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li><li><strong>Required Query Parameters</strong>: Same 5 parameters (weight, pallets, distance, pickupzip, destinationzip).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*TTnVcCYF0nE1G5wedP72tA.png" /></figure><ul><li><strong>Example Request</strong>:</li></ul><p><strong>GET </strong><a href="http://127.0.0.1:8012/predict_fuel?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245"><strong>http://127.0.0.1:8002/predict_fuel?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245</strong></a></p><ul><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“Answer”: 377.46</p><p>}</p><p><strong>3. GET /predict_hazmat</strong></p><p>Predicts the <strong>Hazmat Surcharge</strong> for a shipment.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: <a href="http://127.0.0.1:8002/predict_hazmat">http://127.0.0.1:8002/predict_hazmat</a></li><li><strong>Headers</strong>: Authorization: Bearer &lt;your token&gt;</li><li><strong>Required Query Parameters</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Xatj7OUB32OfZerMOJ6tJw.png" /></figure><ul><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“Answer”: 100.00</p><p>}</p><p><strong>4. GET /predict_all (Combined Multi-Model Endpoint)</strong></p><p>Executes Freight, Fuel, and Hazmat models simultaneously and returns an itemized pricing breakdown along with the total estimated cost.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/predict_all</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li><li><strong>Query Parameters</strong>: weight, pallets, distance, pickupzip, destinationzip, is_hazmat.</li><li><strong>Example Request</strong>:</li><li>GET <a href="http://127.0.0.1:8012/predict_all?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245&amp;is_hazmat=Yes">http://127.0.0.1:8002/predict_all?weight=10551&amp;pallets=13&amp;distance=618.1&amp;pickupzip=08810&amp;destinationzip=40245&amp;is_hazmat=Yes</a></li><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“FreightCharge”: 1450.25,</p><p>“FuelCharge”: 377.46,</p><p>“AccessorialCharge”: 100.00,</p><p>“TotalEstimatedCharge”: 1927.71</p><p>}</p><p><strong>5. POST /update_data</strong></p><p>Queries SQL Server for new shipment records created after the highest TrakingInfoID currently in local CSVs, cleans them via CSV_maker.py, and appends them to local training CSVs.</p><ul><li><strong>HTTP Method</strong>: POST</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/update_data</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li><li><strong>Request Body</strong>: None required.</li><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“status”: “success”,</p><p>“freight_added_records”: 39,</p><p>“fuel_added_records”: 7,</p><p>“hazmat_added_records”: 2,</p><p>“message”: “FreightCharge CSV added 39 rows; FuelCharge CSV added 7 rows; HazmatCharge CSV added 2 rows.”</p><p>}</p><p><strong>6. GET /retrain</strong></p><p>Triggers model retraining across the updated CSV datasets. Evaluates candidate models against held-out validation sets, logs training history, and promotes models if R2 scores improve.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/retrain</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“status”: “success”,</p><p>“message”: “Model was trained on the existing CSV and created a test and train CSV with predictions. Use /predict to get predictions for new inputs.”</p><p>}</p><p><strong>7. GET /last_tracking_id_value</strong></p><p>Returns the highest TrakingInfoID stored in each local CSV dataset.</p><ul><li><strong>HTTP Method</strong>: GET</li><li><strong>URL</strong>: http://&lt;server-ip&gt;:8002/last_tracking_id_value</li><li><strong>Headers</strong>: Authorization: Bearer &lt;your_token&gt;</li><li><strong>Sample Response (200 OK)</strong>:</li></ul><p>{</p><p>“freight_trakinginfoid”: 526501,</p><p>“fuel_trakinginfoid”: 526501</p><p>}</p><p><strong>Operational Guide: Running &amp; Testing the Application</strong></p><p><strong>1. Environment Setup (.env)</strong></p><p>Create a .env file in the project root directory with the following variables:</p><p><strong>DATABASE_URL=mssql+pyodbc://username:password@server_ip:1433/WQ_EliteExpress?driver=ODBC+Driver+17+for+SQL+Server</strong></p><p><strong>DB_TABLE=ProBillingtable</strong></p><p><strong>API_BEARER_TOKEN=your_secure_generated_secret_key</strong></p><p><strong>2. Starting the API Server</strong></p><p>Run Uvicorn from the project folder:</p><p>Command: <strong>python -m uvicorn api:app — host 0.0.0.0 — port 8002</strong></p><p><strong>3. Accessing Swagger Documentation</strong></p><p>Open your web browser and navigate to:</p><p><a href="http://127.0.0.1:8012/docs"><strong>http://127.0.0.1:8002/docs</strong></a></p><p>This interactive page allows you to inspect, authenticate, and test all API endpoints directly or you can use your postman app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=965cda8450d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IOT]]></title>
            <link>https://medium.com/@jeetlimbachiya1999/iot-6f44c50a11b9?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f44c50a11b9</guid>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 13:25:59 GMT</pubDate>
            <atom:updated>2026-11-16T07:16:38.005Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Running the MQTT IoT Platform: A Beginner’s Guide</strong></p><p><strong>Introduction</strong></p><p>This project receives IoT sensor messages over MQTT, checks whether the connecting device is allowed to connect, stores selected messages in PostgreSQL, and converts sensor data into topics that Home Assistant can understand.</p><p>The project has four main parts:</p><p>1. <strong>HiveMQ Community Edition 2025.5</strong> is the MQTT broker. It receives messages and delivers them to the correct clients.</p><p>2. <strong>The Java HiveMQ extension </strong>connects HiveMQ broker to Django during MQTT login.</p><p>3. <strong>The Django API</strong> registers users and decides whether an MQTT username and password are valid to send the MQTT messages.</p><p>4. <strong>The Python worker and mediator</strong> store raw sensor events and publish Home Assistant discovery and state messages.</p><p>PostgreSQL is the database used by Django to stores MQTT credentials.</p><p>The raw messages saved by the worker can also be stored in the database (optional).</p><p>The easiest way to understand the system is:</p><p>- HiveMQ broker handles MQTT messages.</p><p>- Django handles authentication and database access.</p><p>- The Java extension is the bridge between HiveMQ and Django.</p><p>- The worker stores messages (optional).</p><p>- The mediator transforms messages for Home Assistant platform.</p><p>Uses the Python mediator file for converting the sensor data to Home-Assistant functionality format.</p><p><strong>Quick start order</strong></p><p>Run the services in this order:</p><p>1. Start PostgreSQL.</p><p>2. Configure the Django database environment variables.</p><p>3. Install Python dependencies and run Django migrations.</p><p>4. Register an active MQTT user (via API).</p><p>5. Start Django on port `8000`.</p><p>6. Build and copy the Java extension.</p><p>7. Start HiveMQ on port `1883`.</p><p>8. Start the Python worker.</p><p>9. Start the Python mediator.</p><p>10. Connect an MQTT client and publish a sensor event.</p><p>If MQTT login fails, check Django first. HiveMQ calls Django synchronously during every new MQTT connection.</p><p><strong>Commands for each service</strong></p><p><strong>Start Django</strong></p><p>From the Django project directory, activate the virtual environment and start the API:</p><p>```bat</p><p>cd /d “u:\Jeet Limbachiya\Production\client\iot\cred_server”</p><p>.venv\Scripts\activate</p><p>python manage.py migrate</p><p>python manage.py runserver 127.0.0.1:8000</p><p>```</p><p>Keep this terminal running. HiveMQ calls Django at `http://127.0.0.1:8000/api/mqtt-auth/` when an MQTT client logs in.</p><p><strong>Build and install the Java extension</strong></p><p>Build the extension, then copy the JAR and descriptor into HiveMQ’s extension folder:</p><p>```bat</p><p>cd /d “u:\Jeet Limbachiya\Production\client\django-auth-extension”</p><p>mvn clean package</p><p>copy /Y target\django-auth-extension-1.0.jar “u:\Jeet Limbachiya\Production\client\hivemq-ce-2025.5\extensions\django-auth-extension\”</p><p>copy /Y src\main\resources\hivemq-extension.xml “u:\Jeet Limbachiya\Production\client\hivemq-ce-2025.5\extensions\django-auth-extension\”</p><p>```</p><p><strong>Start HiveMQ</strong></p><p>Start the broker after Django and the extension are ready:</p><p>```bat</p><p>cd /d “u:\Jeet Limbachiya\Production\client\hivemq-ce-2025.5\bin”</p><p>run.bat</p><p>```</p><p>The development MQTT listener is `127.0.0.1:1883`.</p><p><strong>Start the worker</strong></p><p>The worker saves raw messages in the `MQTTMessage` table:</p><p>```bat</p><p>cd /d “u:\Jeet Limbachiya\Production\client\iot\cred_server”</p><p>.venv\Scripts\activate</p><p>python mqtt_worker\run_worker.py</p><p>```</p><p><strong>Start the mediator</strong></p><p>The mediator publishes Home Assistant discovery and state topics:</p><p>```bat</p><p>cd /d “u:\Jeet Limbachiya\Production\client\iot\cred_server”</p><p>.venv\Scripts\activate</p><p>python mqtt_worker\mediator.py</p><p>```</p><p>Run the worker and mediator in separate terminals. They are ordinary MQTT clients, so they must connect with an active credential that Django can authenticate.</p><p>```mermaid</p><p>flowchart LR</p><p>Device[Sensor or MQTT client] →|MQTT CONNECT| Broker[HiveMQ CE]</p><p>Broker →|SimpleAuthenticator hook| Java[Java Django Auth Extension]</p><p>Java →|HTTP POST /api/mqtt-auth/| Django[Django API]</p><p>Django →|Credential query| DB[(PostgreSQL)]</p><p>Django →|allow or deny| Java</p><p>Java →|authentication result| Broker</p><p>Broker →|sensor event| Worker[Python ingestion worker]</p><p>Worker →|MQTTMessage INSERT| DB</p><p>Broker →|sensor event| Mediator[Python mediator]</p><p>Mediator →|retained Home Assistant topics| Broker</p><p>Broker → HA[Home Assistant or downstream consumers]</p><p>```</p><p>This article describes the implementation currently present in the repository. It also calls out behavior that is incomplete or unsafe for production, because a technical explanation should not confuse current code with the desired final design.</p><p><strong>Repository layout</strong></p><p>The relevant folders are:</p><p>- `hivemq-ce-2025.5/`: the HiveMQ Community Edition distribution, configuration, extensions directory, runtime data, and logs.</p><p>- `django-auth-extension/`: the standard Java extension source.</p><p>- `django-auth-extension-EntEdition/`: a second Java source variant with a smaller extension entry point.</p><p>- `iot/cred_server/`: the Django project and Python MQTT processes.</p><p>- `build_and_test.bat`: the Maven build helper.</p><p>- `project workflow.md`: an operational description of the system.</p><p>The repository also contains Maven `target/` directories and HiveMQ runtime data. Those generated files are useful evidence of previous builds and executions, but the source files and configuration are the authoritative implementation.</p><p><strong>1. HiveMQ Community Edition</strong></p><p><strong>What HiveMQ does</strong></p><p>HiveMQ is the central MQTT broker. MQTT clients connect to it, authenticate, publish messages, and subscribe to topics. The broker does not itself contain the Django credential logic. That behavior is injected through the Java extension API.</p><p>The current broker configuration is in `hivemq-ce-2025.5/conf/config.xml`. It defines four listeners:</p><p>| Listener | Address | Purpose |</p><p>| — -| — -:| — -|</p><p>| TCP | `0.0.0.0:1883` | Plain MQTT, mainly local/testing traffic |</p><p>| TLS TCP | `0.0.0.0:8883` | TLS-protected MQTT |</p><p>| WebSocket | `127.0.0.1:8083/mqtt` | Local WebSocket MQTT |</p><p>| TLS WebSocket | `0.0.0.0:8084/mqtt` | TLS WebSocket MQTT |</p><p>Port `1883` is unencrypted and bound to every interface. Port `8883` uses a PKCS12 keystore at `hivemq_cert/keystore.p12`. The repository configuration contains a literal keystore password, so that value must be replaced and managed as a secret before production use.</p><p>The configuration does not show topic-level authorization rules. Authentication answers the question “may this client connect?” It does not visibly answer “which topics may this client read or write?” A production deployment needs authorization rules in addition to authentication.</p><p><strong>How the Community Edition was obtained</strong></p><p>The current folder is a HiveMQ CE distribution rather than a source build of HiveMQ itself. Its `README.txt` contains the vendor quick-start instructions for running `bin/run.sh` on Unix-like systems or `bin/run.bat` on Windows. The repository does not contain a download script, checksum record, or installation automation, so the exact original download operation cannot be proven from source alone.</p><p>The project notes also reference the HiveMQ Extension SDK Maven artifact at:</p><p>```text</p><p><a href="https://repo1.maven.org/maven2/com/hivemq/hivemq-extension-sdk/4.48.1/">https://repo1.maven.org/maven2/com/hivemq/hivemq-extension-sdk/4.48.1/</a></p><p>```</p><p>That SDK is a Java compile-time dependency for the extension. It is separate from the HiveMQ broker distribution itself.</p><p><strong>Starting HiveMQ</strong></p><p>On Windows, the intended command is run from the broker’s `bin` directory:</p><p>```bat</p><p>cd /d “…\hivemq-ce-2025.5\bin”</p><p>run.bat</p><p>```</p><p>The broker loads extension folders under `hivemq-ce-2025.5/extensions/`. The deployed extension currently contains:</p><p>```text</p><p>hivemq-ce-2025.5/extensions/django-auth-extension/</p><p>django-auth-extension-1.0.jar</p><p>hivemq-extension.xml</p><p>```</p><p>HiveMQ runtime logs and `client_report.txt` provide evidence of broker startup, extension startup, and connected clients. Runtime logs should be treated as operational evidence, not as a replacement for checking the active configuration: one documented startup encountered a configuration-read problem and fell back to defaults.</p><p><strong>2. The Java HiveMQ authentication extension</strong></p><p><strong>Maven project</strong></p><p>The standard extension is built from `django-auth-extension/pom.xml`.</p><p>Its important build settings are:</p><p>- Java release: 17</p><p>- HiveMQ Extension SDK: `4.48.1`, scope `provided`</p><p>- Jackson Databind: `2.15.2`</p><p>- Maven Compiler Plugin: `3.11.0`</p><p>- Maven Shade Plugin: `3.5.1`</p><p>The HiveMQ SDK is marked `provided` because HiveMQ supplies the SDK classes at runtime. Jackson is shaded into the resulting JAR so that the extension can serialize request JSON and parse response JSON without requiring a separately installed Jackson library in the broker.</p><p>Build it with:</p><p>```bat</p><p>cd /d “…\django-auth-extension”</p><p>mvn clean package</p><p>```</p><p>The output is `target/django-auth-extension-1.0.jar`. The original, unshaded artifact is also produced in `target/`.</p><p>The root `build_and_test.bat` correctly resolves its Maven directory relative to the script using `%~dp0`, although older project notes contain stale absolute paths. The safe deployment step is to copy the newly built JAR and its extension descriptor into the CE extension directory, then restart HiveMQ.</p><p><strong>Extension descriptor</strong></p><p>`src/main/resources/hivemq-extension.xml` identifies the extension to HiveMQ:</p><p>```xml</p><p>&lt;hivemq-extension xmlns=”http://www.hivemq.com/hivemq-extension&quot;&gt;</p><p>&lt;id&gt;django-mqtt-auth&lt;/id&gt;</p><p>&lt;name&gt;Django MQTT Auth Extension&lt;/name&gt;</p><p>&lt;version&gt;1.0.0&lt;/version&gt;</p><p>&lt;priority&gt;100&lt;/priority&gt;</p><p>&lt;main-class&gt;com.company.mqtt.DjangoAuthExtensionMain&lt;/main-class&gt;</p><p>&lt;start-priority&gt;100&lt;/start-priority&gt;</p><p>&lt;/hivemq-extension&gt;</p><p>```</p><p>The `main-class` points to the Java entry point. The current source descriptors in both Java folders use this element. The deployed descriptor should always be checked against the source artifact because a copied JAR and an old descriptor can represent different builds.</p><p><strong>Standard extension startup</strong></p><p>`DjangoAuthExtensionMain` implements HiveMQ’s `ExtensionMain` interface. On startup it:</p><p>1. Registers `DjangoAuthenticatorProvider` through `Services.securityRegistry()`.</p><p>2. Registers a `ClientLifecycleEventListener` through `Services.eventRegistry()`.</p><p>3. Starts periodic client reporting through `ClientSessionStore`.</p><p>On shutdown it stops the reporting scheduler.</p><p>The extension does not open a server port and does not own the database connection. It is an adapter inside the broker process. Its job is to translate HiveMQ authentication events into an HTTP request to Django.</p><p><strong>Authentication provider and authenticator</strong></p><p>`DjangoAuthenticatorProvider` creates a `DjangoAuthenticator` for an authentication request. The authenticator receives the MQTT `CONNECT` packet through `SimpleAuthInput`.</p><p>The sequence is:</p><p>```mermaid</p><p>sequenceDiagram</p><p>participant C as MQTT client</p><p>participant H as HiveMQ</p><p>participant J as Java authenticator</p><p>participant D as Django</p><p>participant P as PostgreSQL</p><p>C-&gt;&gt;H: CONNECT(username, password)</p><p>H-&gt;&gt;J: onConnect(SimpleAuthInput)</p><p>J-&gt;&gt;J: Read username and password from ConnectPacket</p><p>J-&gt;&gt;D: POST /api/mqtt-auth/ JSON credentials</p><p>D-&gt;&gt;P: SELECT Credential by username</p><p>P →&gt;D: Credential row</p><p>D →&gt;J: {“result”:”allow”} or {“result”:”deny”}</p><p>J-&gt;&gt;H: authenticateSuccessfully() or failAuthentication()</p><p>H →&gt;C: CONNACK accepted or rejected</p><p>```</p><p>`DjangoAuthenticator` performs these steps:</p><p>1. Reads the optional MQTT username and password from `ConnectPacket`.</p><p>2. Rejects the connection immediately if either is absent.</p><p>3. Copies the password bytes from the `ByteBuffer` and decodes them as UTF-8.</p><p>4. Builds a JSON body containing `username` and `password`.</p><p>5. Sends a synchronous HTTP `POST` to `http://127.0.0.1:8000/api/mqtt-auth/`.</p><p>6. Uses five-second connect and read timeouts.</p><p>7. Parses the JSON response with Jackson.</p><p>8. Allows the MQTT connection only when `result` equals `allow`, ignoring case.</p><p>9. Rejects the connection when Django is unavailable, returns a non-200 response, returns malformed JSON, or returns any other result.</p><p>This means Django availability is part of the broker’s authentication path. If Django or PostgreSQL is down, new MQTT connections fail closed.</p><p><strong>Client tracking</strong></p><p>The standard extension listens for successful authentication and disconnect events. On successful authentication it records:</p><p>- MQTT client ID</p><p>- Client IP address</p><p>- Connection time</p><p>`ClientSessionStore` keeps active clients in a `ConcurrentHashMap`. Every 30 minutes it overwrites:</p><p>```text</p><p>&lt;hivemqHome&gt;/log/client_report.txt</p><p>```</p><p>The report is a snapshot of currently active clients. Disconnected clients are removed from the map, so the file is not a historical connection audit log. The `disconnectTime` field is assigned briefly during removal but is not written to the report.</p><p><strong>Enterprise-named variant (optional for prototyping)</strong></p><p>`django-auth-extension-EntEdition` is not demonstrably a different commercial SDK project. Its POM uses the same Maven coordinates and HiveMQ SDK version as the standard project. Its `DjangoAuthenticator` is effectively the same, but its `DjangoAuthExtensionMain` registers only the authenticator provider.</p><p>Therefore the practical difference in the repository is:</p><p>| Capability | Standard folder | EntEdition folder |</p><p>| — -| — -:| — -:|</p><p>| Django-backed MQTT authentication | Yes | Yes |</p><p>| Client lifecycle listener | Yes | No |</p><p>| Periodic client report | Yes | No |</p><p>| HiveMQ SDK version | 4.48.1 | 4.48.1 |</p><p>| Java target | 17 | 17 |</p><p>The folder name alone should not be used to claim that the code is linked to HiveMQ Enterprise Edition.</p><p><strong>3. Django credential service</strong></p><p><strong>Project configuration</strong></p><p>The Django project is `iot/cred_server/`. Its root URL configuration exposes the admin site and includes the application API under `/api/`.</p><p>The settings configure PostgreSQL using environment variables:</p><p>```text</p><p>DB_NAME</p><p>DB_USER</p><p>DB_PASSWORD</p><p>DB_HOST</p><p>DB_PORT</p><p>```</p><p>`load_dotenv()` is called, so a local `.env` can provide these values. The repository has development-oriented settings: `DEBUG = True`, a hardcoded Django secret key, and `ALLOWED_HOSTS = [‘*’]`.</p><p>The checked-in `iot/requirements.txt` does not describe all imports used by the Django project. It includes Paho, FastAPI-related packages, and supporting packages, but the Django, PostgreSQL adapter, and Django dotenv requirements should be made explicit in a maintained deployment requirements file.</p><p><strong>API routes</strong></p><p>The application maps two routes:</p><p>```text</p><p>POST /api/register-user/</p><p>POST /api/mqtt-auth/</p><p>```</p><p>Both views are marked `csrf_exempt` because they are intended for machine-to-machine calls. That removes CSRF protection, so the endpoints need another strong authentication mechanism and should not be exposed publicly without TLS and access control.</p><p><strong>Credential model</strong></p><p>The `Credential` model contains:</p><p>- `id`: UUID primary key</p><p>- `user_id`: unique generated application identifier</p><p>- `username`: unique MQTT username</p><p>- `password_hash`: credential field</p><p>- `is_active`: connection enable/disable flag</p><p>- `org_name`: organization metadata</p><p>- `org_token`: organization token metadata</p><p>- `created_at`: creation timestamp</p><p>- `last_connected_at`: updated after successful MQTT authentication</p><p>- `metadata`: flexible JSON metadata</p><p>The name `password_hash` is misleading in the current implementation because registration stores the raw password. The model is prepared for hashed values, but the active service code does not use Django’s password hashing API.</p><p>`MQTTMessage` stores:</p><p>- Auto-incrementing message ID</p><p>- Hub serial</p><p>- Sensor serial</p><p>- Message type</p><p>- Complete raw payload</p><p>- Creation timestamp</p><p>The migration history shows that the schema evolved from an earlier credential-consumption design, then added organization fields and user IDs, renamed connection timestamps, reintroduced `is_active`, and finally added `MQTTMessage`.</p><p><strong>Registration flow</strong></p><p>A client sends JSON like:</p><p>```json</p><p>{</p><p>“username”: “example-device-user”,</p><p>“password”: “redacted”,</p><p>“orgName”: “Example Organization”,</p><p>“token”: “redacted”</p><p>}</p><p>```</p><p>`register_user_view`:</p><p>1. Requires `POST`.</p><p>2. Parses the request body as JSON.</p><p>3. Requires all four fields.</p><p>4. Rejects an existing username.</p><p>5. Calls `CredentialService.register_user`.</p><p>6. Returns the generated `userId`, username, and organization name.</p><p>`CredentialService.generate_user_id()` uses a five-digit pseudo-random number prefixed with `u_`. That can collide because it is not generated from a uniqueness retry loop or a cryptographic identifier.</p><p>The active registration code does this:</p><p>```python</p><p>hashed_password = password</p><p>```</p><p>The intended `make_password(password)` call is commented out. Consequently, `password_hash` currently contains the original password and the response is compatible with the MQTT authentication endpoint’s direct string comparison.</p><p><strong>What the token does</strong></p><p>The registration field named `token` is stored in `Credential.org_token`. No current view or Java extension compares an incoming request against `org_token`. The Java extension sends only `username` and `password` to `/api/mqtt-auth/`.</p><p>Therefore the current token is not an API key in the enforcement sense. It is stored organization metadata. A blog should describe this accurately rather than claiming that it authorizes MQTT access.</p><p>A real API-key design would need to define where the key is presented, how it is hashed and rotated, how it is associated with an organization or client, and how it is checked. It would also need a clear distinction between an HTTP API key and an MQTT password.</p><p><strong>MQTT authentication endpoint</strong></p><p>`mqtt_authenticate_view` accepts JSON containing `username` and `password`. It:</p><p>1. Rejects non-POST requests.</p><p>2. Parses the JSON body.</p><p>3. Looks up the credential by username.</p><p>4. Denies unknown users.</p><p>5. Compares the submitted password directly with `cred.password_hash`.</p><p>6. Denies inactive users.</p><p>7. Updates `last_connected_at` on success.</p><p>8. Returns `{“result”: “allow”}`.</p><p>Every failure returns `{“result”: “deny”}` except the method error, which returns HTTP 405 with the same result. The Java extension accepts only HTTP 200, so method errors and server errors become failed MQTT authentication.</p><p>The current view logs the entire request body, the submitted password, the database password field, and authentication details. This must be removed before production. Passwords should never appear in application logs.</p><p><strong>4. Python MQTT worker</strong></p><p>The worker consists of `run_worker.py` and `mqtt_client.py`.</p><p>`run_worker.py` bootstraps Django manually by adding `iot/cred_server` to `sys.path`, setting `DJANGO_SETTINGS_MODULE`, and calling `django.setup()`. It then creates an `MQTTClient` with the current defaults:</p><p>```text</p><p>Broker: 127.0.0.1</p><p>Port: 1883</p><p>Topic: praxis/test/events</p><p>Client ID: django_mqtt_worker</p><p>Username: service credential configured in source</p><p>Password: configured in source</p><p>```</p><p>The worker uses the MQTT v3.1.1 protocol, a clean session, and Paho’s background network loop. On connection it subscribes to `praxis/test/events` with QoS 1.</p><p>For each message it:</p><p>1. Decodes the payload as UTF-8.</p><p>2. Parses JSON.</p><p>3. Reads `hub serial`, `type`, and `sensor data.serial`.</p><p>4. Inserts the original payload into `MQTTMessage`.</p><p>The worker is an ingestion path, not a transformation path. It does not publish Home Assistant topics. It also does not validate a schema before inserting. Missing non-null model fields can cause database errors, and malformed UTF-8 or unexpected JSON shapes are handled only partially.</p><p><strong>5. Python mediator</strong></p><p>The mediator is a second MQTT client with a different responsibility. It bootstraps Django because it reads the service credential from the database, then connects to HiveMQ with:</p><p>```text</p><p>MQTT_BROKER_HOST default: 127.0.0.1</p><p>MQTT_BROKER_PORT default: 1883</p><p>MQTT_SERVICE_USER default: service username configured in source</p><p>```</p><p>Unlike the worker, the mediator obtains its password using:</p><p>```python</p><p>Credential.objects.get(username=SERVICE_USERNAME, is_active=True)</p><p>```</p><p>It then calls `username_pw_set` and connects to the broker. On connection it subscribes to `#`, meaning every topic visible to that MQTT identity.</p><p><strong>Message filtering</strong></p><p>The mediator:</p><p>1. Ignores topics ending in `/digital_out/set` after logging the command.</p><p>2. Ignores payloads that do not look like JSON objects.</p><p>3. Parses JSON.</p><p>4. Processes only messages whose `type` is `sensor data`.</p><p>5. Reads `hub serial`.</p><p>6. Accepts either `sensor data` or `sensor data ` with a trailing space.</p><p>7. Removes a leading `0x` from the sensor serial.</p><p>8. Publishes discovery metadata once for each `hub/serial` pair.</p><p>9. Publishes retained sensor state topics.</p><p>It keeps an in-memory `contexts` map for discovery and a `last_values` map for duplicate suppression. Restarting the mediator clears both maps, so discovery is sent again after a restart.</p><p><strong>State topic format</strong></p><p>The mediator publishes state to:</p><p>```text</p><p>xcom/{username}/{hub}/{sensor-serial}/{identifier}</p><p>```</p><p>Numeric values use JSON payloads:</p><p>```json</p><p>{“value”: 23.4}</p><p>```</p><p>Binary values use plain text:</p><p>```text</p><p>ON</p><p>OFF</p><p>```</p><p>All state messages are retained, so a new subscriber can receive the latest known value immediately.</p><p><strong>Transformations</strong></p><p>The mediator maps source sensor data as follows:</p><p>| Source field | Output identifier | Transformation |</p><p>| — -| — -| — -|</p><p>| `temperature` | `temperature` | Divide by 10 |</p><p>| `humidity` | `humidity` | Divide by 10 |</p><p>| `light` | `light` | Direct value |</p><p>| `battery` | `battery` | Convert 3300–4200 mV to 0–100%, clamp and round |</p><p>| `analog 1` | `analog1` | Direct value |</p><p>| `analog 2` | `analog2` | Direct value |</p><p>| `motion.x/y/z` | `accel_x/y/z` | Direct axes |</p><p>| motion magnitude | `motion_state` | `Stationary`, `Moderate`, or `High` |</p><p>| trigger bit 5 | `movement` | Binary ON/OFF |</p><p>| trigger bit 6 | `sound` | Binary ON/OFF |</p><p>| trigger bit 10 | `digital1` | Binary ON/OFF |</p><p>| trigger bit 11 | `digital2` | Binary ON/OFF |</p><p>Motion state uses the Euclidean magnitude:</p><p>$$m = \sqrt{x² + y² + z²}$$</p><p>The thresholds are:</p><p>- Below 1200: `Stationary`</p><p>- 1200 through below 2500: `Moderate`</p><p>- 2500 or above: `High`</p><p>The mediator also emits `last_update` using the current UTC timestamp.</p><p><strong>Home Assistant discovery</strong></p><p>For each sensor, the mediator publishes retained discovery JSON below:</p><p>```text</p><p>homeassistant/sensor/{username}_{serial}_{identifier}_v8/config</p><p>homeassistant/binary_sensor/{username}_{serial}_{identifier}_v8/config</p><p>```</p><p>The discovery payload includes the state topic, unique ID, display name, device class where applicable, and a shared device object:</p><p>```json</p><p>{</p><p>“identifiers”: [“&lt;username&gt;-&lt;hub&gt;-&lt;serial&gt;”],</p><p>“name”: “XSEN &lt;serial&gt;”,</p><p>“manufacturer”: “Praxis Tech”,</p><p>“model”: “NG Sensor”</p><p>}</p><p>```</p><p>The Python mediator registers temperature, humidity, light, battery, analog inputs, accelerometer axes, last update, motion state, movement, sound, and two digital inputs.</p><p><strong>6. End-to-end runtime sequence</strong></p><p>A normal local startup is conceptually:</p><p>```mermaid</p><p>flowchart TD</p><p>A[Configure PostgreSQL environment] → B[Start Django on port 8000]</p><p>B → C[Build Java extension with Maven]</p><p>C → D[Copy JAR and descriptor into HiveMQ extensions]</p><p>D → E[Start HiveMQ]</p><p>E → F[Start worker and/or mediator]</p><p>F → G[Connect an MQTT client]</p><p>G → H[Java extension calls Django]</p><p>H → I[Broker accepts connection]</p><p>I → J[Publish sensor event]</p><p>J → K[Worker stores raw event]</p><p>J → L[Mediator publishes retained HA state]</p><p>```</p><p>Detailed ordering matters:</p><p>1. PostgreSQL must be reachable with the environment variables expected by Django.</p><p>2. Django must be running before an MQTT client attempts to connect, because the Java extension calls it synchronously.</p><p>3. The Java JAR must be copied into the broker’s extension directory before HiveMQ starts or before the extension is reloaded.</p><p>4. A credential must exist and be active before the worker or mediator can authenticate.</p><p>5. The publisher must send the sensor JSON on a topic consumed by the worker or mediator.</p><p>6. Home Assistant must be connected to the broker and subscribed to the discovery/state topics.</p><p><strong>7. Security and production review</strong></p><p>The current repository is a development implementation. The major risks are:</p><p>- Passwords are stored and compared in plaintext.</p><p>- The Java extension sends credentials over plain HTTP, even though it is local-loopback traffic.</p><p>- Django logs submitted and stored passwords.</p><p>- Database credentials and client credentials exist in local project files or source configuration.</p><p>- Port 1883 is unencrypted and bound to all interfaces.</p><p>- TLS keystore passwords are written in broker XML.</p><p>- Django runs with `DEBUG = True`, a hardcoded secret key, and wildcard hosts.</p><p>- The registration token is not enforced as an API key.</p><p>- No topic-level authorization is visible in the broker configuration.</p><p>- The worker uses hardcoded credentials and topic settings.</p><p>- The mediator subscribes to every topic with `#`.</p><p>- The Java authentication request is synchronous, so Django latency directly affects MQTT connection latency.</p><p>- There are no meaningful automated tests in the Django application.</p><p>- The requirements file does not fully describe the Django runtime.</p><p>A hardening roadmap should include:</p><p>1. Use `make_password` during registration and `check_password` during authentication.</p><p>2. Remove all password logging immediately.</p><p>3. Move secrets to a secret manager or protected environment configuration.</p><p>4. Use HTTPS between the extension and Django, ideally with certificate verification.</p><p>5. Prefer TLS MQTT and restrict or firewall plain MQTT.</p><p>6. Add HiveMQ authorization rules for topic-level permissions.</p><p>7. Replace wildcard subscriptions with the smallest required topic filters.</p><p>8. Validate sensor payloads with an explicit schema.</p><p>9. Add rate limiting and auditing that never records secrets.</p><p>10. Use cryptographically strong, collision-resistant user and API-key identifiers.</p><p>11. Add tests for registration, authentication, inactive users, malformed JSON, message transformation, and topic generation.</p><p>12. Make broker URL, Django URL, client IDs, topics, and credentials configurable.</p><p>13. Rotate every credential that has ever been committed to source or logs.</p><p><strong>8. What the project demonstrates</strong></p><p>The project is a practical example of extending a broker without embedding application-specific credential logic into the broker itself. HiveMQ owns MQTT protocol handling, connection lifecycle, subscriptions, retained messages, and listener management. The Java extension adapts HiveMQ’s authentication hook to an HTTP API. Django owns credential records and organization metadata. PostgreSQL persists credentials and raw messages. Python provides application-level message processing and Home Assistant integration.</p><p>The resulting division of responsibility is:</p><p>| Component | Responsibility |</p><p>| — -| — -|</p><p>| HiveMQ | MQTT transport, client sessions, routing, retained messages |</p><p>| Java extension | Translate MQTT authentication into a Django request |</p><p>| Django | Credential lookup, active-state check, connection timestamp, registration API |</p><p>| PostgreSQL | Credential and raw event persistence |</p><p>| Python worker | Store selected raw MQTT events |</p><p>| Python mediator | Convert sensor events to retained Home Assistant topics |</p><p>| Home Assistant | Consume discovery and state topics |</p><p>The most accurate summary is not that Django is the MQTT broker or that the token is already an API key. The broker remains HiveMQ, Django is the authentication authority, the Java extension is the broker integration point.</p><p>Happy learning !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f44c50a11b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Shipment Registration from Incoming Emails Using n8n and AI]]></title>
            <link>https://medium.com/@jeetlimbachiya1999/automating-shipment-registration-from-incoming-emails-using-n8n-and-ai-16da6f6dbb12?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/16da6f6dbb12</guid>
            <category><![CDATA[n8n-workflow-automation]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 06:50:15 GMT</pubDate>
            <atom:updated>2026-09-11T06:50:15.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Freight and logistics companies receive a significant number of shipment requests through email. A customer may send an email containing pickup details, delivery locations, pallet counts, cargo information, weight, hazardous-material details, and reference numbers.</p><p>Traditionally, an employee must read the email, understand the shipment request, manually enter the information into a freight management system, and confirm that the shipment has been registered.</p><p>Although this process appears straightforward, it introduces several operational challenges:</p><ul><li>Shipment emails are written in different formats.</li><li>Customers use unstructured language.</li><li>Important information may be buried inside long email conversations.</li><li>Manual data entry can introduce errors.</li><li>Hazardous material information requires additional attention.</li><li>Automatically registering incorrect information can create operational or compliance issues.</li><li>A fully automated AI workflow without human validation may create unwanted shipment records.</li></ul><p>This article explains an end-to-end workflow built using n8n, Microsoft Outlook, an AI-powered information extraction node, human approval, and PostgreSQL.</p><p>The workflow follows a controlled automation model:</p><p><strong>Incoming Email</strong> → <strong>AI Analysis</strong> → <strong>Shipment Detection</strong> → <strong>Structured Data Extraction</strong> → <strong>Human Approval</strong> → <strong>Database Registration</strong> → <strong>Email Cleanup</strong></p><p>The important design principle is that AI does not directly create shipment records. Instead, AI extracts and structures the information, while a human remains responsible for approving the final registration.</p><h3>The Business Problem</h3><p>Consider a freight company that receives shipment requests through an Outlook mailbox.</p><p>A customer might send an email like this:</p><p><strong><em>From: </em></strong><a href="/service/mailto:logistics@fedricks-llp.com"><em>logistics@fedricks-llp.com</em></a><strong><em><br>Subject: </em></strong><em>New shipment booking — Ohio to Toronto</em></p><p><em>Hi team, we’d like to register a new shipment.<br>Shipper: Fedricks LLP.<br>Pickup from Columbus, Ohio, USA.<br>Deliver to Toronto, Canada.<br>Cargo: 12 pallets of industrial solvents (UN1993, flammable).<br>Total weight approximately 4,200 kg.<br>Ready for pickup on 2026–09–15.<br>Our reference: PO-88231.<br>Thanks.</em></p><p>A human can easily understand this request. However, software cannot reliably process it using simple rules because the same information could be written in hundreds of different ways.</p><p>For example, customers might write:</p><ul><li>“Pickup is in Columbus.”</li><li>“Collect the shipment from our Ohio facility.”</li><li>“Origin location: Columbus, OH.”</li><li>“Goods are ready for collection in Columbus.”</li></ul><p>Similarly, weight could be written as:</p><ul><li>4200 kg or 4200 kilograms,</li><li>Approx. 4.2 tons,</li><li>Weight: four thousand two hundred kg</li></ul><p>A traditional rule-based parser would require a large number of conditions and regular expressions.</p><p>This is where an AI-powered extraction layer becomes useful.</p><h3>Step One: New Email in Outlook</h3><h4><strong>Node Type: Microsoft Outlook Trigger</strong></h4><p>The Outlook Trigger is the entry point of the workflow.</p><p>Its responsibility is to continuously monitor the configured Outlook mailbox and detect new incoming emails.</p><p>In this workflow, the trigger is configured to poll the mailbox every minute.</p><pre>Polling Frequency:<br>Every Minute</pre><p>The trigger only processes unread emails.</p><pre>Read Status:<br>Unread</pre><p>This prevents emails that have already been processed from being picked up again.</p><p>The workflow retrieves important fields from the email, including:</p><ul><li>Message ID</li><li>Subject</li><li>Sender</li><li>Email body</li><li>Received date and time</li><li>Read status</li></ul><p>For the example shipment request, the output would look approximately like this:</p><pre>{<br>  &quot;id&quot;: &quot;AAMkAGI2...==&quot;,<br>  &quot;subject&quot;: &quot;New shipment booking — Ohio to Toronto&quot;,<br>  &quot;from&quot;: {<br>    &quot;emailAddress&quot;: {<br>      &quot;address&quot;: &quot;logistics@fedricks-llp.com&quot;<br>    }<br>  },<br>  &quot;body&quot;: {<br>    &quot;content&quot;: &quot;Hi team, we&#39;d like to register a new shipment...&quot;<br>  },<br>  &quot;receivedDateTime&quot;: &quot;2026-09-10T09:15:00Z&quot;,<br>  &quot;isRead&quot;: false<br>}</pre><p>At this point, n8n has not yet determined whether this is a shipment request.</p><p>It could be:</p><ul><li>A shipment booking</li><li>A customer question</li><li>A complaint or A newsletter</li><li>An automated notification</li><li>Spam</li><li>A reply to an existing conversation</li></ul><p>Therefore, the next stage uses AI to understand the content.</p><h3>Step Two: Extract Shipment Data Using AI</h3><h4>Node Type: <strong>Information Extractor</strong></h4><p>The Information Extractor node is connected to an AI model, such as an OpenAI Chat Model, or a Gemini chat model.</p><p>Its job is not simply to answer questions. Instead, it performs a structured extraction task.</p><p>The incoming email is transformed into a prompt containing information such as:</p><pre>Subject: New shipment booking — Ohio to Toronto</pre><pre>From: logistics@fedricks-llp.com</pre><pre>Email Body:</pre><pre>Hi team, we&#39;d like to register a new shipment.</pre><pre>Shipper: Fedricks LLP.<br>Pickup from Columbus, Ohio, USA.<br>Deliver to Toronto, Canada.<br>Cargo: 12 pallets of industrial solvents (UN1993, flammable).<br>Total weight approx 4,200 kg.<br>Ready for pickup on 2026-09-15.<br>Our reference: PO-88231.</pre><p>The AI model then analyzes the text.</p><p>Instead of returning a paragraph, the Information Extractor forces the AI to produce structured fields.</p><p>The extraction schema includes:</p><p>FieldPurposeis_shipment_registrationDetermines whether the email is requesting shipment registrationshipper_nameName of the customer or shipperoriginPickup locationdestinationDelivery locationcargo_descriptionDescription of goodsweightShipment weightpiecesNumber of pallets, boxes, or other unitsready_dateDate shipment is readyreference_numberCustomer reference or PO numberhazmatIndicates whether dangerous goods are involved</p><p>For the example email, the LLM may generate:</p><pre>{<br>  &quot;output&quot;: {<br>    &quot;is_shipment_registration&quot;: true,<br>    &quot;shipper_name&quot;: &quot;Fedricks LLP&quot;,<br>    &quot;origin&quot;: &quot;Columbus, Ohio, USA&quot;,<br>    &quot;destination&quot;: &quot;Toronto, Canada&quot;,<br>    &quot;cargo_description&quot;: &quot;12 pallets of industrial solvents (UN1993, flammable)&quot;,<br>    &quot;weight&quot;: &quot;4200 kg&quot;,<br>    &quot;pieces&quot;: &quot;12 pallets&quot;,<br>    &quot;ready_date&quot;: &quot;2026-09-15&quot;,<br>    &quot;reference_number&quot;: &quot;PO-88231&quot;,<br>    &quot;hazmat&quot;: true<br>  }<br>}</pre><p>This transformation is one of the most important parts of the workflow.</p><p>The AI has converted unstructured human language into a machine-readable JSON structure.</p><h3>Step Three: Determine Whether the Email Is Actually a Shipment Request</h3><h4>Node Type: <strong>IF Node</strong></h4><p>The next node acts as the first decision gate.</p><p>The condition checks:</p><pre>output.is_shipment_registration === true</pre><p>The workflow now has two possible paths.</p><h4>Path 1: TRUE</h4><p>The email is identified as a shipment registration request.</p><p>The workflow continues toward human approval.</p><h4>Path 2: FALSE</h4><p>The email is not a shipment registration request.</p><p>The workflow does not send anything to the database.</p><p>Instead, the email is marked as read. (or We can keep it as unread for manual review)</p><p>This is important because an AI workflow should not assume that every email arriving in a logistics inbox represents a new shipment.</p><p>Examples of emails that may go through the FALSE path include:</p><ul><li>“Can you provide the status of shipment ABC123?”</li><li>“Thank you for your assistance.”</li><li>Marketing newsletters</li><li>Automated system notifications</li><li>Customer complaints</li><li>Delivery confirmations</li></ul><p>For our example:</p><pre>&quot;is_shipment_registration&quot;: true</pre><p>Therefore, the workflow proceeds to the human approval stage.</p><h3>Step Four: Human Approval Before Registration</h3><h4>Node Type: <strong>Outlook Send and Wait for Response</strong></h4><p>This is the human-in-the-loop component of the workflow.</p><p>Rather than immediately inserting the AI-generated data into the shipment database table, n8n sends an approval request.</p><p>The approval email can contain:</p><pre>Shipment Registration Approval Required</pre><pre>Shipper:<br>Fedricks LLP</pre><pre>Origin:<br>Columbus, Ohio, USA</pre><pre>Destination:<br>Toronto, Canada</pre><pre>Cargo:<br>12 pallets of industrial solvents (UN1993, flammable)</pre><pre>Weight:<br>4200 kg</pre><pre>Pieces:<br>12 pallets</pre><pre>Ready Date:<br>2026-09-15</pre><pre>Reference:<br>PO-88231</pre><pre>Hazmat:<br>Yes</pre><pre>Original Sender:<br>logistics@fedricks-llp.com</pre><p>The approver receives options such as:</p><pre>Approve &amp; Register</pre><pre>Reject</pre><p>The workflow pauses while waiting for the response.</p><p>This is significantly different from a normal email node.</p><p>The workflow may be configured with a maximum wait time, such as 2 days and during this period, the workflow execution remains in a waiting state.</p><p>This provides a critical safety mechanism.</p><p>AI can extract information, but the final business decision remains with a human.</p><p>This approach is particularly valuable for freight operations because incorrect data may lead to:</p><ul><li>Incorrect routing</li><li>Pricing errors</li><li>Pickup failures</li><li>Incorrect customs documentation</li><li>Dangerous goods compliance issues</li><li>Duplicate shipments</li></ul><p>For hazardous cargo, human approval becomes even more important.</p><p>In the example email:</p><pre>UN1993<br>Flammable</pre><p>These are strong indicators that additional verification may be required before operational processing.</p><h3>Step Five: Check Whether the Shipment Was Approved</h3><h4>Node Type: <strong>IF Node</strong></h4><p>After the human responds, the workflow resumes.</p><p>The approval response may look similar to:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;approved&quot;: true<br>  }<br>}</pre><p>The IF node checks:</p><pre>data.approved === true</pre><p>Again, there are two branches.</p><h4>Approved</h4><p>If the response is approved</p><h4>Rejected</h4><p>If the response is rejected then no shipment record is created.</p><p>This creates a controlled operational workflow where AI assists with data processing but does not independently create business records.</p><h3>Step Six: Normalize and Validate Data Before Database Insertion</h3><p>This is an extremely important stage.</p><p>The extracted AI output should not always be inserted directly into a relational database.</p><p>Consider the weight from our example:</p><pre>&quot;weight&quot;: &quot;4200 kg&quot;</pre><p>From a human perspective, this is perfectly understandable.</p><p>However, suppose the PostgreSQL database column is:</p><pre>weight NUMERIC</pre><p>PostgreSQL expects something similar to:</p><pre>4200</pre><p>It does not expect:</p><pre>4200 kg</pre><p>Therefore, inserting the original AI output directly may cause an error.</p><p>For example:</p><pre>invalid input syntax for type numeric</pre><p>This is not necessarily an AI problem.</p><p>It is a data contract problem between the AI extraction layer and the database schema.</p><p>The AI has correctly extracted a human-readable value.</p><p>The database requires a machine-compatible numeric value.</p><p>Therefore, a production workflow should introduce a normalization stage. which normalize the output like below example:</p><h4>AI Output</h4><pre>{<br>  &quot;weight&quot;: &quot;4200 kg&quot;,<br>  &quot;pieces&quot;: &quot;12 pallets&quot;<br>}</pre><h4>Normalized Output</h4><pre>{<br>  &quot;weight_value&quot;: 4200,<br>  &quot;weight_unit&quot;: &quot;kg&quot;,<br>  &quot;pieces_value&quot;: 12,<br>  &quot;pieces_type&quot;: &quot;pallets&quot;<br>}</pre><p>This can be achieved using an n8n Code node, Set node, or additional structured extraction rules.</p><h3>Step Six: Register Shipment in PostgreSQL</h3><h4>Node Type: <strong>PostgreSQL Node</strong></h4><p>Once approval is received and the data has been validated, the workflow inserts the shipment into the database.</p><p>The destination table is using postgreSQL database:</p><pre>public.shipment_detail</pre><p>The workflow retrieves the original AI extraction data.</p><p>This is necessary because the approval node’s output typically contains the approval result, not the complete shipment details.</p><p>For example, an expression may reference:</p><pre>$(&#39;Extract Shipment Data&#39;)</pre><p>The database mapping may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*e6K4gHAZpQrCSPAPjV7Udw.png" /></figure><p>For the example shipment:</p><pre>source_address:<br>Columbus, Ohio, USA<br><br>destination_address:<br>Toronto, Canada<br><br>hazmat:<br>true<br><br>weight:<br>4200</pre><p>The shipment ID may be automatically generated by PostgreSQL.</p><p>For example:</p><pre>SERIAL</pre><p>or:</p><pre>GENERATED ALWAYS AS IDENTITY</pre><p>The resulting conceptual record might look like:</p><pre>Shipment_id: 10542<br><br>Source Address:<br>Columbus, Ohio, USA<br><br>Destination Address:<br>Toronto, Canada<br><br>Weight:<br>4200<br><br>Hazmat:<br>True</pre><p>At this point, the shipment registration process is complete.</p><h3>Step Seven: Mark the Original Email as Read</h3><p>The workflow contains multiple Outlook nodes responsible for marking the original email as read.</p><p>This is essential for preventing duplicate processing.</p><p>There are typically three cleanup paths.</p><h4>Mark Read: Registered</h4><p>This node runs after a successful database insert.</p><pre>Database Insert Successful<br>        │<br>        ▼<br>Mark Original Email as Read</pre><p>This indicates that the shipment request has been successfully processed.</p><h4>Mark Read: Rejected</h4><p>This node runs when the human rejects the shipment registration.</p><pre>Rejected<br>   │<br>   ▼<br>Mark Email as Read</pre><p>No database record is created.</p><p>However, the email is marked as processed so that it does not trigger the workflow again.</p><h4>Mark Read: Not a Shipment</h4><p>This node runs when AI determines that the email is not a shipment registration request.</p><pre>Not a Shipment<br>      │<br>      ▼<br>Mark Email as Read</pre><p>Again, this prevents repeated processing.</p><h3>Conclusion:</h3><p>The key architectural advantage is the balance between automation and control.</p><p>AI handles the difficult task of understanding unstructured emails. n8n orchestrates the movement of data and workflow logic. PostgreSQL stores the approved shipment information. The human approver remains responsible for the final business decision.</p><p>This approach provides a practical path toward intelligent freight automation without immediately introducing the risks associated with fully autonomous AI-based shipment registration.</p><p>Do like and comment on what you want to learn next, till than</p><p>Happy learning !!! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16da6f6dbb12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Local RAG Chatbot from Scratch: Architecture, Tools, and Debugging Journey]]></title>
            <link>https://towardsdev.com/building-a-local-rag-chatbot-from-scratch-architecture-tools-and-debugging-journey-d3f526cb1a2b?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f526cb1a2b</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 14:42:49 GMT</pubDate>
            <atom:updated>2025-08-21T14:53:58.432Z</atom:updated>
            <content:encoded><![CDATA[<p>In this technical blog, we will walk through the process of building a Retrieval-Augmented Generation (RAG) chatbot using local tools, addressing challenges encountered, and explaining the core technologies involved. This guide is intended for developers who want a deep understanding of how RAG pipelines work and how to build scalable, flexible solutions with local LLMs.</p><h3>What is an LLM (Large Language Model)?</h3><p>A <strong>Large Language Model (LLM)</strong> is a machine learning model trained on massive text corpora to understand, generate, and manipulate human language. These models, such as GPT, Mistral, or LLaMA, can answer questions, summarize content, generate code, and more.</p><h3>Why do we need an LLM?</h3><p>· To understand user queries</p><p>· To generate meaningful answers from knowledge sources or vector DB</p><p>· To provide a natural language interface</p><p>Mojorly projects use <strong>Mistral 7B</strong>, a fast and open-weight LLM, which serve’s locally via <strong>Ollama</strong>.</p><h3>What is HuggingFace?</h3><p><strong>HuggingFace</strong> is a platform and library that provides access to thousands of open-source models, datasets, and tools in NLP. We used the HuggingFace transformers and sentence-transformers models (like all-MiniLM-L6-v2) to generate vector embeddings.</p><h3>Why is HuggingFace used?</h3><p>· To convert textual data into high-dimensional embeddings</p><p>· To enable semantic search for relevant chunks in the vector database</p><h3>What is RAG (Retrieval-Augmented Generation)?</h3><p><strong>RAG</strong> is a technique that combines retrieval-based methods with generative models. It retrieves relevant documents from a knowledge base and feeds them as context to an LLM to generate an accurate response.</p><h3>RAG Architecture:</h3><p>1. <strong>Retriever</strong>: Finds relevant documents based on the query</p><p>2. <strong>Generator</strong>: LLM uses these documents to answer the question</p><h3>Benefits of RAG:</h3><p>· Better factual accuracy</p><p>· Real-time domain-specific knowledge</p><p>· Reduced hallucination</p><h3>What is ChromaDB?</h3><p><strong>ChromaDB</strong> is an open-source vector database that stores and retrieves document embeddings. It supports fast similarity searches.</p><h3>Why use ChromaDB?</h3><p>· Local storage and fast retrieval of embeddings based on similarity (cosine similarity)</p><p>· No need for cloud APIs or internet access</p><p>· Integration with LangChain retrievers</p><h3>LangChain and its Role</h3><p><strong>LangChain</strong> is a framework for building LLM applications. It helps structure chains (pipelines) combining LLMs, retrievers, prompts, and memory.</p><h3>Key LangChain modules used:</h3><p>· RetrievalQA: For RAG implementation</p><p>· Document: To represent content chunks</p><p>· MarkdownTextSplitter: To split large texts into manageable chunks</p><p>· Ollama: To access local LLMs</p><p>· Chroma: Vector store wrapper</p><h3>Selenium-Based Crawler</h3><p>To gather data from websites, we built a custom crawler using <strong>Selenium</strong> to support :</p><p>· Handling multi-page structures</p><p>· Converting HTML into Markdown</p><p>· Storing results in .json and .docx files</p><h3>Project Structure and Modules</h3><h3>1. Python file to convert text into documents</h3><p>· Cleans and chunks text using regex and MarkdownTextSplitter</p><p>· Outputs LangChain Document objects with metadata</p><h3>2. utils.py</h3><p>· Wraps crawling, embedding, and storage logic</p><p>· Stores documents in ChromaDB using HuggingFace embeddings</p><h3>3. pipeline.py</h3><p>· Main execution file</p><p>· Loads cache, embeds data, and runs RAG pipeline for Q&amp;A</p><h3>4. prompt.py</h3><p>· Custom prompt template for controlling how LLM responds</p><p>· Enforces the rule: “Don’t make up information.”</p><h3>Debugging Journey: What Wasn’t Working?</h3><h3>Initial Problems:</h3><p>· Embedding step was skipped due to embed=False</p><p>· all_docs was empty due to markdown key being missing or blank</p><p>· ChromaDB failed with Expected IDs to be a non-empty list</p><p>· Retrieval returned no results — queries failed</p><h3>Fixes Implemented:</h3><p>· Added logs to verify markdown and document chunking</p><p>· Verified and cleaned input text to avoid empty documents</p><p>· Used embed=True to trigger storage</p><p>· Rewrote prompt and RetrievalQA to correctly pass context</p><p>· Ensured retriever search_kwargs={“k”: 4} returns enough results</p><h3>Sample Output</h3><p>Ask anything about the website. Type ‘exit’ to quit.<br> Your question: What QA and Testing services are provided by your compnay?<br> <br> Answer:<br> It provides end-to-end Quality Assurance and Software Testing services including manual, automation, and performance testing.</p><h3>Final Working Flow</h3><p>1. Crawl the site and extract markdown</p><p>2. Clean and split markdown into document chunks</p><p>3. Embed documents with HuggingFace</p><p>4. Store vectors in ChromaDB</p><p>5. User asks question ➝ Retriever gets relevant chunks ➝ Mistral answers</p><h3>Learnings &amp; Best Practices</h3><p>· Always validate your document content before embedding</p><p>· Add debug logs in embedding and retrieval pipeline</p><p>· Use local models (Ollama, Chroma, HuggingFace) for privacy</p><p>· Design prompts carefully to avoid hallucinations</p><p>· Cache crawl data to avoid redundant scraping</p><h3>Future Enhancements</h3><p>· Add PDF, DOCX, and other file format support</p><p>· UI interface for non-developers</p><p>· Multiple model switching (OpenAI, Gemini, LLaMA)</p><p>· Auto-retrain embeddings if content changes</p><p>By combining flexible open-source tools and rigorous debugging, we successfully built a fast, private, and domain-specific RAG chatbot capable of answering any website-related questions accurately.</p><p>Happy Building!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f526cb1a2b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/building-a-local-rag-chatbot-from-scratch-architecture-tools-and-debugging-journey-d3f526cb1a2b">Building a Local RAG Chatbot from Scratch: Architecture, Tools, and Debugging Journey</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating CI/CD pipeline between Github action and EC2 on the AWS server.]]></title>
            <link>https://towardsdev.com/creating-ci-cd-pipeline-between-github-action-and-ec2-on-the-aws-server-d26798c5c6cc?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/d26798c5c6cc</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 16:27:47 GMT</pubDate>
            <atom:updated>2022-11-21T14:10:49.927Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s a CI/CD pipeline?</h3><p>A pipeline is a process that drives software development through a path of building, testing, and deploying code, also known as CI/CD. By automating the process, the objective is to minimize human error and maintain a consistent process for how software is released. Tools that are included in the pipeline could include compiling code, unit tests, code analysis, security, and binaries creation.</p><p>CI/CD is the backbone of a DevOps methodology, bringing developers and IT operations teams together to deploy software.</p><h3>What’s a Github actions?</h3><p>GitHub Actions is <strong>a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline</strong>. You can create workflows that build and test every pull request to your repository, or deploy merged pull requests to production.</p><p>Pre-requistes:</p><ul><li>Github actions</li><li>AWS account</li><li>IAM role</li></ul><p><strong>Step 1: Go to AWS console</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*L1Y42Xcn_-1gDqBdsNAHZA.png" /></figure><p><strong>Step 2: Now you need to go to the EC2 console. So type EC2 in the search bar.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UZRfoZCWus2EIWFRGNYu6A.png" /></figure><p><strong>Step 3: Head on to the Instance in which you want to set up an automated CI/CD pipeline.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*WDHAD2sYR92I5KlY2KPG1w.png" /></figure><p><strong>Step 4 : Now you need to provide some important permissions to the instance. So move to IAM role and open the console</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cbIkYI7jVd7J_0k_HrtAXg.png" /></figure><p><strong>Step 5: Now here to this role you have to assign the permissions via policies. So, under “Add Permissions” select “Attach policies” and search about “AmazonEC2FullAccess” and click on “Attach policies”. You will get something like above snapshot.</strong></p><p><strong>Step 6: Now you can review your IAM role attached to your instance with the latest assigned permission.</strong></p><p><strong>Step 7: Now you should move to the github account and it’s repository on which you would like to setup CI/CD pipeline.</strong></p><p><strong>Step 8: Open the github account, move to the repository on which you would like to establish CI/CD.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Kq3cO6diHHR0pYQCd13Qug.png" /></figure><p><strong>Step 9: Head on to the settings of that repository</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*qTpkvUZZ2xlw-7QIfGWS5g.png" /></figure><p><strong>Step 10: You need to create three secrets and put the values you kept from the IAM user creation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*B4QBdntyzAyemmUHzCDZlw.png" /></figure><p><strong>Step 11: Now as you have credentials ready, let’s quickly head on to the workflow file building.</strong></p><p><strong>Step 12: Go back to the repository and you can click on “Actions” on the bar at the top and click on the “set up a workflow yourself” appears as a link in blue color</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*35hKU9DEpRfmZGcEwRneSQ.png" /></figure><p><strong>Step 13: After you click on that link, you will get the below snapshot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*dSUCb96CmbRWGv2tlrX8OA.png" /></figure><p><strong>Step 14: Now here you need to specify the workflow of how you would like to process with the file when any changes is committed to the repository in the same branch, you would need to work as per your requirement, but I will give you a sample as per my requirements.</strong></p><p><strong>Note: My pipeline will trigger, if any changes/modification is committed to the repository in the main branch, then checks the changes to the server and modifies the code in the server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*owRWJfufIDYi3PS1dcu3dQ.png" /></figure><p><strong>Step 15: Now as I have build a “.yml file” (workflow file) in the github repository, so, I have to run some of the commands in the server to accept the provisioning of the workflow file from the github.</strong></p><p><strong>Step 16: So, you need to go to the “settings” of your repository and click on the “Actions” dropdown in the left pane and select “Runners”.</strong></p><p><strong>Step 17: Now hit on “New self-hosted runner” and follow the steps given as per the OS you are working on. Below is a reference snapshot.</strong></p><p><strong>Note: In my case, I am working on ubuntu instance so, I am following Linux commands on the EC2 ubuntu instance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fRrU8OQRzPoj1KUvKKj80g.png" /></figure><p><strong>Step 18: So now as you fire the last command “./run.sh” you will get the below snapshot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*k-qVzJWm-Gx38ub4vi4MTQ.png" /></figure><p><strong>Step 19: Now, if you modify your repo, then automatically the changes will be deployed to the server as per the workflow file we have specified in the github repo. We can also track the process.</strong></p><p><strong>Step 20: To track the current progress, we need to move to “Actions” and select the latest pipeline. Below are the sample ref.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DuGZJsiWPCkaPXXEiSapUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*XAWL-16GI6KBIU2w_qz2eg.png" /></figure><p><strong>Step 21: Now, here you would need to provide the credentials of your github account because you are asked in the server. So you need to give the username and authentication token for your account.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*DEOTX0q2-_l1Ymi7O3hnfg.png" /></figure><p><strong>Once you specify the credentials, you will see the success output in the console and same can be verified over “Actions” at the top in the repository in your github account.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UFtvLVc7t231yEskNjavfQ.png" /></figure><p><strong><em>Congratulations</em></strong><em>!!! 😊 You have successfully build the pipeline in the server.</em></p><p><em>Stay tuned for more updates/tutorials regarding AWS, Devops, MLops things.</em></p><p><em>Happy Learning !!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d26798c5c6cc" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/creating-ci-cd-pipeline-between-github-action-and-ec2-on-the-aws-server-d26798c5c6cc">Creating CI/CD pipeline between Github action and EC2 on the AWS server.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing AWS instances if “.Pem Key/File” is lost.]]></title>
            <link>https://towardsdev.com/accessing-aws-instances-if-pem-key-file-is-lost-2a7f4dca4f89?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a7f4dca4f89</guid>
            <category><![CDATA[recovery]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ubuntu-server]]></category>
            <category><![CDATA[ec2-instance-connect]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 17:24:17 GMT</pubDate>
            <atom:updated>2022-11-21T14:10:35.889Z</atom:updated>
            <content:encoded><![CDATA[<p>In a hypothetical scenario if you misplaced/lost the .pem key for an AWS linux/ubuntu instance and you would like to access your server for any purpose then can we get it ?</p><p>So today we are going to cover the scenario of recovering access to an AWS instance if the .pem file for the instance is lost.</p><p>Some of us might have faced this issue, if not all. 😊</p><p>Suppose we have an instance whose .pem file is lost, destroyed, etc. We know that an AWS instance is secured with .pem file, sadly we can’t regenerate this .pem file from the AWS again ☹.</p><p>This post highlights the steps needed to recover the access to your AWS EC2 Instance after losing or misplacing your SSH .pem key-pair file.</p><p><strong>Note</strong>: The below process requires a stop and start of your AWS Instance thus It can only be done on an <strong>EBS backed instance.</strong> It is not possible to do this procedure on store-backed instances.</p><p><strong>What is a key-pair file?</strong></p><p>If you are asking this yourself, then maybe this post is not the right one for you. <strong>However</strong>, a key-pair is a combination of a public and private key. Amazon EC2 uses public-key cryptography to encrypt and decrypt login information.</p><p>Very often people lost access to their AWS EC2 Instances. This can happen for many different reasons such as switching to a new computer, losing one’s files, becoming responsible for someone else’s AWS deployments and much more. When this happens, there is a need to recover access to these instances.</p><p>We will be needing a new instance to recover the .pem file for our lost instance. So, let’s call this new instance as <strong>recovery instance</strong> and lost instance as <strong>Primary instance.</strong></p><p>We can gain access to the instance in case of missing “.pem key” using a technique called <strong><em>volume exchange.</em></strong></p><p>Step 1: Suppose you have one server called primary instance/server. (let’s say it is production) server to be recovered via volume exchange.</p><p>Step 2: Create a recovery server.</p><p>Step 3: Now we have to choose appropriate details for launching instance from generated AMI, as it will create a new instance/server for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZzeeNK8irQaIG_PfUP2j7Q.png" /></figure><p>Step 4: Details like VPC, Subnet needs to be selected properly from the Configured Instance option (see below screenshot for reference) and after that select Add Storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*8BUMYBiDvKvExc5NAuKn3A.png" /></figure><p>Step 5: Choose to create a new key pair, provide a name for the key pair and launch the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Fx02uI-xXIwSBqO78HDdXQ.png" /></figure><p>Step 6: Download the key pair before we try to use that with our SSH connection.</p><p>Step 7: Stop the prod/primary server and remove/detach the root volume of the prod server. (make a note of root device attachment e.g. here it is dev/xvda)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*S-U29PWoiawofoe_qRyrkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5l2M4TMxJMxGMsG0JeZmNw.png" /></figure><p>Step 8: Attach that primary/prod server volume(root volume) as secondary to your recovery server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fWBrOrU0PD5Ae7MZ0uCq6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*QNSnPequGw4o2u4WFCjm3Q.png" /></figure><p>Step 9: · Login to recovery server and go to the volume of prod/primary server which is attached as secondary here, find out available volumes using below command.</p><p><strong><em>$ lsblk -f</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*AY1SjIgIFW6DSpyrmDrG5A.png" /></figure><p>Create new directory for the mount purpose</p><p><strong><em>$ sudo mkdir /tmp/tmpvolume</em></strong></p><p>To mount on old Amazon Linux/ubuntu:</p><p><strong><em>$ sudo mount /dev/xvdf1 /tmp/tmpvolume</em></strong></p><p>To mount on new Amazon Linux/ubuntu:</p><p><strong><em>$ sudo mount -o nouuid /dev/xvdf1 /tmp/tmpvolume</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*VLrY99Hp0y8RGhIM81n43A.png" /></figure><p>Step 10: Copy the recovery instance’s private key to the mounted volume of Primary/prod Instance authorized_keys and you can see the same via cat command.</p><p><strong><em>$ cp .SSH/authorized_keys /tmp/tmpvolume/home/ec2-user/.SSH/</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*BWAezvjjeorYEdNquRt4sA.png" /></figure><p>Step 11: Unmount and detach the volume that we mounted as secondary from the Recovery server.</p><p>Step 12: Command for unmount:</p><p><strong><em>$ sudo umount /tmp/tmpvolume</em></strong></p><p>For Detaching the Volume:</p><p>Step 13: Select the volume , Right click and select Detach volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UhoRxL1jMnkmEPfbooTyTg.png" /></figure><p>Step 14: Click on the Yes, Detach button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gE3wlxR1WjChNZQfuqGdnA.png" /></figure><p>Step 15: · Attach the volume back to the prod server as root volume. (e.g. dev/xvda)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*_SWPBlxNptVlqnM5ep7nkA.png" /></figure><p>Step 16: Start the prod server again.</p><p>Step 17: Try to SSH via the newly copied private key, In this case login to the Primary server with the Recovery server’s pem file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z4WR8gVadTJD63va.png" /></figure><p><em>Below is a summary of the steps required and covered in the post to recover access to your EC2 Instance after losing your key-pair.</em></p><p>· <em>Gather config details of the original(</em><strong><em>primary</em></strong><em>) instance.</em></p><p>· <em>Power off the original(</em><strong><em>primary</em></strong><em>) EC2 instance of which you want to regain access.</em></p><p>· <em>Launch new (</em><strong><em>recovery</em></strong><em>) instance and generate new key-pair</em></p><p>· <em>Login via SSH to the new recovery instance</em></p><p>· <em>Detach the primary EBS volume from original(</em><strong><em>primary)</em></strong><em> instance (taking note of its current attachment)</em></p><p>· <em>Attach/Mount the previously detached volume to the new(</em><strong><em>recovery</em></strong><em>) instance</em></p><p>· <em>Copy authorized keys from recovery instance to the mounted (</em><strong><em>primary</em></strong><em>) volume</em></p><p>· <em>Unmount </em><strong><em>primary</em></strong><em> volume from recovery instance and reattach back to original (</em><strong><em>primary)</em></strong><em> instance using configs noted earlier</em></p><p>· <em>Start the original (</em><strong><em>primary</em></strong><em>) instance and login with new key-pair</em></p><p>· <em>Delete temporary(</em><strong><em>recovery</em></strong><em>) instance</em></p><p><strong><em>Congratulations</em></strong><em>!!! 😊 You have successfully recovered your server.</em></p><p><em>Stay tuned for more updates/tutorials regarding AWS, Devops, MLops things.</em></p><p><em>Happy Learning !!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a7f4dca4f89" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/accessing-aws-instances-if-pem-key-file-is-lost-2a7f4dca4f89">Accessing AWS instances if “.Pem Key/File” is lost.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up conda environment on linux-ubuntu.]]></title>
            <link>https://medium.com/@jeetlimbachiya1999/setting-up-conda-environment-on-linux-ubuntu-b89c27e2e9?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89c27e2e9</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[conda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 16:49:40 GMT</pubDate>
            <atom:updated>2022-10-24T16:49:40.046Z</atom:updated>
            <content:encoded><![CDATA[<p>Miniconda is a free minimal installer for conda. It is a small, bootstrap version of Anaconda that includes only conda, Python, the packages they depend on, and a small number of other useful packages, including pip, zlib and a few others. Use this conda install command to install 720+ additional conda packages from the Anaconda repository.</p><p>On Windows, macOS, and Linux, it is best to install Miniconda for the local user, which does not require administrator permissions and is the most robust type of installation. However, if you need to, you can install Miniconda system wide, which does require administrator permissions.</p><p>It is a free minimal Conda Installer. Broadly, to understand Miniconda is, you can think of it as a tiny, bootstrap version of Anaconda. It comprises Python, Conda, the package they rely on, and a few applicable packages, such as zlib, pip, and others.</p><p>So, let’s jump in. Open the terminal and run the below commands to get the mini-conda in hands.</p><p><strong>Step 1:</strong> First, you need to download the latest shell script. You can do that using the below snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*rAx0wDdXVp4WmwfBQJwGww.png" /></figure><p><strong>Step 2:</strong> Now you need to execute the downloaded scripts. So we, should give the required authority to the downloaded scripts. Here, we are using chmod command. Below is the snapshot for the ref..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DD8lJD4aVeI1riqJDWGU4A.png" /></figure><p><strong>Step 3:</strong> Now, as we have downloaded the script and provide the permissions, we are about to install the scripts. So we should run the installation scripts. Below is the ref. snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*o132cumzBV_PrM2n70D_tQ.png" /></figure><p><strong>Step 4: </strong>Here after executing the above scripts, we are required to configure the miniconda. So, as and when prompted, we need to press “Enter” key repeatedly until we reach input of “yes” or “no”.</p><p>We type “yes” to continue and select the default location. And then again press “Enter”.</p><p><strong>Step 5:</strong> At this point miniconda is installed, we can check the installation pointing in below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*k-8Kjflo3e5jRhXqZANfZQ.png" /></figure><p><strong>Step 6:</strong> Now, we need to activate the conda environment, as we have installed it and we must activate to use it to get isolated virtual environment for our python projects. So we need to type the command specified in below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*KitTttrGyk1IUG3lIbc3pg.png" /></figure><p><strong>Note:</strong> Just in case, you can’t see the (base) environment in the beginning, you need to close and again open the terminal and type above command. You will be getting the conda environment right there.</p><p><strong>Step 7:</strong> Now once your work gets completed so you need to deactivate the environment. So we can do that like below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*NoVKjUA3qnvFgrmRdQYz4A.png" /></figure><p><strong>Step 8:</strong> Now as, you are working on multiple projects you need to create multiple virtual environment with other python versions as required. So, we can do that in below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5sbzjQUZUyMY0EjzUOj0tQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7lkCRwuhnGg8cnkHKHxcOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*J9NHZgGuRSklSK0NepN4Xg.png" /></figure><p><strong>Step 9:</strong> Now you can activate the newly created virtual environment using below snapshot. Like below snapshot you can see the name of virtual environment you are using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*ZciE-FIIOD7saHsNGLlA1Q.png" /></figure><p><strong>Step 10:</strong> After this you can also deactivate the virtual environment in order to use other venv for other projects. So we can do that using below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ZsJPxZnC8mJpWhWWNuBlDQ.png" /></figure><p><strong>Step 11:</strong> You can also check the available list of virtual env. You have created using below snapshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Pd-SyiUVoHL6kzxIfEb4Lw.png" /></figure><p><strong>Step 12:</strong> As our projects get completed we are required to delete the venv. So, we could do that using below ref. image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wbmJCaNHs2jxoAcftLwkyw.png" /></figure><p>That’s all in this blog post.</p><p>Stay tuned for more such an amazing tutorials/lessons regarding AWS, Ubuntu, DevOps, MLOps things.</p><p><strong>Happy learning!!! 😊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89c27e2e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps using Jenkins Pipeline]]></title>
            <link>https://towardsdev.com/mlops-using-jenkins-pipeline-962d60bd715b?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/962d60bd715b</guid>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Sun, 22 May 2022 09:21:03 GMT</pubDate>
            <atom:updated>2022-11-21T14:10:26.930Z</atom:updated>
            <content:encoded><![CDATA[<p>This article covers various ways of organizing Jenkins on your server. Use our informed guide for manual installation or launching Jenkins in Docker containers. Deploy Jenkins on your server in 5 minutes using our control.</p><p>Jenkins benefits:</p><ul><li>Written in Java, and thus you can run it on all platforms</li><li>Has lots of plugins, which can help you solve almost any problem you can imagine.</li><li>Helps developers to integrate code changes and always produce stable software build</li></ul><p>Install Jenkins Manually</p><p>The installation process is simple and straightforward. It consists of several easy steps:</p><ul><li>Java installation.</li><li>Adding official Jenkins repositories to your package manager.</li><li>Package installation.</li><li>Firewall configuration.</li><li>Initial Jenkins configuration.</li></ul><p>Let’s get started,</p><p>First, update the apt package index using this:</p><p>$ sudo apt update</p><p>To be able to run Jenkins, you need to install Java.</p><p>Now, install the default Java OpenJDK package using this:</p><p>$ sudo apt install openjdk-8-jre</p><p>Verify the installation using this command:</p><p>$ java -version</p><p>By the time of this article, Jenkins is using the Java 8 version. If you see another version, switch to the correct one:</p><p>$ sudo update-alternatives — config java</p><p>Add Jenkins repository</p><p>By default, Jenkins is not included in the Ubuntu repositories, and you need to add it.</p><p>First, we need to import the repository key:</p><p>$ wget -q -O — <a href="https://pkg.jenkins.io/debian-stable/jenkins.io.key">https://pkg.jenkins.io/debian-stable/jenkins.io.key</a> | sudo apt-key add -</p><p>Next step is to append the repository address to the server’s repositories list:</p><p>$ sudo sh -c ‘echo deb <a href="https://pkg.jenkins.io/debian-stable">https://pkg.jenkins.io/debian-stable</a> binary/ &gt; \</p><p>/etc/apt/sources.list.d/jenkins.list’</p><p>Once that is done, we need to update the information about the software, which we can use from the new repository:</p><p>$ sudo apt-get update</p><p>Jenkins Package Installation</p><p>Since we have the repository up to date, let’s run the following command:</p><p>$ sudo apt-get -y install jenkins</p><p>Running this command will prompt you to confirm the download and installation.</p><p>By default, Jenkins starts after installation process. If not, use the following command to do it manually:</p><p>$ sudo systemctl start jenkins</p><p>Let check if Jenkins service status:</p><p>$ sudo systemctl status jenkins</p><p>By default, Jenkins runs on port <strong>8080</strong>.</p><p>So this can be done through enabling security group and inbound 8080 port for TCP connection on AWS.</p><p>Then copy your AWS Instance IPV4 : ubuntu@IP.regrion_name.compute.amazonaws.com:8080</p><p>This command results to opening the Jenkins docker container on port <strong>8080.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*hWmMZk1TgkwTmXLOB9M8Mg.png" /><figcaption>Snapshot 1</figcaption></figure><p>Initial password is available here:</p><p>$ sudo cat /var/lib/jenkins/secrets/initialAdminPassword</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*OqO58F1qqxkAQxcYFat0lA.png" /><figcaption>Snapshot 2</figcaption></figure><p>Jenkins Plugins</p><p>At the next screen, you will be required to choose plugins for initial installation. If you do not know which plugins to set up yet, use the “<strong>Install suggested plugins</strong>” option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DClrQdSe3SvI-AR44qEx7A.png" /><figcaption>Snapshot 3</figcaption></figure><p>Select the install suggested plugins</p><p>The below is the screen you will be prompted after clicking on Install Suggested plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*d0KeAL_ZtRkeU1vZd5AI5Q.png" /><figcaption>Snapshot 4</figcaption></figure><p>Thereafter you will be prompted with the below screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Ozku0gHjihEgfFUSL6VkuQ.png" /><figcaption>Snapshot 5</figcaption></figure><p>create first admin user</p><p>We need to create your Jenkins user.</p><p>After successfully entering the user details, you will be directed to the instance configuration page to confirm the URL for the Jenkins instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UKw_wO9132WpCwBKYYAd-g.png" /><figcaption>Snapshot 6</figcaption></figure><p>set your instance configuration or local host</p><p>There after click on save and finish button. The below screen will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*IMfwPEv8u_UIelZZu_EGmg.png" /><figcaption>Snapshot 7</figcaption></figure><p>Jenkins is ready</p><p>To access the Jenkins main dashboard, click the “Start using Jenkins” button. This action will bring you to the main Jenkins interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*J2ViEupVtzKR5x83vLN9xQ.png" /><figcaption>Snapshot 8</figcaption></figure><p>Jenkins home page</p><p>To run MLOps pipeline in Jenkins you need to have Docker installed because in docker we have code dependencies. The complete installation process is described in the Docker official documentation, so we’ll provide the necessary commands here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*bm4qT6xmUkeMvbMGNRso9g.png" /><figcaption>Snapshot 9</figcaption></figure><p>Install the docker by running the code in ubuntu</p><p>Once Docker is successfully installed, you can run the Docker container.</p><p>$ sudo visudio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*D-YTcv6ZQCoJ-KkwyaT9TA.png" /><figcaption>Snapshot 10</figcaption></figure><p>visudio</p><p>$ sudo vi /etc/default/jenkins</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*kM9j4VUN8a86UmenvAWuSw.png" /><figcaption>Snapshot 11</figcaption></figure><p>make jenkins root</p><p>$ sudo service jenkins restart</p><p>Now we should get into EC2 instance and pull GitHub repository of our Machine Learning project.</p><p><a href="https://github.com/aniforverizon/MLOPS-Pipeline-Jenkins.git">git clone https://github.com/aniforverizon/MLOPS-Pipeline-Jenkins.git</a></p><p>Then apply the following commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*3vtuQ46dPKvwXFcVka_4bw.png" /><figcaption>Snapshot 12</figcaption></figure><p>First we will create a container image that has python installed (in addition to all the other libraries which will be necessary for a ML/DL code to run) using Dockerfile.</p><p>Now build dockerfile with new image name. so we run the following command on ubuntu:18.04</p><p>” docker build -t your_imagename:your_tagname .”</p><p>Thereafter go to Jenkins dashboard and click on “New Items” then below screen will be prompted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*talQNgFDNN06yeldgMQ-7w.png" /><figcaption>Snapshot 13</figcaption></figure><p>create job1</p><p>Here enter the name of the job and click on Freestyle project then click on OK Now you need to execute docker container through Jenkins.</p><p>JOB 1 :-</p><p>Jenkins should automatically start the respective container on pre install libraries to deploy code and start training. For that below is the process. Move to the Build Environment and select “Execute shell” enter the command to execute container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Pycp3FDZdhpuU2Yc9HaMGw.png" /><figcaption>Snapshot 14</figcaption></figure><p>Job1 configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*42VGQrupjPSrw5-dzX0M4g.png" /><figcaption>Snapshot 15</figcaption></figure><p>job1 executing the command</p><p>Job 2:</p><p>This job will check the health of the container, if somehow container is stopped then it will restart the container. To do this again create a new item that will check the health of the container from Job1 (MLOPSDocker_Container_Setup).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*mBpfuIk3tx8iIRyApPLIng.png" /><figcaption>Snapshot 16</figcaption></figure><p>Job2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*S7atpmWqgB3k3SrxSJb9pw.png" /><figcaption>Snapshot 17</figcaption></figure><p>job2 write the below code in the command box</p><p>if sudo docker ps -a | grep job2</p><p>then</p><p>exit 0</p><p>else</p><p>sudo docker container run -dir -v /mlops/:/root/mlops/ — name job2 jeet:v1</p><p>exit 1</p><p>fi</p><p>fi</p><p>Job3 :</p><p>This job will start the training for the Machine Learning model if and only if the docker container is in running mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5AvRDkxzS7zdxNNRtylzfQ.png" /><figcaption>Snapshot 18</figcaption></figure><p>job3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*H9r8mCsZBb0zFq0HhFaeNg.png" /><figcaption>Snapshot 19</figcaption></figure><p>Execute the command in job3</p><p>We can check the output for the training process by the following process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*WlS4KZ_FyeUq5RYMWevndQ.png" /><figcaption>Snapshot 20</figcaption></figure><p>To check the output click on console output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JdSwGEDlKHPeGz4JRZirUw.png" /><figcaption>Snapshot 21</figcaption></figure><p>Once the training process is done then here comes mailing service in the picture.</p><p>Job 4:</p><p>This job will trigger the mail regarding your model’s accuracy. It will check the accuracy of the model, if it is below 90% then it will send mail to the developer that the accuracy doesn’t match with the expected accuracy. And then it will trigger next job for tuning hyperparameters. It will also depend on the previous job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*_lwssSEFluTR5BhkIyQ7_A.png" /><figcaption>Snapshot 22</figcaption></figure><p>configuration for job4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Y4SmZERhBYHPboRb4K2T9w.png" /><figcaption>Snapshot 23</figcaption></figure><p>Execute the code in job4</p><p>JOB 5 :</p><p>This job will be responsible for hyperparameter tuning of the model and will make changes in the code in order to achieve the required accuracy. Then send the mail to developer regarding the accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*n0o9mZL8pJU5kKMrlpGtcw.png" /><figcaption>Snapshot 24</figcaption></figure><p>configuration of job5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gZTxYdrXRwDljBu8S3pnWA.png" /><figcaption>Snapshot 25</figcaption></figure><p>execute the code in job5</p><p>To check the accuracy of tuned model we can check the below process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oeVBeoCVseJaWt2qDrFHLA.png" /><figcaption>Snapshot 26</figcaption></figure><p>Once the pipeline is done then you will get the below related dashboard .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*x7utsCEQS1fsWIqreH3PUg.png" /><figcaption>Dashboard of all the jobs</figcaption></figure><p>Happy Learning !!!</p><p>Thank you <a href="https://medium.com/u/639469baf88f">Anubhav Chaturvedi</a> for helping me.</p><p>Thank you for reading and stay tuned for my next technical post!!!</p><p><strong>For anything related to Development ,Coding, Blogging, Tech Documentation you can DM me on </strong><a href="https://www.linkedin.com/in/jeet-limbachiya-1948281b0/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=962d60bd715b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/mlops-using-jenkins-pipeline-962d60bd715b">MLOps using Jenkins Pipeline</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running X server on UBUNTU– 18.04]]></title>
            <link>https://blog.devops.dev/running-x-server-on-ubuntu-18-04-c7689b581c97?source=rss-99398f512698------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7689b581c97</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Jeetlimbachiya]]></dc:creator>
            <pubDate>Sun, 22 May 2022 07:59:58 GMT</pubDate>
            <atom:updated>2022-11-21T16:42:46.217Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a blog, wherein I will show various steps to be followed to run GUI based application on AWS.</p><p>When we talk about AI, computer vision is one of the top applications in people’s minds. Hype aside, I have always been fascinated by it because it pertains to human sight, arguably the most important organ of human sense. I have come across plenty of computer vision projects involving the human face and/or body.</p><p>Computer vision (CV) is a field of Artificial Intelligence (AI) that processes all types of digital images or videos, extracting the relevant information and allowing us to identify some of the elements or objects in those images/videos. To identify these elements, we apply mathematical models that struggle with the pixel positions, colour layers, and the relations between every different neighbourhood or colour of the pixel. All these tasks are made by different algorithmic structures, like decision trees, hashes, neural networks (NN), or graphs, and other techniques, like greedy algorithms, divide and conquer, dynamic algorithms, searching techniques, sorting techniques, etc.</p><p>The reason why I worked on this topic is, I want to run my project on AWS server which has involvement of CV. So, Initially I had a very hard time to run such GUI based video rendering on AWS Instance (server), It took my crucial time in investigating/researching on the topic, then at one novel day when I was doing research one thing catches my eye.</p><p>So, I want community won’t waste time in finding the same.</p><p>So, kindly follow my blog step by step to get GUI based video rendering application to be run on the server. Today, I’ll be showing each and every process from very beginning.</p><p>So, lets get cracking,</p><p><strong>Step 1: </strong>You need to have a AWS account. If you have one you are good to go, if not create one from <a href="https://aws.amazon.com/console/">https://aws.amazon.com/console/</a> and login to console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*vqdTk26A0aX6eb1nPFl4kw.png" /><figcaption>Snapshot 1</figcaption></figure><p><strong>Step 2: </strong>As soon as you will get the console you would have to spin up a EC2 instance, I am using Ubuntu — 18.04 free tier eligible instance (server).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0VkWkBuLVmLtWD88VD3-A.png" /><figcaption>Snapshot 2</figcaption></figure><p>To launch an instance, you need to follow the below specified steps:</p><p>Step 1: Login to the aws console</p><p>Step 2: Choose Launch Instance</p><p>Step 3: Choose AMI</p><p>Step 4: Choose EC2 Instance Types</p><p>Step 5: Configure Instance Details</p><p>Step 6: Add Storage of Ec2 Intance (Storage 30 GB)</p><p>Step 7: Tag Instance of Ec2 Instance</p><p>Step 8: Configure Security Groups</p><p>Step 9: Review Instances</p><p>Step 10: Create Key-Pair For Instance Access (and download pem key)</p><p>Step 11: Type Ec2 Instance Public Ip On Browser</p><p><strong>Step 3: </strong>You need to connect to the instance to access the instance as soon as it comes in running state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9PqSG1FpbVDnzBq2tEpRw.png" /><figcaption>Snapshot 3</figcaption></figure><p>You can connect it by the below command running on shell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKKSGkiD4wO4Vk6wak4vHw.png" /><figcaption>Snapshot 4</figcaption></figure><p>$ ssh -i “pem key(Step 2 è Step 10)” ubuntu@instance_public_IPV4_address And then hit enter. And boom, you will be in the AWS server.</p><p><strong>Step 4: </strong>Now you need to type the below command to update the installed stuffs in the instance.</p><p>$ sudo apt-get update</p><p><strong>Step 5: </strong>You need to install <strong>curl </strong>to download the other dependencies from the internet in the instance.</p><p>$ sudo apt-get wget curl</p><p><strong>Step 6: </strong>Now, If you want, you can also install <strong>Anaconda software </strong>to the instance, by the following gist:</p><p>$ wget <a href="https://repo.continum.io/archieve/Anaconda2-4.1.1-Linux-x86_64.sh">https://repo.continum.io/archieve/Anaconda2-4.1.1-Linux-x86_64.sh</a></p><p><strong>Step 7: </strong>Now you need to install the downloaded anaconda software by following command.</p><p>$ bash Anaconda2–4.1.1-Linux-x86_64.sh</p><p><strong>Step 8: </strong>Thereafter, you need to activate the software by following command.</p><p>$ source .bashrc</p><p><strong>Step 9: </strong>Now check the conda version.</p><p>$ conda –version</p><p><strong>Step 10: </strong>If you already have anaconda installed, you can update to latest version by the below commands.</p><p>$ conda update conda</p><p>$ conda update anaconda</p><p>Now you need to install python latest version in the instance to run the CV projects on the AWS server.</p><p><strong>Step 11: </strong>So, you can do the same by the following command.</p><p>$ conda install python==3.9.0</p><p>If this conda command doesn’t work than don’t worry, I have one another approach to install the same.</p><p>Kindly follow the below steps.</p><p>Step I: $ sudo add-apt-repository ppa:deadsnakes/ppa Step II: $ sudo apt-get update</p><p>Step III: $ apt list | grep python3.9</p><p>Step IV: $ sudo apt-get install python3.9</p><p>Step V: $ sudo update-alternatives –install /usr/bin/python3 python3 / usr/bin/python3.6 1</p><p>Step VI: $ sudo update-alternatives –install /usr/bin/python3 python3 / usr/bin/python3.9 2</p><p>Step VII: $ sudo update-alternatives –config python3 Step VIII: $ python -V</p><p>So, here at this stage we have updated python version from 3.6.1 to the version 3.9. Note: <strong>Optional part </strong>(from Step IX to Step XII)</p><p>If you will get error like below,</p><p>Error: import apt_pkg ModuleNotFoundError: No module named ‘apt_pkg’ Then below are the steps,</p><p>$ sudo apt remove –purge python3-apt</p><p>$ sudo apt autoclean</p><p>$ sudo apt install python3-apt</p><p>$ sudo apt install python3.9-distutils</p><p>$ curl <a href="https://bootstrap.pypa.io/get-pip.py%20-o%20get-pip.py">https://bootstrap.pypa.io/get-pip.py -o get-pip.py</a></p><p>$ sudo python3.9 get-pip.py</p><p>As python version is upgraded, we need to install upgraded dependencies for it as well.</p><p>So, let’s continue with the commands.</p><p>Step IX: $ sudo apt install python3.9-distutils</p><p>Step X: $ pip3 install –upgrade setuptools</p><p>Step XI: $ sudo apt-get install –reinstall python3-apt</p><p>Step XII:$ pip3 install –upgrade distlib</p><p>Now, here comes an interesting step, as we want to run/deploy our <strong>Computer Vision project </strong>on the AWS server.</p><p>So, follow along with me.</p><p><strong>Step 12: </strong>we need to run qt files on the instance, and it requires some dependencies. So, install them by below commands.</p><p>$ sudo apt-get install ffmpeg libsm6 libxext6 -y</p><p>$ sudo apt remove python3-apt</p><p>Now, the punch, the most required thing on the instance to run the GUI based python application on the instance, which is <strong>enabling X — server on the instance.</strong></p><p><strong>Step 13: </strong>You can install x11 by the following command, to enable X11 forwarding to the instance.</p><p>$ sudo apt install x11-apps</p><p>Now you should restart your instance.</p><p><strong>Step 14: </strong>Some required steps to be followed to allow x11 forwarding to the instance are as under. Also, we need to check whether ubuntu has permission or not.</p><p>If ubuntu has permission, it’ll will be seen like at some point like below.</p><p>Ubuntu Ubuntu .Xauthority</p><p>So let’s check the permission by the following command.</p><p>$ ls -la</p><p><strong>Step 15: </strong>If you have permission, then proceed with me by following steps. Step I: $ sudo vi /etc/ssh/sshd_config</p><p>Step II: $ sudo cat /etc/ssh/sshd_config | grep -i X11Forwarding Step III: $ sudo service ssh restart</p><p>Step IV: $ xauth list</p><p>Here after the above command you will be able to see some magic cookies, which means you can now be able to see GUI based video/output from CV project. If you unable to see magic cookie, you can try restarting the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*rVgyxfeYG9jPHXMUyDf8ig.png" /><figcaption>Snapshot 5</figcaption></figure><p><strong>Step 16: </strong>If you do not have permission, I’m here with you, just follow below steps to give permission.</p><p>Step I: $ sudo chown ubuntu:ubuntu .Xauthority</p><p>After above command you would notice something like below at some point. Ubuntu Ubuntu .Xauthority</p><p>Step II: $ mv $HOME/.Xauthority -n /var/tmp/</p><p>Step III: $ mv $HOME/.Xauthority /var/tmp/</p><p>Step IV: $ xauth list</p><p>Here after the above command you will be able to see some magic cookies, which means you can now be able to see GUI based video/output from CV project.</p><p><strong>Step 17: </strong>Now you need to exit/logout your instance by the following command.</p><p>$ exit</p><p><strong>Step 18: </strong>Now again, login to the instance and this time you need to tell your instance explicitly that you have to forward X server for viewing GUI based output of your CV model. The below is the command you must use, if you want to get GUI based output on the instance.</p><p>$ ssh -X -i “pem key” ubuntu@instance_public_IPV4_address -y</p><p><strong>Step 19: </strong>After ssh/accessing your instance you can run your python project of CV by following command.</p><p>$ python3 python file –video video_path</p><p>For example, Suppose I want to detect dog from the video file.</p><p><strong>Step 20: </strong>So below is my command to run python file which takes video path to detect human face.</p><p>$ python3 dog_detection.py –video ./mix _video.mp4</p><p>Happy Learning !!!</p><p>Thank you for reading and stay tuned for our next technical post!!!</p><p><strong>For anything related to Development ,Coding, Blogging, Tech Documentation you can DM me on </strong><a href="https://www.linkedin.com/in/jeet-limbachiya-1948281b0/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7689b581c97" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/running-x-server-on-ubuntu-18-04-c7689b581c97">Running X server on UBUNTU– 18.04</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>