<?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 Mokitha on Medium]]></title>
        <description><![CDATA[Stories by Mokitha on Medium]]></description>
        <link>https://medium.com/@mokithapriyan?source=rss-ff6e0da6d6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GZJTLrgDg5nYMftX</url>
            <title>Stories by Mokitha on Medium</title>
            <link>https://medium.com/@mokithapriyan?source=rss-ff6e0da6d6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:37:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mokithapriyan/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[How I Built a Context-Aware Chatbot Using Vertex AI and Gemini]]></title>
            <link>https://medium.com/@mokithapriyan/how-i-built-a-context-aware-chatbot-using-vertex-ai-and-gemini-c8c391f292ee?source=rss-ff6e0da6d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c391f292ee</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Mokitha]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 15:52:09 GMT</pubDate>
            <atom:updated>2025-06-28T15:53:15.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built a Context-Aware Chatbot Using GCP and Vertex AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgcu5A--F2JDBVm_gdKiBQ.png" /></figure><p>A while ago, I wanted to build a chatbot — not just any chatbot, but one that could actually understand what someone was asking, retrieve meaningful context, and respond intelligently. I didn’t want to hardcode Q&amp;A pairs or rely solely on keyword matching. I wanted it to be smarter.</p><p>So I turned to Google Cloud’s Vertex AI Matching Engine and Gemini 1.5 Pro.</p><p>This post is a walkthrough of how I built a context-aware conversational bot using these tools. It includes the lessons I learned, some stumbles along the way, and the exact steps you can follow — whether you’re comfortable in code or prefer clicking through GCP’s UI.</p><h3>The Idea</h3><p>The goal was simple on the surface:<br> → Let users ask a question<br> → Find the most relevant answers from a knowledge base<br> → Use generative AI to turn those into a thoughtful, human response</p><p>I had structured text data (like FAQs), and I wanted to turn that into something more conversational and intelligent.</p><h3>Step 1: Converting Text into Embeddings</h3><p>Before anything else, I had to make the data understandable to a machine. That means converting each question into a vector — a series of numbers that represent its meaning.</p><p>I used the text-embedding-005 model from Vertex AI for this. It’s actually really straightforward in code:</p><pre>from vertexai.language_models import TextEmbeddingModel<br>embedding_model = TextEmbeddingModel.from_pretrained(&quot;text-embedding-005&quot;)<br>embedding = embedding_model.get_embeddings([&quot;How do I reset my password?&quot;])[0].values</pre><p>Each question turned into a list of 768 floating point numbers.</p><p>This lets the model understand that, say, “reset password” and “forgot login” are similar, even if the words are different.</p><p>Tip: Don’t stop at the question. If you’re building a bot like I did, include answers too. I concatenated relevant answer fields from my dataset to keep the context rich.</p><h3>Step 2: Uploading to Cloud Storage (GCS)</h3><p>Once I had all the embeddings and metadata packaged into a .json file, I needed to upload it to Google Cloud Storage so that Vertex AI’s Matching Engine could use it.</p><p>Here’s how I did it in code:</p><pre>gsutil cp embedding_data.jsonl gs://my-bucket-name/</pre><p>Note: If you’re more of a UI person, you can go to GCP Console → Storage → Upload File and just upload your .json there.</p><p>I made sure the file format looked like this:</p><pre>{<br>  &quot;id&quot;: &quot;some-uuid&quot;,<br>  &quot;embedding&quot;: [0.12, -0.45, ..., 0.89],<br>  &quot;metadata&quot;: {<br>    &quot;question&quot;: &quot;...&quot;,<br>    &quot;answer&quot;: &quot;...&quot;<br>  }<br>}</pre><h3>Step 3: Building the Matching Engine Index</h3><p>This part felt a bit more complex at first, but it’s one of the most important. Google’s Matching Engine lets you store and search millions of embeddings efficiently — it’s basically your chatbot’s brain for memory and retrieval.</p><p>Here’s how I created the index in Python:</p><pre>from google.cloud import aiplatform<br>aiplatform.init(project=&quot;my-project&quot;, location=&quot;us-central1&quot;)<br>index = aiplatform.MatchingEngineIndex.create_tree_ah_index(<br>    display_name=&quot;my-index&quot;,<br>    contents_delta_uri=&quot;gs://my-bucket-name/embedding_data.jsonl&quot;,<br>    dimensions=768,<br>    distance_measure_type=&quot;DOT_PRODUCT_DISTANCE&quot;<br>)</pre><p>And yes — you can also do this from the console:</p><ol><li>Go to <strong>Vertex AI &gt; Indexes</strong></li><li>Click <strong>Create Index</strong></li><li>Choose <strong>Tree-AH</strong></li><li>Set dimensions (768 for the model I used)</li><li>Set distance type to DOT_PRODUCT_DISTANCE</li><li>Provide your GCS path</li></ol><p>It takes a few minutes to process, but once done, you’ve got a fully searchable index.</p><h3>Step 4: Making It Queryable with an Endpoint</h3><p>Now that I had an index, I needed to deploy it so I could send queries and get back the most relevant matches.</p><p>In code:</p><pre>endpoint = aiplatform.MatchingEngineIndexEndpoint.create(<br>    display_name=&quot;my-endpoint&quot;,<br>    public_endpoint_enabled=True<br>)<br>endpoint.deploy_index(index=index, deployed_index_id=&quot;my-deployed-id&quot;)</pre><p>From the UI:</p><ol><li>Go to <strong>Vertex AI &gt; Index Endpoints</strong></li><li>Click <strong>Create Endpoint</strong></li><li>Enable public access (if needed)</li><li>After creation, click <strong>Deploy Index</strong></li></ol><p>Done. Now I had an endpoint that I could query with a vector and get back the top N most similar embeddings (and their metadata).</p><h3>Step 5: Letting Gemini Generate the Final Answer</h3><p>Now the fun part — making the chatbot sound intelligent.</p><p>I didn’t want to simply show the retrieved answer. Instead, I wanted to feed the retrieved Q&amp;A context to a Gemini 1.5 Pro model, and let it respond naturally — like a conversation.</p><pre>import google.generativeai as genai<br>genai.configure(api_key=os.getenv(&quot;GEMINI_API_KEY&quot;))<br>chat_model = genai.GenerativeModel(&quot;gemini-1.5-pro&quot;)<br>def chat_with_context(query, context):<br>    prompt = f&quot;&quot;&quot;<br>    Context:<br>    {context}<br>    User question:<br>    {query}<br>    Answer:<br>    &quot;&quot;&quot;<br>    response = chat_model.generate_content(prompt)<br>    return response.text.strip()</pre><p>And to get the context, I queried the index:</p><pre>response = endpoint.find_neighbors(<br>    deployed_index_id=&quot;my-deployed-id&quot;,<br>    queries=[query_vector],<br>    num_neighbors=3<br>)</pre><p>Then I built a Flask API to wire it all together.</p><h3>Bonus: Local Fallback Using Cosine Similarity</h3><p>Sometimes cloud APIs hiccup or I just wanted to test locally.</p><p>I added a fallback using sklearn&#39;s cosine similarity:</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br>def local_fallback(query_vector, all_vectors, metadata):<br>    scores = cosine_similarity([query_vector], all_vectors)[0]<br>    top_indices = scores.argsort()[::-1][:3]<br>    return [metadata[i] for i in top_indices]</pre><p>It saved me more than once while debugging.</p><p>If you’re interested in the code, you can check out the full project here:<br>🔗 <a href="https://github.com/smoke2005/pg-chatbot">GitHub — chatbot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c391f292ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Multi-Modal Harmful URL Detection System Using ML]]></title>
            <link>https://medium.com/@mokithapriyan/how-i-built-a-multi-modal-harmful-url-detection-system-using-ml-f02939dccdd5?source=rss-ff6e0da6d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02939dccdd5</guid>
            <category><![CDATA[densenet121]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[xgbclassifier]]></category>
            <dc:creator><![CDATA[Mokitha]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 13:20:26 GMT</pubDate>
            <atom:updated>2025-06-23T13:26:50.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPNyKwepHAp7HsDVCcBsXQ.png" /></figure><p>In a world overflowing with online content, it’s getting harder to know which websites are safe to visit. Some links lead to phishing scams, others contain hate speech, adult content, or gambling interfaces — especially dangerous for children and vulnerable users.</p><p>I wanted to build something that could help: a <strong>multi-modal AI system that can analyze a URL and tell you if it’s potentially harmful</strong>. It’s not just about checking the link’s structure (like many phishing detectors do) — my goal was to <strong>analyze the full content</strong> of a website: the text, images, and even subtle signals of danger.</p><p>In this article, I’ll walk you through how I built it — what datasets I used, which models I trained, and how it all fits together into a unified safety-checking system.</p><h3>The Big Picture: How My Pipeline Works</h3><p>Here’s the basic workflow I designed:</p><ol><li>You give the system a URL.</li><li>It opens the website in the background (using Selenium).</li><li>It extracts the full <strong>text content</strong> and takes a <strong>screenshot</strong>.</li><li>Then, it passes this data through <strong>four separate models</strong>:</li></ol><ul><li>A <strong>phishing URL classifier</strong></li><li>A <strong>hate speech text classifier</strong></li><li>An <strong>adult content text classifier</strong></li><li>A <strong>gambling image classifier</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7mxlMHVfywmQz3IDUfgpg.png" /><figcaption>Architecture</figcaption></figure><h3>1. Phishing URL Classifier</h3><h3>Why I built this</h3><p>Phishing attacks are still one of the most common online threats. Even tech-savvy users can get tricked by a carefully disguised link. I wanted my system to catch those deceptive URLs before users clicked on them.</p><h3>Dataset</h3><p>I used <a href="https://www.kaggle.com/datasets/shashwatwork/web-page-phishing-detection-dataset">this phishing dataset from Kaggle</a>, which contains thousands of labeled URLs — some legitimate, some phishing.</p><h3>How it works</h3><p>Phishing links usually contain suspicious patterns — like strange subdomains (secure-login.paypa1.com) or even raw IP addresses. To detect them, I built a two-part feature extractor:</p><ul><li><strong>Character-level TF-IDF</strong>: This helps catch obfuscated patterns like replacing letters with numbers (1ogin, secure-acc0unt).</li><li><strong>Handcrafted features</strong>: I added custom logic to count special characters, check for IP addresses, and measure the overall length of the URL.</li></ul><p>I trained a <strong>Logistic Regression</strong> model on these features. It’s fast and works well with sparse, high-dimensional data.</p><pre>char_vectorizer = TfidfVectorizer(analyzer=&#39;char_wb&#39;, ngram_range=(3, 5))<br>model = Pipeline([<br>    (&#39;features&#39;, FeatureUnion([<br>        (&#39;char_tfidf&#39;, char_vectorizer),<br>        (&#39;url_struct_features&#39;, URLFeatureExtractor())<br>    ])),<br>    (&#39;clf&#39;, LogisticRegression(solver=&#39;liblinear&#39;))<br>])</pre><p>This model predicts whether a URL itself is suspicious, even before loading the page.</p><h3>2. Hate Speech Text Classifier</h3><h3>Why I built this</h3><p>After loading the page, I extract all the visible text using BeautifulSoup. But just having the text isn’t enough — I need to understand <strong>what kind of content the site contains</strong>. One red flag is <strong>hate speech</strong>.</p><h3>Dataset</h3><p>I used <a href="https://www.kaggle.com/datasets/waalbannyantudre/hate-speech-detection-curated-dataset">a hate speech detection dataset from Kaggle</a>. It includes tweets and comments labeled for hate speech.</p><h3>How it works</h3><p>Hate speech is often <strong>coded or disguised</strong>, like using h@te instead of “hate.” To deal with this, I used:</p><ul><li><strong>Word-level TF-IDF (1–2 grams)</strong>: To capture full phrases like “go back to [place]”.</li><li><strong>Character-level TF-IDF (3–5 grams)</strong>: To detect disguised or obfuscated slurs.</li></ul><p>I used both of these together in a FeatureUnion, and trained an <strong>XGBoost classifier</strong>.</p><pre>combined_vectorizer = FeatureUnion([<br>    (&#39;word&#39;, TfidfVectorizer(ngram_range=(1, 2), stop_words=&#39;english&#39;)),<br>    (&#39;char&#39;, TfidfVectorizer(analyzer=&#39;char_wb&#39;, ngram_range=(3, 5)))<br>])<br>pipeline = Pipeline([<br>    (&#39;vectorizer&#39;, combined_vectorizer),<br>    (&#39;clf&#39;, XGBClassifier(use_label_encoder=False, eval_metric=&#39;logloss&#39;))<br>])</pre><p>After training, the model could flag text that contains toxic, abusive, or discriminatory language — even if it was hidden behind misspellings.</p><h3>3. Adult Content Text Classifier</h3><h3>Why I built this</h3><p>Another major concern is adult or explicit content — especially on websites that appear safe at first glance. I wanted to detect this just from the <strong>text on the page</strong>.</p><h3>Dataset</h3><p>I used the <a href="https://huggingface.co/datasets/valurank/Adult-content-dataset">Valurank Adult Content Dataset</a>, which contains web page descriptions labeled as “adult” or “non-adult.”</p><h3>How it works</h3><p>This model is simpler but effective. I:</p><ul><li>Cleaned and standardized the labels</li><li>Used a <strong>TF-IDF vectorizer</strong> (with a vocab size of 5,000)</li><li>Trained a <strong>Logistic Regression</strong> model</li></ul><pre>vectorizer = TfidfVectorizer(max_features=5000)<br>model = LogisticRegression()</pre><p>This setup performs well because adult content tends to use a specific vocabulary. The model learns which words are commonly associated with explicit content and flags them accordingly.</p><h3>4. Gambling Image Classifier</h3><h3>Why I built this</h3><p>Some harmful sites don’t reveal their intent through text — they use <strong>visual elements</strong>. Gambling sites, for example, might just show flashy graphics, chips, slot machines, or betting UIs.</p><p>So I needed a model that could look at the page <strong>as an image</strong> and say: “Does this look like a gambling site?”</p><h3>Datasets</h3><p>I combined two UI-focused image datasets from <a href="https://huggingface.co/datasets/YashJain/UI-Elements-Detection-Dataset">Hugging Face</a> and <a href="https://www.kaggle.com/datasets/shenaozheng/ui-detection-for-gambling-sites">Kaggle</a>.</p><h3>How it works</h3><p>I used <strong>DenseNet121</strong>, a powerful convolutional neural network pretrained on ImageNet.</p><p>Steps I followed:</p><ul><li>Took a screenshot of the page using Selenium</li><li>Applied real-time data augmentation (flip, zoom, brightness)</li><li>Trained a classifier using the DenseNet backbone and a small custom head</li></ul><pre>model = models.Sequential([<br>    DenseNet121(weights=&#39;imagenet&#39;, include_top=False),<br>    layers.GlobalAveragePooling2D(),<br>    layers.Dense(64, activation=&#39;relu&#39;),<br>    layers.Dropout(0.3),<br>    layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><p>This model learned to recognize subtle UI patterns — like colorful banners, chips, spinning wheels — that often indicate gambling content.</p><h3>Scraping: How I Collected Content from URLs</h3><p>To pull all this data together, I built a <strong>stealth web scraper</strong> using Selenium. It loads the page, waits for it to fully render, takes a screenshot, and extracts the text.</p><pre>def scrape_and_save(url):<br>    driver = webdriver.Chrome(...)<br>    stealth(driver, ...)<br>    driver.get(url)<br>    soup = BeautifulSoup(driver.page_source, &#39;html.parser&#39;)<br>    text = soup.get_text()<br>    driver.save_screenshot(&quot;page.png&quot;)</pre><p>This allowed me to feed both the image and text into the respective models, without being blocked or flagged as a bot.</p><h3>Final Verdict: Is the URL Safe?</h3><p>After the system finishes running:</p><ul><li>The <strong>phishing model</strong> tells me if the URL structure is shady</li><li>The <strong>hate speech</strong> and <strong>adult content models</strong> scan the page’s text</li><li>The <strong>gambling model</strong> evaluates the screenshot</li></ul><p>Each model returns a probability score. I combine these scores with a simple logic: if any of them cross a danger threshold, I flag the URL as <strong>potentially harmful</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el8AiaAYDj02IE9flCOpuA.png" /><figcaption>Classified as SAFE</figcaption></figure><h3>Conclusion</h3><p>This project helped me understand how different machine learning approaches — NLP, computer vision, feature engineering — can work together to solve a real-world problem.</p><p>By combining:</p><ul><li><strong>Structural URL analysis</strong></li><li><strong>Text classification</strong></li><li><strong>Image classification</strong></li><li><strong>Web scraping automation</strong></li></ul><p>I built a system that doesn’t just scan links — it understands content, context, and visual cues. And most importantly, it helps users stay safer online.</p><p>If you’re interested in the code, you can check out the full project here:<br> 🔗 <a href="https://github.com/smoke2005/url-content-classifier">GitHub — URL Content Classifier</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02939dccdd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>