<?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 Satish Kumar Andey on Medium]]></title>
        <description><![CDATA[Stories by Satish Kumar Andey on Medium]]></description>
        <link>https://medium.com/@satishkumarandey?source=rss-8a774c28484c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yx5U2XX3qG9LevUOJLk14g.jpeg</url>
            <title>Stories by Satish Kumar Andey on Medium</title>
            <link>https://medium.com/@satishkumarandey?source=rss-8a774c28484c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:43:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satishkumarandey/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[Building a Production-Grade RAG System: From Vector Search to Hybrid Ranking]]></title>
            <link>https://satishkumarandey.medium.com/building-a-production-grade-rag-system-from-vector-search-to-hybrid-ranking-c14577f2a83a?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c14577f2a83a</guid>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 21:24:58 GMT</pubDate>
            <atom:updated>2026-02-06T21:34:40.718Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How We Built an AI-Powered Real Estate Document Assistant That Actually Works</strong></p><p><em>A deep dive into implementing semantic search, keyword matching, and intelligent reranking for real-world applications</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94GspdsRGmyV7Xr5EUW2Wg.png" /><figcaption>by <a href="https://dezgo.com/">https://dezgo.com/</a></figcaption></figure><p><strong>The Problem: Why Simple RAG Isn’t Enough</strong></p><p>You’ve probably seen countless RAG (Retrieval-Augmented Generation) tutorials that make it look easy:</p><pre># Oversimplified RAG<br>    embeddings = embed_documents(docs)<br>    query_embedding = embed_query(question)<br>    results = vector_search(query_embedding)<br>    answer = llm.generate(results + question)</pre><p>But when you deploy this to production, you quickly discover:</p><ul><li>Vector search misses exact matches (searching “purchase price” might not find “$450,000”)</li><li>Semantic similarity isn’t always relevant (similar words ≠ relevant content)</li><li>No way to filter by metadata (customer, property, document type)</li><li>Results lack context (which document? which page?)</li></ul><p>After building a real estate document assistant handling thousands of PDFs, we learned that **<strong>production RAG requires a hybrid approach**</strong>. Here’s how we built it.</p><p><strong>Architecture Overview</strong></p><p>Application is deployed in AWS with following Aws components:</p><p>Aws CloudFront -&gt; S3 -&gt; frontendcode -&gt; AWS Apigateway -&gt; AWS lambda -&gt; AWS ECR -&gt; AWS RDS (postgresql with pgvector)</p><p>Our system combines three search strategies:</p><p>1. <strong>Vector Search </strong>— Semantic similarity using embeddings</p><p>2. <strong>Keyword Search </strong>— Exact term matching with BM25</p><p>3. <strong>Reranking</strong> — Cross-encoder scoring for final ordering</p><p><strong>Part 1: Vector Search with pgvector</strong></p><p><strong>Why pgvector?</strong></p><p>We chose PostgreSQL with pgvector because:</p><ul><li>✅ No separate vector database to manage</li><li>✅ ACID transactions for data consistency</li><li>✅ Metadata filtering with SQL</li><li>✅ Scales to millions of vectors</li></ul><p><strong>Database Schema</strong></p><pre>from sqlalchemy import Column, Integer, String, Text<br>    from pgvector.sqlalchemy import Vector<br>    <br>    class Embedding(Base):<br>        __tablename__ = &#39;embeddings&#39;<br>        <br>        id = Column(Integer, primary_key=True)<br>        document_id = Column(Integer, ForeignKey(&#39;documents.id&#39;))<br>        chunk_text = Column(Text)<br>        embedding = Column(Vector(1536))  # OpenAI dimensions<br>        metadata = Column(JSON)<br>        page_number = Column(Integer) # For source citation</pre><p><strong>Creating Embeddings</strong></p><pre>from openai import OpenAI<br>    from langchain.text_splitter import RecursiveCharacterTextSplitter<br>    <br>    def create_embeddings(document_text, document_id, metadata):<br>        # Split into chunks<br>        splitter = RecursiveCharacterTextSplitter(<br>            chunk_size=1000,<br>            chunk_overlap=200<br>        )<br>        chunks = splitter.split_text(document_text)<br>        <br>        client = OpenAI()<br>        embeddings = []<br>        <br>        for i, chunk in enumerate(chunks):<br>            response = client.embeddings.create(<br>                model=&quot;text-embedding-ada-002&quot;,<br>                input=chunk<br>            )<br>            <br>            embedding = Embedding(<br>                document_id=document_id,<br>                chunk_text=chunk,<br>                embedding=response.data[0].embedding,<br>                metadata=metadata,<br>                page_number=i // 3<br>            )<br>            embeddings.append(embedding)<br>        <br>        return embeddings</pre><p><strong>Key Insight</strong>: Store rich metadata with each chunk for powerful filtering.</p><p><strong>Vector Search Implementation:</strong></p><pre>from pgvector.sqlalchemy import cosine_distance<br>    from app.database import Embedding<br>    <br>    def vector_search(query, top_k=5, customer_id=None):<br>        # Generate query embedding<br>        client = OpenAI()<br>        response = client.embeddings.create(<br>            model=&quot;text-embedding-ada-002&quot;,<br>            input=query<br>        )<br>        query_embedding = response.data[0].embedding<br>        <br>        # Build query with filters<br>        stmt = select(<br>            Embedding, //embedding database model<br>            cosine_distance(Embedding.embedding, query_embedding)<br>        )<br>        <br>        if customer_id:<br>            stmt = stmt.where(<br>                Embedding.metadata[&#39;customer_id&#39;] == customer_id<br>            )<br>        <br>        stmt = stmt.order_by(&#39;distance&#39;).limit(top_k)<br>        results = db.execute(stmt).all()<br>        <br>        return results</pre><p><strong>Performance Tip</strong>: Create an index for faster searches:</p><ul><li>CREATE INDEX ON embeddings USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);</li></ul><p><strong>Part 2: Keyword Search with BM25</strong></p><p><strong>Why Keyword Search? </strong>Vector search fails on:</p><ul><li>Exact numbers: “$450,000”, “2,500 sq ft”</li><li>Specific names: “John Smith”, “123 Main St”</li><li>Technical terms: “contingency”, “escrow”</li></ul><p>BM25 excels at exact matching.</p><p><strong>Implementation</strong></p><pre>from rank_bm25 import BM25Okapi<br>    import re<br>    <br>    class KeywordSearchEngine:<br>        def __init__(self):<br>            self.bm25 = None<br>            self.documents = []<br>        <br>        def index_documents(self, chunks):<br>            self.documents = [chunk[&#39;text&#39;] for chunk in chunks]<br>            tokenized = [self._tokenize(doc) for doc in self.documents]<br>            self.bm25 = BM25Okapi(tokenized)<br>        <br>        def _tokenize(self, text):<br>            return re.findall(r&#39;\b\w+\b&#39;, text.lower())<br>        <br>        def search(self, query, top_k=5):<br>            query_tokens = self._tokenize(query)<br>            scores = self.bm25.get_scores(query_tokens)<br>            <br>            results = []<br>            for idx, score in enumerate(scores):<br>                results.append({<br>                    &#39;text&#39;: self.documents[idx],<br>                    &#39;score&#39;: score<br>                })<br>            <br>            results.sort(key=lambda x: x[&#39;score&#39;], reverse=True)<br>            return results[:top_k]</pre><p><strong>Part 3: Hybrid Search — Best of Both Worlds</strong></p><p><strong>Reciprocal Rank Fusion: </strong>Combine vector and keyword search:</p><ul><li>RRF_score(doc) = Σ 1 / (k + rank_i)</li><li>Where k = 60 (constant) and rank_i = rank in search method i</li></ul><p><strong>Implementation</strong></p><pre>def hybrid_search(query, top_k=5, alpha=0.5):<br>        # Get results from both methods<br>        vector_results = vector_search(query, top_k=20)<br>        keyword_results = keyword_search(query, top_k=20)<br>        <br>        # Reciprocal Rank Fusion<br>        k = 60<br>        scores = {}<br>        <br>        for rank, result in enumerate(vector_results):<br>            doc_id = result[&#39;id&#39;]<br>            scores[doc_id] = alpha / (k + rank + 1)<br>        <br>        for rank, result in enumerate(keyword_results):<br>            doc_id = result[&#39;id&#39;]<br>            scores[doc_id] = scores.get(doc_id, 0) + (1 - alpha) / (k + rank + 1)<br>        <br>        # Sort by combined score<br>        all_results = {r[&#39;id&#39;]: r for r in vector_results + keyword_results}<br>        ranked = sorted(<br>            all_results.values(),<br>            key=lambda x: scores.get(x[&#39;id&#39;], 0),<br>            reverse=True<br>        )<br>        <br>        return ranked[:top_k]</pre><p><strong>Alpha Tuning:</strong></p><ul><li>alpha=0.7 → Favor semantic (general questions)</li><li>alpha=0.3 → Favor exact matching (specific queries)</li><li>alpha=0.5 → Balanced (default)</li></ul><p><strong>Part 4: Reranking with Cross-Encoders</strong></p><p><strong>Why Rerank?</strong></p><p>Initial retrieval is fast but imprecise. Reranking uses a powerful model to score query-document pairs.</p><pre>from sentence_transformers import CrossEncoder<br>    <br>    class Reranker:<br>        def __init__(self):<br>            self.model = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)<br>        <br>        def rerank(self, query, documents, top_k=5):<br>            # Create query-document pairs<br>            pairs = [[query, doc[&#39;text&#39;]] for doc in documents]<br>            <br>            # Score all pairs<br>            scores = self.model.predict(pairs)<br>            <br>            # Add scores and sort<br>            for doc, score in zip(documents, scores):<br>                doc[&#39;rerank_score&#39;] = float(score)<br>            <br>            documents.sort(key=lambda x: x[&#39;rerank_score&#39;], reverse=True)<br>            return documents[:top_k]</pre><p><strong>Performance</strong>: Reranking is slower (10–50ms per doc) but dramatically improves relevance.</p><p><strong>Part 5: Complete RAG Pipeline</strong></p><pre>class RAGEngine:<br>        def __init__(self, db_session):<br>            self.db = db_session<br>            self.keyword_engine = KeywordSearchEngine()<br>            self.reranker = Reranker()<br>            self.llm = ChatOpenAI(model=&quot;gpt-4&quot;)<br>        <br>        def query(self, question, search_mode=&quot;hybrid&quot;):<br>            # Step 1: Retrieve<br>            if search_mode == &quot;hybrid&quot;:<br>                chunks = hybrid_search(question, top_k=20)<br>            <br>            # Step 2: Rerank<br>            chunks = self.reranker.rerank(question, chunks, top_k=5)<br>            <br>            # Step 3: Build context<br>            context = &quot;\n\n&quot;.join([<br>                f&quot;[{i+1}] {chunk[&#39;text&#39;]}\nSource: {chunk[&#39;filename&#39;]} (Page {chunk[&#39;page&#39;]})&quot;<br>                for i, chunk in enumerate(chunks)<br>            ])<br>            <br>            # Step 4: Generate answer<br>            messages = [<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Answer based ONLY on context. Always cite sources.&quot;},<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Context:\n{context}\n\nQuestion: {question}&quot;}<br>            ]<br>            <br>            response = self.llm.invoke(messages)<br>            <br>            return {<br>                &quot;answer&quot;: response.content,<br>                &quot;sources&quot;: chunks<br>            }</pre><p><strong>Example Usage</strong></p><pre>rag = RAGEngine(db_session)<br>    <br>    result = rag.query(&quot;What is the purchase price?&quot;)<br>    print(result[&#39;answer&#39;])<br>    # &quot;The purchase price is $450,000 [Source: Purchase_Agreement.pdf (Page 2)]&quot;</pre><p><strong>Common Pitfalls &amp; Solutions</strong></p><p><strong>1. Chunk Size Matters</strong></p><ul><li>❌ Too small (&lt; 500 chars): Loses context</li><li>❌ Too large (&gt; 2000 chars): Dilutes relevance</li><li>✅ Sweet spot: 800–1200 characters with 200 char overlap</li></ul><p><strong>2. Metadata is Critical</strong></p><pre># Bad: No metadata<br>    embedding = Embedding(text=chunk, embedding=vector)<br>    <br>    # Good: Rich metadata<br>    embedding = Embedding(<br>        text=chunk,<br>        embedding=vector,<br>        metadata={<br>            &#39;customer_id&#39;: 123,<br>            &#39;property_id&#39;: 456,<br>            &#39;document_type&#39;: &#39;purchase_agreement&#39;,<br>            &#39;filename&#39;: &#39;contract.pdf&#39;,<br>            &#39;page&#39;: 5<br>        }<br>    )</pre><p><strong>3. Handle “No Results” Gracefully</strong></p><pre>def query_with_fallback(question, **filters):<br>        results = hybrid_search(question, **filters)<br>        <br>        if len(results) &lt; 3:<br>            # Relax filters<br>            results = hybrid_search(question, customer_id=filters.get(&#39;customer_id&#39;))<br>        <br>        if len(results) &lt; 3:<br>            # Last resort: no filters<br>            results = hybrid_search(question)<br>        <br>        return results</pre><p><em>If you found this helpful, please share and subscribe for more deep dives into production AI systems!</em></p><ul><li><strong>👏 Clap if you learned something new!</strong></li><li><strong>💬 Comment with your RAG challenges</strong></li><li><strong>🔔 Follow for weekly AI engineering tips</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14577f2a83a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Video Scene Description System]]></title>
            <link>https://satishkumarandey.medium.com/building-an-ai-powered-video-scene-description-system-f69955841aa1?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69955841aa1</guid>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 15:57:22 GMT</pubDate>
            <atom:updated>2025-09-23T16:11:45.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how to automatically generate descriptions for video scenes? In this article, I’ll walk you through building a powerful video processing system that can extract frames from a video and generate natural language descriptions using state-of-the-art AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihH998qxExTk1PGfy8O_Hw.png" /><figcaption>by Google Ai Studio</figcaption></figure><h3>The Architecture</h3><p>Our video processing system consists of four main components:</p><ol><li>Frame Extractor</li><li>Scene Description Generator</li><li>Output Writer</li><li>Video Processor (Orchestrator)</li></ol><p>Let’s dive deep into each component and see how they work together.</p><h3>1. Frame Extraction</h3><p>The FrameExtractor class handles the crucial first step of breaking down a video into individual frames:</p><pre>import cv2<br>import os<br><br>class FrameExtractor:<br>    def __init__(self, output_dir: str, interval: int = 1):<br>        self.output_dir = output_dir<br>        self.interval = interval<br><br>    def extract_frames(self, video_path: str):<br>        os.makedirs(self.output_dir, exist_ok=True)<br>        cap = cv2.VideoCapture(video_path)<br>        frame_count = 0<br>        success, frame = cap.read()<br><br>        while success:<br>            if frame_count % self.interval == 0:<br>                frame_path = os.path.join(self.output_dir, f&quot;frame_{frame_count}.jpg&quot;)<br>                cv2.imwrite(frame_path, frame)<br>            success, frame = cap.read()<br>            frame_count += 1<br><br>        cap.release()<br>        return self.output_dir</pre><p>This component uses OpenCV ( cv2) to read the video frame by frame. The interval parameter allows you to control how frequently frames are extracted, helping to manage processing time and storage requirements.</p><h3>2. Scene Description Generation</h3><p>The magic happens in the SceneDescription class, which leverages the BLIP (Bootstrapping Language-Image Pre-training) model:</p><pre>from transformers import BlipProcessor, BlipForConditionalGeneration<br>from PIL import Image<br>import os<br><br>class SceneDescription:<br>    def __init__(self, model_name: str = &quot;Salesforce/blip-image-captioning-base&quot;):<br>        self.processor = BlipProcessor.from_pretrained(model_name)<br>        self.model = BlipForConditionalGeneration.from_pretrained(model_name)<br><br>    def generate_descriptions(self, frames_dir: str):<br>        descriptions = {}<br>        for frame_file in sorted(os.listdir(frames_dir)):<br>            frame_path = os.path.join(frames_dir, frame_file)<br>            image = Image.open(frame_path).convert(&quot;RGB&quot;)<br>            inputs = self.processor(image, return_tensors=&quot;pt&quot;)<br>            outputs = self.model.generate(**inputs)<br>            description = self.processor.decode(outputs[0], skip_special_tokens=True)<br>            descriptions[frame_file] = description<br>        return descriptions</pre><p>BLIP is a powerful model that can understand and describe image content in natural language. For each frame, it:</p><ol><li>Processes the image into a format the model can understand</li><li>Generates a description using the pre-trained model</li><li>Decodes the output into human-readable text</li></ol><h3>3. Output Management</h3><p>The OutputWriter class handles the storage of results:</p><pre>class OutputWriter:<br>    @staticmethod<br>    def write_to_json(data: dict, output_path: str):<br>        with open(output_path, &quot;w&quot;) as json_file:<br>            json.dump(data, json_file, indent=4)</pre><p>This component provides a clean interface for saving the frame descriptions in JSON format, making it easy to use the results in other applications or analysis.</p><h3>4. Bringing It All Together</h3><p>The VideoProcessor class orchestrates the entire process:</p><pre>class VideoProcessor:<br>    def __init__(self, output_dir: str, frame_interval: int = 1):<br>        self.output_dir = output_dir<br>        self.frame_interval = frame_interval<br><br>    def process_video(self, video_path: str, output_format: str = &quot;json&quot;):<br>        # Extract frames<br>        frames_dir = os.path.join(self.output_dir, &quot;frames&quot;)<br>        frame_extractor = FrameExtractor(frames_dir, self.frame_interval)<br>        frame_extractor.extract_frames(video_path)<br><br>        # Generate descriptions<br>        scene_description = SceneDescription()<br>        descriptions = scene_description.generate_descriptions(frames_dir)<br><br>        # Save results<br>        output_path = os.path.join(self.output_dir, f&quot;output.{output_format}&quot;)<br>        OutputWriter.write_to_json(descriptions, output_path)<br>        return output_path</pre><h3>Using the System</h3><pre># Initialize the processor<br>processor = VideoProcessor(output_dir=&quot;output&quot;, frame_interval=30)<br><br># Process a video<br>output_file = processor.process_video(&quot;my_video.mp4&quot;)</pre><h3>Key Benefits</h3><ol><li><strong>Automation </strong>: Automatically generate natural language descriptions for video content</li><li><strong>Flexibility </strong>: Extract frames at custom intervals to balance detail and processing time</li><li><strong>Scalability </strong>: Process videos of any length</li><li><strong>Easy Integration </strong>: JSON output format makes it simple to integrate with other systems</li></ol><h3>Potential Applications</h3><ul><li>Content moderation</li><li>Video cataloging and searching</li><li>Accessibility improvements for visual content</li><li>Video content analysis</li><li>Automated video summarization</li></ul><h3>Ouput Result:</h3><pre>{<br>    &quot;frame_0.jpg&quot;: &quot;the flash in the flash&quot;,<br>    &quot;frame_1.jpg&quot;: &quot;the flash in the flash&quot;,<br>    &quot;frame_100.jpg&quot;: &quot;a man in a red shirt is standing next to a woman&quot;,<br>    &quot;frame_101.jpg&quot;: &quot;a man is standing on a boat with a bunch of boxes&quot;,<br>    &quot;frame_102.jpg&quot;: &quot;a man is standing on a boat with a bunch of luggage&quot;,<br>    &quot;frame_103.jpg&quot;: &quot;a man is standing on a boat with luggage&quot;,<br>    &quot;frame_109.jpg&quot;: &quot;a man is standing on the back of a boat&quot;,<br>    &quot;frame_110.jpg&quot;: &quot;a boat with a bunch of trash on the deck&quot;<br>    &quot;frame_138.jpg&quot;: &quot;a tall building with a fire in the middle&quot;<br>}</pre><h3>Conclusion</h3><p>This video processing system demonstrates the power of combining computer vision with natural language processing. By leveraging the BLIP model and organizing our code into clean, maintainable components, we’ve created a powerful tool for automated video understanding.</p><p>Ready to try it yourself? The complete code is available on GitHub</p><p><a href="https://github.com/satishnaidu/video-scene-description">GitHub - satishnaidu/video-scene-description: Video Scene Descriptioin using Python and BLIP</a></p><p>and you can customize it to suit your specific needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69955841aa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Parenting: Building an AI-Powered Baby Cry Alert System]]></title>
            <link>https://satishkumarandey.medium.com/smart-parenting-building-an-ai-powered-baby-cry-alert-system-3b0e58241f20?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0e58241f20</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[yamnet]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 22:03:07 GMT</pubDate>
            <atom:updated>2025-07-31T17:44:59.873Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Detecting a baby’s cry in real-time can help parents and caregivers respond quickly and effectively. In this article, you’ll learn how to build a robust baby cry detection pipeline using Python, deep learning, and audio processing. We’ll walk through data preparation, model training, and real-time inference, with code examples you can run yourself!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNAx6Jvbzz7pwnLrXgjjdg.png" /></figure><h3>Why Baby Cry Detection?</h3><p>Babies cry for many reasons — hunger, discomfort, or simply needing attention. Automating cry detection can:</p><ul><li>Instantly alert parents or caregivers</li><li>Trigger smart home actions (lights, music, notifications)</li><li>Log cry events for health monitoring</li><li>Enable peace of mind, especially for busy or new parents</li></ul><p>In this article, I’ll walk you through a robust, production-ready Python-based Baby Cry Detection system I developed. We’ll cover everything from data validation and augmentation to model training, analytics, and real-time inference with smart home integration.</p><h3>Project Structure Overview</h3><p>Here’s how the project is organized for clarity and scalability:</p><pre>babycry/<br>├── audio_processing/     # Data validation, augmentation, SMOTE<br>├── model/                # Model architecture, training, tuning<br>├── inference/            # Real-time and batch inference scripts<br>├── notebooks/            # EDA and diagnostics<br>├── utils/                # Visualization, notifications, smart actions<br>├── train.py              # Main training pipeline<br>├── requirements.txt      # Dependencies<br>└── README.md</pre><p><strong>Key modules:</strong></p><ul><li><strong>audio_processing/</strong>: Cleans, augments, and balances audio data.</li><li><strong>model/</strong>: Defines and trains the deep learning model (YAMNet-based).</li><li><strong>inference/</strong>: Runs predictions and triggers smart actions.</li><li><strong>utils/</strong>: Visualization, notifications, and smart home integrations.</li></ul><h3>Step 1: Install Dependencies</h3><p>First, clone the repository and install the required packages:</p><pre>git clone https://github.com/satishnaidu/babycrymonitor<br>cd babycrymonitor<br>pip install -r requirements.txt</pre><h3>Step 2: Prepare Your Data</h3><p>Place your audio files in the donateacry_corpus directory, organized by class:</p><pre>data/donateacry_corpus/<br>├── belly_pain/<br>│   ├── sample1.wav<br>│   └── ...<br>├── burping/<br>│   ├── sample2.wav<br>│   └── ...<br>└── ...</pre><p>Data Validation &amp; Preparation:</p><p>Clean, well-labeled data is the foundation of any reliable ML system. We validate labels, remove duplicates, and ensure all audio files are usable.</p><pre>from audio_processing.data_quality import validate_labels, remove_duplicates<br><br>audio_files, labels = validate_labels(&#39;data/donateacry_corpus&#39;)<br>audio_files, labels = remove_duplicates(audio_files, labels)<br><br><br>def validate_labels(data_dir):<br>    &quot;&quot;&quot;Check for mislabels and print class distribution.&quot;&quot;&quot;<br>    audio_files, labels = [], []<br>    for label in os.listdir(data_dir):<br>        label_dir = os.path.join(data_dir, label)<br>        if os.path.isdir(label_dir):<br>            for file in os.listdir(label_dir):<br>                if file.endswith(&#39;.wav&#39;):<br>                    audio_files.append(os.path.join(label_dir, file))<br>                    labels.append(label)<br>    print(&quot;Class distribution:&quot;, Counter(labels))<br>    return audio_files, labels<br><br>def remove_duplicates(audio_files, labels):<br>    &quot;&quot;&quot;Remove duplicate audio files by hash.&quot;&quot;&quot;<br>    import hashlib<br>    seen = set()<br>    unique_files, unique_labels = [], []<br>    for f, l in zip(audio_files, labels):<br>        with open(f, &#39;rb&#39;) as file:<br>            file_hash = hashlib.md5(file.read()).hexdigest()<br>        if file_hash not in seen:<br>            seen.add(file_hash)<br>            unique_files.append(f)<br>            unique_labels.append(l)<br>    print(f&quot;Removed {len(audio_files) - len(unique_files)} duplicates.&quot;)<br>    return unique_files, unique_labels</pre><h3>Step 3: Audio Augmentation &amp; Class Balancing</h3><p>Baby cries are rare compared to silence or other sounds. Augmentation (noise, pitch, speed) and SMOTE (synthetic minority oversampling) help balance the dataset for better generalization.</p><pre>from audio_processing.augmentation import get_augmentation_pipeline<br>from audio_processing.smote import apply_smote<br><br>aug_pipeline = get_augmentation_pipeline()<br>X_aug = [aug_pipeline(x, 16000) for x in X]  # Example usage<br><br># SMOTE for feature-level balancing<br>X_features = feature_extractor.predict(X, batch_size=16)<br>X_bal, y_bal = apply_smote(X_features, y)<br><br><br>def get_augmentation_pipeline():<br>    return Compose([<br>        AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.5),<br>        TimeStretch(min_rate=0.8, max_rate=1.25, p=0.5),<br>        PitchShift(min_semitones=-4, max_semitones=4, p=0.5),<br>        Gain(min_gain_db=-6, max_gain_db=6, p=0.5),<br>    ])<br><br>aug_pipeline = get_augmentation_pipeline()<br>class_counts = Counter(y)<br>max_count = max(class_counts.values())<br>X, y_aug = [], []<br><br>for idx, file in enumerate(audio_files):<br>    y_audio, _ = librosa.load(file, sr=SAMPLE_RATE)<br>    y_audio = np.pad(y_audio, (0, max(0, MAX_SAMPLES - len(y_audio))), mode=&#39;constant&#39;)[:MAX_SAMPLES]<br>    X.append(y_audio)<br>    # Augment minority classes<br>    n_to_add = max_count - class_counts[y[idx]]<br>    for _ in range(n_to_add):<br>        X.append(aug_pipeline(samples=y_audio, sample_rate=SAMPLE_RATE))<br>        y_aug.append(y[idx])<br><br>X = np.array(X + X)<br>y_bal = np.array(list(y) + y_aug)</pre><h3>Step 4: Model Architecture: YAMNet + TensorFlow</h3><p><a href="https://tfhub.dev/google/yamnet/1">YAMNet</a> is a pre-trained audio event classifier that excels at extracting meaningful features from audio. We use its embeddings as input to our custom classifier.</p><pre>from model.architecture import get_yamnet_model<br><br>model = get_yamnet_model((MAX_SAMPLES,), num_classes)<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br><br>class YamNetEmbedding(tf.keras.layers.Layer):<br>    yamnet_model = None<br>    def __init__(self, yamnet_handle, **kwargs):<br>        super().__init__(**kwargs)<br>        self.yamnet_handle = yamnet_handle<br>    def build(self, input_shape):<br>        if YamNetEmbedding.yamnet_model is None:<br>            YamNetEmbedding.yamnet_model = hub.load(self.yamnet_handle)<br>        super().build(input_shape)<br>    def call(self, inputs):<br>        def extract(x):<br>            _, embeddings, _ = YamNetEmbedding.yamnet_model(x)<br>            return embeddings<br>        return tf.map_fn(extract, inputs, fn_output_signature=tf.float32)<br><br>def get_yamnet_model(input_shape, num_classes):<br>    inputs = tf.keras.Input(shape=input_shape)<br>    yamnet_layer = YamNetEmbedding(&#39;https://tfhub.dev/google/yamnet/1&#39;)<br>    embeddings = yamnet_layer(inputs)<br>    x = tf.keras.layers.GlobalAveragePooling1D()(embeddings)<br>    outputs = tf.keras.layers.Dense(num_classes, activation=&#39;softmax&#39;)(x)<br>    return tf.keras.Model(inputs, outputs)</pre><h3>Step 5: Training with Cross-Validation</h3><p>Cross-validation ensures the model generalizes well and isn’t overfitting to a particular split.</p><pre>from model.training import train_with_cv<br><br>histories = train_with_cv(model_fn, X_bal, y_bal, n_splits=5, epochs=20, batch_size=32)<br><br><br>def train_with_cv(model_fn, X, y, n_splits=5, epochs=20, batch_size=32):<br>    skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)<br>    histories = []<br>    for fold, (train_idx, val_idx) in enumerate(skf.split(X, y)):<br>        print(f&quot;Fold {fold+1}/{n_splits}&quot;)<br>        X_train, X_val = X[train_idx], X[val_idx]<br>        y_train, y_val = y[train_idx], y[val_idx]<br>        class_weights = compute_class_weight(&#39;balanced&#39;, classes=np.unique(y_train), y=y_train)<br>        class_weight_dict = dict(enumerate(class_weights))<br>        model = model_fn()<br>        model.compile(optimizer=&#39;adam&#39;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>        history = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=epochs, batch_size=batch_size, class_weight=class_weight_dict)<br>        histories.append(history)<br>    return histories</pre><h3>Step 6: Advanced Analytics &amp; Visualization</h3><p>Understanding model performance is crucial. We export confusion matrices, ROC curves, per-class accuracy, t-SNE plots, and misclassified samples for deep diagnostics.</p><pre>from utils.visualization import (<br>    plot_confusion_matrix, print_classification_report, plot_roc_curves,<br>    plot_per_class_accuracy, confusion_matrix_df, show_sample_predictions<br>)<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>model = get_yamnet_model((MAX_SAMPLES,), len(label_encoder.classes_))<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(X, y, epochs=1, batch_size=32)<br>preds = model.predict(X, batch_size=16)<br>y_pred = np.argmax(preds, axis=1)<br>class_names = label_encoder.classes_<br><br>plot_confusion_matrix(y, y_pred, class_names)<br>print_classification_report(y, y_pred, class_names)<br>plot_roc_curves(y, preds, class_names)<br>plot_per_class_accuracy(y, y_pred, class_names)<br>cm_df = confusion_matrix_df(y, y_pred, class_names)<br>cm_df.to_csv(&#39;confusion_matrix.csv&#39;)</pre><p><strong>All analytics are saved as CSV, PNG, or HTML for easy review.</strong></p><h3>Step 7: Real-Time Inference &amp; Smart Actions</h3><p>The system isn’t just about prediction — it can take action! When a cry is detected, it can play music, notify parents, turn on lights, and more.</p><pre>from inference.sample_inference import predict_reason<br><br>label, confidence = predict_reason(&#39;data/donateacry_corpus/cry/sample1.wav&#39;)<br>print(f&quot;Predicted Reason: {label} (confidence: {confidence:.2f})&quot;)<br><br>if label.lower() == &quot;cry&quot;:<br>    play_soothing_music()<br>    send_notification(label)<br>    activate_night_light()<br>    # ...other smart actions</pre><h3>Step 8: How to Run the System</h3><p>1. Train the Model</p><pre>python train.py</pre><p>2. Run Inference</p><pre>python -m inference.sample_inference &lt;audio_path&gt;</pre><p>3. Explore Analytics</p><p>Open model_report.html for a summary of model performance and diagnostics.</p><h3>Troubleshooting &amp; Advanced Features</h3><ul><li><strong>Analytics Export:</strong> All key metrics and plots are saved for offline review.</li><li><strong>Smart Home Integration:</strong> Easily extend smart actions to your devices.</li><li><strong>Batch Evaluation:</strong> Evaluate on a test set for robust diagnostics.</li><li><strong>Notebook EDA:</strong> Use eda.ipynb for interactive exploration.</li></ul><h3>Conclusion</h3><p>This project demonstrates how deep learning and audio processing can create a practical, real-world baby cry detection system. With robust data handling, advanced analytics, and smart home integration, it’s ready for both research and real-world deployment.</p><p>Try it out, experiment with your own data, and make parenting a little bit easier!</p><p><em>If you enjoyed this article, follow me for more deep learning and audio AI tutorials!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0e58241f20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI Fitness Coach: Real-Time Feedback with MediaPipe]]></title>
            <link>https://satishkumarandey.medium.com/build-your-own-ai-fitness-coach-real-time-feedback-with-mediapipe-a787e901efe9?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a787e901efe9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fitness]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 06:18:03 GMT</pubDate>
            <atom:updated>2025-06-08T04:33:42.326Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Are you ready to revolutionize your fitness journey with AI?</strong><br>Imagine having a personal trainer in your pocket — one that gives you instant feedback on your form, counts your reps, and helps you avoid injury, all powered by cutting-edge computer vision. In this article, I’ll show you how to build your own AI fitness coach using Python and MediaPipe, and even turn it into a web or mobile app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JvGBOOcPs8cnnh8APCanQ.png" /><figcaption><a href="https://dezgo.com/">https://dezgo.com/</a></figcaption></figure><h3>Why AI Fitness?</h3><ul><li><strong>Personalized coaching</strong> at home, anytime.</li><li><strong>Instant feedback</strong> to improve your form and results.</li><li><strong>Fun and engaging</strong> for all fitness levels.</li><li><strong>Open-source and customizable</strong> — make it your own!</li></ul><h3>What We’ll Build</h3><ul><li>Real-time pose estimation using your webcam.</li><li>Feedback for multiple exercises (squats, pushups, and more).</li><li>Automatic rep counting and workout stats.</li><li>A web app interface anyone can use — no coding required!</li></ul><h3>Step 1: Set Up Your Project</h3><pre>pip install mediapipe opencv-python numpy streamlit fastapi uvicorn python-multipart</pre><h3>Step 2: Pose Estimation and Feedback Logic</h3><p><em>This code defines functions to calculate joint angles and provide real-time feedback for squats and pushups using MediaPipe pose landmarks.</em></p><pre>import numpy as np<br><br>def get_angle(a, b, c):<br>    a = np.array([a.x, a.y])<br>    b = np.array([b.x, b.y])<br>    c = np.array([c.x, c.y])<br>    ba = a - b<br>    bc = c - b<br>    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))<br>    angle = np.arccos(cosine_angle)<br>    return np.degrees(angle)<br><br>def squat_feedback(landmarks):<br>    left_hip = landmarks.landmark[23]<br>    left_knee = landmarks.landmark[25]<br>    left_ankle = landmarks.landmark[27]<br>    angle = get_angle(left_hip, left_knee, left_ankle)<br>    if angle &lt; 70:<br>        return &quot;Go Higher!&quot;, angle<br>    elif angle &gt; 160:<br>        return &quot;Go Lower!&quot;, angle<br>    else:<br>        return &quot;Good Squat!&quot;, angle<br><br>def pushup_feedback(landmarks):<br>    left_shoulder = landmarks.landmark[11]<br>    left_elbow = landmarks.landmark[13]<br>    left_wrist = landmarks.landmark[15]<br>    angle = get_angle(left_shoulder, left_elbow, left_wrist)<br>    if angle &lt; 60:<br>        return &quot;Push Up!&quot;, angle<br>    elif angle &gt; 160:<br>        return &quot;Go Down!&quot;, angle<br>    else:<br>        return &quot;Good Pushup!&quot;, angle</pre><h3>Step 3: Rep Counting and Stats</h3><p><em>This class tracks the number of repetitions by monitoring angle transitions, helping you keep count of your workout automatically.</em></p><pre>class RepCounter:<br>    def __init__(self, down_angle, up_angle):<br>        self.down_angle = down_angle<br>        self.up_angle = up_angle<br>        self.stage = None<br>        self.reps = 0<br><br>    def update(self, angle):<br>        if angle &gt; self.up_angle:<br>            self.stage = &quot;up&quot;<br>        if angle &lt; self.down_angle and self.stage == &quot;up&quot;:<br>            self.stage = &quot;down&quot;<br>            self.reps += 1<br>        return self.reps</pre><h3>Step 4: Build a Web App with Streamlit</h3><p><em>This Streamlit app captures webcam video, runs pose estimation, displays feedback, and shows your rep count in real time — all in your browser!</em></p><pre># main.py<br><br>import streamlit as st<br>import cv2<br>import mediapipe as mp<br>from feedback import squat_feedback, pushup_feedback<br>from stats import RepCounter<br><br>st.title(&quot;AI Fitness Coach&quot;)<br><br>exercise = st.selectbox(&quot;Choose exercise&quot;, [&quot;Squat&quot;, &quot;Pushup&quot;])<br>run = st.button(&quot;Start Workout&quot;, key=&quot;start_button&quot;)<br><br>if run:<br>    mp_pose = mp.solutions.pose<br>    pose = mp_pose.Pose()<br>    cap = cv2.VideoCapture(0)<br>    counter = RepCounter(down_angle=70, up_angle=160) if exercise == &quot;Squat&quot; else RepCounter(down_angle=60, up_angle=160)<br>    stframe = st.empty()<br>    stop = st.button(&quot;Stop&quot;, key=&quot;stop_button&quot;)  # Create Stop button outside the loop<br>    while cap.isOpened():<br>        if stop:  # Check if Stop button is clicked<br>            break<br>        ret, frame = cap.read()<br>        if not ret:<br>            break<br>        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>        results = pose.process(image)<br>        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>        feedback, angle = &quot;&quot;, 0<br>        if results.pose_landmarks:<br>            if exercise == &quot;Squat&quot;:<br>                feedback, angle = squat_feedback(results.pose_landmarks)<br>            else:<br>                feedback, angle = pushup_feedback(results.pose_landmarks)<br>            reps = counter.update(angle)<br>            cv2.putText(image, f&#39;Reps: {reps}&#39;, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,0), 2)<br>        cv2.putText(image, feedback, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)<br>        stframe.image(image, channels=&quot;BGR&quot;)<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><h3>Step 5: REST API for Mobile/Web Integration</h3><p><em>This FastAPI app exposes a REST endpoint so you can send images (from a mobile or web client) and receive pose feedback as JSON.</em></p><pre>from fastapi import FastAPI, File, UploadFile<br>from fastapi.responses import JSONResponse<br>import cv2<br>import numpy as np<br>import mediapipe as mp<br>from feedback import squat_feedback, pushup_feedback<br><br>app = FastAPI()<br>mp_pose = mp.solutions.pose<br>pose = mp_pose.Pose(static_image_mode=True)<br><br>@app.post(&quot;/pose/&quot;)<br>async def analyze_pose(exercise: str, file: UploadFile = File(...)):<br>    contents = await file.read()<br>    nparr = np.frombuffer(contents, np.uint8)<br>    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)<br>    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>    results = pose.process(image_rgb)<br>    if not results.pose_landmarks:<br>        return JSONResponse({&quot;feedback&quot;: &quot;No person detected&quot;, &quot;angle&quot;: None, &quot;reps&quot;: None})<br>    if exercise.lower() == &quot;squat&quot;:<br>        feedback, angle = squat_feedback(results.pose_landmarks)<br>    elif exercise.lower() == &quot;pushup&quot;:<br>        feedback, angle = pushup_feedback(results.pose_landmarks)<br>    else:<br>        feedback, angle = &quot;Unknown exercise&quot;, None<br>    return JSONResponse({&quot;feedback&quot;: feedback, &quot;angle&quot;: angle})</pre><p>Sample Rest Client:</p><pre>import requests<br><br>with open(&quot;test_squat.jpg&quot;, &quot;rb&quot;) as f:<br>    files = {&quot;file&quot;: f}<br>    response = requests.post(&quot;http://localhost:8000/pose/?exercise=squat&quot;, files=files)<br>    print(response.json())</pre><h3>Step 6: Try It Yourself!</h3><ul><li><strong>Run the web app:</strong><br>streamlit run main.py</li><li><strong>Run the REST API:</strong><br>uvicorn app:app --reload</li><li><strong>Integrate with your mobile/web app</strong> for a seamless AI fitness experience.</li></ul><p><em>If you enjoyed this, follow for more AI, fitness, and coding tutorials!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a787e901efe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transform PDFs into Intelligent Assistants: A Step-by-Step Guide]]></title>
            <link>https://satishkumarandey.medium.com/transform-pdfs-into-intelligent-assistants-a-step-by-step-guide-5c62a71546b3?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c62a71546b3</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 06:14:59 GMT</pubDate>
            <atom:updated>2025-03-06T06:14:59.950Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine transforming your dense PDF documents into interactive knowledge bases, ready to answer your burning questions with remarkable accuracy. No more endless scrolling or Ctrl+F hunts. What if you could extract the wisdom locked within those pages and put it to work?</p><figure><img alt="https://dezgo.com/" src="https://cdn-images-1.medium.com/max/1024/1*evDkHqnSTmzoHcd01fGQZg.png" /></figure><p>In this article, we’ll embark on a journey to do just that, leveraging the power of Python, OCR, and cutting-edge Hugging Face transformers. We’ll walk through a step-by-step process to convert PDFs into images, extract text using OCR, create a question-answering dataset, and train a model capable of achieving over 90% accuracy.</p><p>Ready to dive in? Let’s get started.</p><p><strong>The Magic Ingredients: Dependencies</strong></p><p>First, ensure you have the necessary libraries installed:</p><pre>pip install pdf2image pytesseract transformers datasets</pre><p><strong>Step 1: Unlocking the Visual Content — PDF to Images</strong></p><p>We begin by converting the PDF into a series of images, allowing us to process each page visually.</p><pre>from pdf2image import convert_from_path<br><br>def pdf_to_images(pdf_path, output_folder):<br>    images = convert_from_path(pdf_path)<br>    for i, image in enumerate(images):<br>        image_path = f&quot;{output_folder}/page_{i + 1}.png&quot;<br>        image.save(image_path, &#39;PNG&#39;)<br>        print(f&quot;Saved {image_path}&quot;)<br>pdf_path = &#39;path/to/your/pdf_file.pdf&#39;<br>output_folder = &#39;path/to/output/folder&#39;<br>pdf_to_images(pdf_path, output_folder)</pre><p><strong>Step 2: Decoding the Pixels — OCR with Tesseract</strong></p><p>Next, we employ Optical Character Recognition (OCR) to extract the text from the generated images.</p><pre>import pytesseract<br>from PIL import Image<br>import os<br><br>def ocr_images(image_folder, output_file):<br>    text_data = []<br>    for image_file in os.listdir(image_folder):<br>        if image_file.endswith(&#39;.png&#39;):<br>            image_path = os.path.join(image_folder, image_file)<br>            text = pytesseract.image_to_string(Image.open(image_path))<br>            text_data.append(text)<br>            print(f&quot;Extracted text from {image_path}&quot;)<br>    <br>    with open(output_file, &#39;w&#39;) as f:<br>        f.write(&quot;\n&quot;.join(text_data))<br>        print(f&quot;Saved OCR text to {output_file}&quot;)<br>image_folder = &#39;path/to/output/folder&#39;<br>output_file = &#39;path/to/output/ocr_text.txt&#39;<br>ocr_images(image_folder, output_file)</pre><p><strong>Important:</strong> Ensure you have Tesseract installed and configured correctly. You can download it from <a href="https://www.google.com/url?sa=E&amp;source=gmail&amp;q=https://tesseract-ocr.github.io/tessdoc/Installation.html">https://tesseract-ocr.github.io/tessdoc/Installation.html</a>.</p><p><strong>Step 3: Crafting the Knowledge Base — Creating a Question Answering Dataset</strong></p><p>Now, we structure the extracted text into a dataset suitable for training our question-answering model. We’ll use the SQuAD format, a standard for question-answering tasks.</p><pre>import json<br><br>def create_qa_dataset(ocr_text_file, qa_dataset_file):<br>    with open(ocr_text_file, &#39;r&#39;) as f:<br>        text = f.read()<br>    <br>    # Example dataset structure<br>    dataset = {<br>        &quot;data&quot;: [<br>            {<br>                &quot;title&quot;: &quot;Document&quot;,<br>                &quot;paragraphs&quot;: [<br>                    {<br>                        &quot;context&quot;: text,<br>                        &quot;qas&quot;: [<br>                            {<br>                                &quot;question&quot;: &quot;Your question here&quot;,<br>                                &quot;id&quot;: &quot;1&quot;,<br>                                &quot;answers&quot;: [<br>                                    {<br>                                        &quot;text&quot;: &quot;Expected answer here&quot;,<br>                                        &quot;answer_start&quot;: text.find(&quot;Expected answer here&quot;)<br>                                    }<br>                                ]<br>                            }<br>                        ]<br>                    }<br>                ]<br>            }<br>        ]<br>    }<br>    <br>    with open(qa_dataset_file, &#39;w&#39;) as f:<br>        json.dump(dataset, f, indent=4)<br>        print(f&quot;Saved QA dataset to {qa_dataset_file}&quot;)<br>ocr_text_file = &#39;path/to/output/ocr_text.txt&#39;<br>qa_dataset_file = &#39;path/to/output/qa_dataset.json&#39;<br>create_qa_dataset(ocr_text_file, qa_dataset_file)</pre><p><strong>Crucial Step:</strong> You will need to manually add questions and answers to the dataset structure, using the extracted text as the context. This is the heart of your knowledge base.</p><p><strong>Step 4: Training the Brain — Question Answering with Hugging Face Transformers</strong></p><p>Finally, we leverage the power of Hugging Face transformers to train a question-answering model.</p><pre>from transformers import AutoTokenizer, AutoModelForQuestionAnswering, Trainer, TrainingArguments<br>from datasets import load_dataset, load_metric<br><br>def train_qa_model(qa_dataset_file):<br>    dataset = load_dataset(&#39;json&#39;, data_files=qa_dataset_file)<br>    tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>    model = AutoModelForQuestionAnswering.from_pretrained(&quot;bert-base-uncased&quot;)<br>    def preprocess_function(examples):<br>        questions = [q.strip() for q in examples[&quot;question&quot;]]<br>        inputs = tokenizer(<br>            questions,<br>            examples[&quot;context&quot;],<br>            max_length=384,<br>            truncation=&quot;only_second&quot;,<br>            return_offsets_mapping=True,<br>            padding=&quot;max_length&quot;,<br>        )<br>        return inputs<br>    tokenized_dataset = dataset.map(preprocess_function, batched=True)<br>    training_args = TrainingArguments(<br>        output_dir=&quot;./results&quot;,<br>        evaluation_strategy=&quot;epoch&quot;,<br>        learning_rate=2e-5,<br>        per_device_train_batch_size=16,<br>        per_device_eval_batch_size=16,<br>        num_train_epochs=3,<br>        weight_decay=0.01,<br>    )<br>    trainer = Trainer(<br>        model=model,<br>        args=training_args,<br>        train_dataset=tokenized_dataset[&quot;train&quot;],<br>        eval_dataset=tokenized_dataset[&quot;validation&quot;],<br>    )<br>    trainer.train()<br>    trainer.evaluate()<br>qa_dataset_file = &#39;path/to/output/qa_dataset.json&#39;<br>train_qa_model(qa_dataset_file)</pre><p><strong>Achieving 90%+ Accuracy:</strong></p><p>Reaching high accuracy requires careful dataset creation. Ensure your questions and answers are precise and cover the key information in your PDF. Experiment with different pre-trained models and fine-tune hyperparameters to optimize performance.</p><p><strong>Beyond the Basics:</strong></p><p>This is just the beginning. You can enhance this process by:</p><ul><li><strong>Improving OCR Accuracy:</strong> Using pre-processing techniques like image denoising and deskewing.</li><li><strong>Handling Complex Layouts:</strong> Implementing layout analysis to preserve document structure.</li><li><strong>Integrating with APIs:</strong> Building a web application to provide question-answering as a service.</li><li><strong>Using more advanced models:</strong> Try models like RoBERTa or DistilBERT for potentially better results.</li></ul><p>By following these steps, you can unlock the hidden potential of your PDFs and transform them into powerful knowledge tools. Let us know in the comments how you plan to use this technique!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c62a71546b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Real-Time Object Detection: Deploy YOLO on Your Orin Nano 8GB with Ease]]></title>
            <link>https://satishkumarandey.medium.com/master-real-time-object-detection-deploy-yolo-on-your-orin-nano-8gb-with-ease-e50d3f2215dc?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50d3f2215dc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[nividia]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 05:38:06 GMT</pubDate>
            <atom:updated>2025-01-16T05:48:07.185Z</atom:updated>
            <content:encoded><![CDATA[<p>Overview: In the world of artificial intelligence and machine learning, real-time object detection is a game-changer. Whether you’re working on a personal project or developing a cutting-edge application, leveraging the power of YOLO (You Only Look Once) on an NVIDIA Orin Nano 8GB device can significantly enhance your capabilities. In this article, we’ll guide you through the process of setting up your Orin Nano with Jetpack 6.2 and running a YOLO-based visual detection algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wrs6yUY0U08xzJHWzWNhg.png" /></figure><h3>Why YOLO and Orin Nano?</h3><p>YOLO is renowned for its speed and accuracy in object detection tasks. When combined with the powerful Orin Nano 8GB, you get a compact yet robust platform capable of handling complex computations efficiently. This setup is ideal for developers, researchers, and hobbyists looking to explore the realms of computer vision.</p><h3>Prerequisites</h3><p>Before diving into the setup, ensure you have the following:</p><ol><li>An NVIDIA Orin Nano 8GB device.</li><li>A clean installation of Jetpack 6.2.</li><li>Basic knowledge of Python and OpenCV.</li><li>An image file for testing the YOLO model.</li></ol><h3>Step-by-Step Guide</h3><h3>Step 1: Prepare Your Orin Nano 8GB Device</h3><p>Start by flashing the Jetpack 6.2 image onto your SD card. Insert the SD card into the Orin Nano and power it on. Follow the on-screen instructions to complete the initial setup, including language and timezone configurations.</p><h3>Step 2: Install Necessary Dependencies</h3><p>Open a terminal on your Orin Nano and run the following commands to update your package list and install Python along with other required libraries:</p><pre>sudo apt-get update<br>sudo apt-get upgrade -y<br>sudo apt-get install -y python3-pip<br>pip3 install numpy opencv-python</pre><h3>Step 3: Set Up YOLO for Visual Detection</h3><p>Clone the YOLO repository and download the pre-trained weights:</p><pre>git clone https://github.com/AlexeyAB/darknet.git<br>cd darknet<br>make<br>wget https://pjreddie.com/media/files/yolov3.weights -O yolov3.weights</pre><h3>Step 4: Run a Sample YOLO Detection Script</h3><p>Create a Python script to load the YOLO model and perform detection on a sample image. Here’s a sample script to get you started:</p><pre>import cv2<br>import numpy as np<br><br>def load_image(img_path):<br>    img = cv2.imread(img_path)<br>    height, width, channels = img.shape<br>    return img, height, width, channels<br><br>def detect_objects(img, net, output_layers):<br>    blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)<br>    net.setInput(blob)<br>    outs = net.forward(output_layers)<br>    return outs<br><br>def draw_labels(img, outs, height, width):<br>    class_ids = []<br>    confidences = []<br>    boxes = []<br>    for out in outs:<br>        for detection in out:<br>            scores = detection[5:]<br>            class_id = np.argmax(scores)<br>            confidence = scores[class_id]<br>            if confidence &gt; 0.5:<br>                center_x = int(detection[0] * width)<br>                center_y = int(detection[1] * height)<br>                w = int(detection[2] * width)<br>                h = int(detection[3] * height)<br>                x = int(center_x - w / 2)<br>                y = int(center_y - h / 2)<br>                boxes.append([x, y, w, h])<br>                confidences.append(float(confidence))<br>                class_ids.append(class_id)<br>    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)<br>    for i in range(len(boxes)):<br>        if i in indexes:<br>            x, y, w, h = boxes[i]<br>            label = str(classes[class_ids[i]])<br>            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)<br>            cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)<br>    return img<br><br>if __name__ == &quot;__main__&quot;:<br>    net = cv2.dnn.readNet(&quot;darknet/yolov3.weights&quot;, &quot;darknet/cfg/yolov3.cfg&quot;)<br>    layer_names = net.getLayerNames()<br>    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]<br>    classes = open(&quot;darknet/data/coco.names&quot;).read().strip().split(&quot;\n&quot;)<br><br>    img_path = &quot;path_to_your_image.jpg&quot;<br>    img, height, width, channels = load_image(img_path)<br>    outs = detect_objects(img, net, output_layers)<br>    img = draw_labels(img, outs, height, width)<br>    cv2.imshow(&quot;Image&quot;, img)<br>    cv2.waitKey(0)<br>    cv2.destroyAllWindows()</pre><p>Replace &quot;path_to_your_image.jpg&quot; with the path to your test image. This script will load the YOLO model, perform object detection, and display the results.</p><h3>Conclusion</h3><p>By following this guide, you can harness the power of YOLO on your Orin Nano 8GB device, enabling real-time object detection for your projects. This setup not only enhances your development capabilities but also opens up new possibilities in the field of computer vision.</p><p>If you found this article helpful, don’t forget to share it with your peers and subscribe to our blog for more insightful tutorials and updates. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50d3f2215dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speech Analysis using Parselmouth]]></title>
            <link>https://satishkumarandey.medium.com/speech-analysis-using-parselmouth-7bb1a2760cc9?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb1a2760cc9</guid>
            <category><![CDATA[speech-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 06:50:01 GMT</pubDate>
            <atom:updated>2024-10-15T06:50:01.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: Speech analysis is a crucial aspect of various applications, including emotion detection, speaker recognition, and linguistic research. The Parselmouth library, a Python interface to Praat, offers powerful tools for analyzing speech. This article will guide you through the process of using Parselmouth for speech analysis, from installation to feature extraction and emotion detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5D9oUsJqa2HiceCBbXCCpw.png" /><figcaption><a href="https://dezgo.com/">https://dezgo.com/</a></figcaption></figure><ol><li>Installation: To get started with Parselmouth, you need to install the library and ensure Praat is installed on your system.</li></ol><pre>pip install praat-parselmouth</pre><p>2. Loading Audio Files: Load your emotional speech recordings from the specified directory.</p><pre>import parselmouth<br>import os<br><br>def load_audio_files(directory):<br>    audio_files = []<br>    for filename in os.listdir(directory):<br>        if filename.endswith(&quot;.wav&quot;):<br>            audio_files.append(os.path.join(directory, filename))<br>    return audio_files</pre><p>3. Feature Extraction: Using Parselmouth, you can extract various features such as pitch, intensity, jitter, shimmer, and Harmonics-to-Noise Ratio (HNR).</p><pre>import parselmouth<br><br>def extract_features(audio_file):<br>    sound = parselmouth.Sound(audio_file)<br>    pitch = sound.to_pitch()<br>    intensity = sound.to_intensity()<br><br>    pitch_mean = pitch.get_mean()<br>    pitch_min = pitch.get_minimum()<br>    pitch_max = pitch.get_maximum()<br>    intensity_mean = intensity.get_mean()<br><br>    point_process = parselmouth.praat.call(sound, &quot;To PointProcess (periodic, cc)&quot;, 75, 500)<br>    jitter = parselmouth.praat.call(point_process, &quot;Get jitter (local)&quot;, 0.0001, 0.02, 0.02, 1.3)<br>    shimmer = parselmouth.praat.call([sound, point_process], &quot;Get shimmer (local)&quot;, 0.0001, 0.02, 1.3, 1.6)<br>    hnr = parselmouth.praat.call(sound, &quot;Get harmonicity (cc)&quot;, 0.01, 75, 0.1, 1.0)<br><br>    return {<br>        &quot;pitch_mean&quot;: pitch_mean,<br>        &quot;pitch_min&quot;: pitch_min,<br>        &quot;pitch_max&quot;: pitch_max,<br>        &quot;intensity_mean&quot;: intensity_mean,<br>        &quot;jitter&quot;: jitter,<br>        &quot;shimmer&quot;: shimmer,<br>        &quot;hnr&quot;: hnr<br>    }</pre><p>4. Emotion Detection: For emotion detection, we can use a pre-trained model. Here, we use a RandomForestClassifier trained on numerical features:</p><pre>from sklearn.ensemble import RandomForestClassifier<br>import joblib<br><br># Load the pre-trained model, <br># Will write a separate article on how to train pretrained model on audio files.<br>emotion_classifier = joblib.load(&#39;emotion_model.pkl&#39;) <br><br>def detect_emotion(features):<br>    feature_values = [<br>        features[&#39;pitch_mean&#39;],<br>        features[&#39;intensity_mean&#39;],<br>        features[&#39;jitter&#39;],<br>        features[&#39;shimmer&#39;],<br>        features[&#39;hnr&#39;]<br>    ]<br>    result = emotion_classifier.predict([feature_values])<br>    return result[0]</pre><p>5. Saving and Analyzing Features: Save the extracted features into a CSV file for further analysis and perform a brief analysis:</p><pre>import pandas as pd<br><br>def process_audio_files(directory):<br>    features_list = []<br>    for filename in os.listdir(directory):<br>        if filename.endswith(&quot;.wav&quot;):<br>            audio_file = os.path.join(directory, filename)<br>            features = extract_features(audio_file)<br>            features[&quot;file&quot;] = filename<br>            features_list.append(features)<br><br>    return pd.DataFrame(features_list)<br><br>def main():<br>    audio_directory = &quot;path/to/your/audio/files&quot;<br>    features_df = process_audio_files(audio_directory)<br>    features_df.to_csv(&quot;extracted_features.csv&quot;, index=False)<br>    print(features_df.groupby(&quot;file&quot;)[&quot;pitch_mean&quot;].mean())<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Summary:</p><p>Parselmouth provides a robust interface to Praat, enabling detailed speech analysis. By following this guide, you can extract meaningful features from speech recordings and use them for various applications, including emotion detection. Start exploring the capabilities of Parselmouth today and unlock the potential of speech analysis in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb1a2760cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger Query Engine with LangChain]]></title>
            <link>https://satishkumarandey.medium.com/swagger-query-engine-with-langchain-6ff2416fd1fa?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ff2416fd1fa</guid>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 15:33:54 GMT</pubDate>
            <atom:updated>2024-09-11T22:55:42.808Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will discuss how to query the swagger file using LangChain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9bTRtSNfdYjKE0CqF0ILQ.png" /><figcaption>From <a href="https://dezgo.com/">https://dezgo.com/</a></figcaption></figure><p><strong>LangChain</strong>: A framework for building applications with large language models (LLMs). It provides tools for document loading, text splitting, vector storage, and more.</p><p><strong>RAG</strong> (Retrieval-Augmented Generation): RAG is a technique for augmenting LLM knowledge with additional data.</p><p><strong>Llama3.1</strong>: A large language model used for generating responses based on the retrieved documents.</p><p><strong>Ollama</strong>: A library that provides access to various LLMs, including Llama3.1.</p><p><strong>Streamlit</strong>: An open-source app framework for creating and sharing data applications. It is used to build the user interface for this application.</p><p><strong><em>The RAG steps are converted using LangChain as follows.</em></strong></p><ol><li><strong>Indexing:</strong> a pipeline for ingesting data from a source and indexing it. <em>This usually happens offline.</em></li><li><strong>Retrieval and generation: </strong>the actual RAG chain, which takes the user query at run time and retrieves the relevant data from the index, then passes that to the model.</li></ol><h3>1. Indexing:</h3><ol><li><strong>Load</strong>: First we need to load our data. This is done with <a href="https://python.langchain.com/v0.2/docs/concepts/#document-loaders">Document Loaders</a>.</li></ol><pre>def load_documents(file):<br>    print(&quot;Loading documents...&quot;)<br>    # Read the uploaded file<br>    file_content = file.read().decode(&quot;utf-8&quot;)<br>    # Save the content to a temporary file<br>    with open(&quot;temp.json&quot;, &quot;w&quot;) as temp_file:<br>        temp_file.write(file_content)<br>    # Load the documents using TextLoader<br>    loader = JSONLoader(&quot;temp.json&quot;, jq_schema=&#39;.&#39;, text_content=False)<br>    documents = loader.load()<br>    return documents</pre><p>2. Split: <a href="https://python.langchain.com/v0.2/docs/concepts/#text-splitters">Text splitters</a> break large Documents into smaller chunks. This is useful both for indexing data and for passing it in to a model, since large chunks are harder to search over and won&#39;t fit in a model&#39;s finite context window.</p><pre>def transform_documents(documents):<br>    text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>    documents = text_splitter.split_documents(documents)<br>    print(&quot;Transformed documents...size=&quot;, len(documents))<br>    return documents</pre><p>3. Store: We need somewhere to store and index our splits, so that they can later be searched over. This is often done using a <a href="https://python.langchain.com/v0.2/docs/concepts/#vector-stores">VectorStore</a> and <a href="https://python.langchain.com/v0.2/docs/concepts/#embedding-models">Embeddings</a> model.</p><pre>def get_embedded_model():<br>    model_name = &quot;BAAI/bge-large-en-v1.5&quot;<br>    model_kwargs = {&#39;device&#39;: &#39;cpu&#39;}<br>    encode_kwargs = {&#39;normalize_embeddings&#39;: True}<br>    embedded_model = HuggingFaceEmbeddings(<br>        model_name=model_name,<br>        model_kwargs=model_kwargs,<br>        encode_kwargs=encode_kwargs,<br>        show_progress=True<br>    )<br>    return embedded_model<br><br>def embedded_documents(file):<br>    documents = load_documents(file)<br>    documents = transform_documents(documents)<br>    return documents<br><br>def store_embeddings_in_vectordb(file):<br>    documents = embedded_documents(file)<br>    embedded_model = get_embedded_model()<br>    db = Chroma.from_documents(documents, embedded_model)<br>    return db</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*trenOplVC6xdZ1vH.png" /><figcaption>Ref LangChain</figcaption></figure><h3>2. Retrieval and Generation</h3><p>4. <strong>Retrieve</strong>: Given a user input, relevant splits are retrieved from storage using a <a href="https://python.langchain.com/v0.2/docs/concepts/#retrievers">Retriever</a>.</p><pre>def get_retriever(file):<br>    db = store_embeddings_in_vectordb(file)<br>    retriever = db.as_retriever()<br>    return retriever<br><br><br>documents = retriever.get_relevant_documents(input)</pre><p>5. <strong>Generate</strong>: A <a href="https://python.langchain.com/v0.2/docs/concepts/#chat-models">ChatModel</a> / <a href="https://python.langchain.com/v0.2/docs/concepts/#llms">LLM</a> produces an answer using a prompt that includes the question and the retrieved data</p><pre>def get_chat_promppt():<br>    prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;context: {context} Given the context information above I want you to answer the query in a crisp manner, incase case you don&#39;t know the answer say &#39;I don&#39;t know!: Question: {question}&quot;&quot;&quot;)<br>    return prompt<br><br>def get_model():<br>    model = OllamaLLM(model=&quot;llama3.1&quot;)<br>    return model<br><br>formatted = prompt.invoke({&quot;context&quot;: documents,&quot;question&quot;: input})<br><br>answer = model.invoke(formatted)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*rkPyjvfaD5JqZZRd.png" /><figcaption>Ref LangChain</figcaption></figure><p>StreamLit WebUI with complete code:</p><pre>import streamlit as st<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_community.document_loaders import JSONLoader<br>from langchain_community.vectorstores import Chroma<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_huggingface.embeddings import HuggingFaceEmbeddings<br>from langchain_ollama.llms import OllamaLLM<br><br><br># Document Loader<br>def load_documents(file):<br>    print(&quot;Loading documents...&quot;)<br>    # Read the uploaded file<br>    file_content = file.read().decode(&quot;utf-8&quot;)<br>    # Save the content to a temporary file<br>    with open(&quot;temp.json&quot;, &quot;w&quot;) as temp_file:<br>        temp_file.write(file_content)<br>    # Load the documents using TextLoader<br>    loader = JSONLoader(&quot;temp.json&quot;, jq_schema=&#39;.&#39;, text_content=False)<br>    documents = loader.load()<br>    return documents<br><br><br>def transform_documents(documents):<br>    text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>    documents = text_splitter.split_documents(documents)<br>    print(&quot;Transformed documents...size=&quot;, len(documents))<br>    return documents<br><br><br>def embedded_documents(file):<br>    documents = load_documents(file)<br>    documents = transform_documents(documents)<br>    embedded_model = HuggingFaceEmbeddings(model_name=&quot;BAAI/bge-large-en-v1.5&quot;)<br>    return documents, embedded_model<br><br><br>def store_embeddings_in_vectordb(file):<br>    documents, embedded_model = embedded_documents(file)<br>    db = Chroma.from_documents(documents, embedded_model)<br>    st.write(&quot;Ready to chat&quot;)<br>    return db<br><br><br>def get_retriever(file):<br>    db = store_embeddings_in_vectordb(file)<br>    retriever = db.as_retriever()<br>    return retriever<br><br><br>def get_model():<br>    model = OllamaLLM(model=&quot;llama3.1&quot;)<br>    return model<br><br><br>def get_chat_promppt():<br>    prompt = ChatPromptTemplate.from_template(<br>        &quot;&quot;&quot;context: {context} Given the context information above I want you to answer the query in a crisp manner, incase case you don&#39;t know the answer say &#39;I don&#39;t know!: Question: {question}&quot;&quot;&quot;)<br>    return prompt<br><br><br>def qa_rag(input, db):<br>    retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 1})<br>    prompt = get_chat_promppt()<br>    model = get_model()<br>    documents = retriever.get_relevant_documents(input)<br>    print(&quot;Retrieved documents size&quot;, len(documents))<br>    print(documents)<br>    formatted = prompt.invoke({&quot;context&quot;: documents, &quot;question&quot;: input})<br><br>    answer = model.invoke(formatted)<br>    return answer<br><br><br>def main():<br>    st.title(&quot;Swagger QA langchain system&quot;)<br>    question = st.text_input(&quot;Enter your question:&quot;)<br>    with st.sidebar:<br>        uploaded_file = st.file_uploader(&quot;Upload a Swagger file in JSON format&quot;, type=&quot;json&quot;)<br>        if uploaded_file is not None:<br>            db = store_embeddings_in_vectordb(uploaded_file)<br>            st.success(&quot;File uploaded successfully and ready for processing.&quot;)<br><br>    if uploaded_file is not None:<br>        if st.button(&quot;Get Answer&quot;):<br>            if question:<br>                answer = qa_rag(question, db)<br>                st.write(answer)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Run the app using ``` streamlit run swaggerlc.py ```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dd30k63xaTwVUEGhVzdpXQ.jpeg" /></figure><p>Summary:</p><p>We used the Ollama library to run the LLama3.1 LLM models to run locally, and we used LangChain to build the pipeline and streamlit library to build a web UI and able to ask any questions related to the uploaded swagger file and get the response.</p><p>If you would like to use LlamaIndex instead of LangChain refer to my other article.</p><p><a href="https://medium.com/@satishkumarandey/introducing-the-swagger-query-engine-using-llamaindex-44fa8bbda139">https://medium.com/@satishkumarandey/introducing-the-swagger-query-engine-using-llamaindex-44fa8bbda139</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ff2416fd1fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Swagger Query Engine using LlamaIndex]]></title>
            <link>https://satishkumarandey.medium.com/introducing-the-swagger-query-engine-using-llamaindex-44fa8bbda139?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/44fa8bbda139</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[llama-3-1]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 20:22:15 GMT</pubDate>
            <atom:updated>2024-08-27T19:53:53.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyjU92Ems9SIxkVIkW2t-g.jpeg" /><figcaption>From DallE</figcaption></figure><p>Do you struggle deciphering complex API documentation written in Swagger format? Imagine a user-friendly interface where you can simply ask questions about your API and get clear, concise answers in real-time. This become reality with cutting-edge AI technology tools like Ollama, Llama3.1, RAG architecture, Streamlit and LlamaIndex.</p><p><strong>Streamlit:</strong> A Python library for creating interactive web applications quickly and easily.</p><p><strong>RAG:</strong> An information retrieval technique that combines retrieval (finding relevant information) and generation (summarizing or answering questions based on the retrieved information).</p><p><strong>Llama 3.1:</strong> A state-of-the-art large language model from Meta capable of understanding and responding to complex queries.</p><p><strong>Ollama</strong>: It’s an open-source, serverless platform for running large language models (LLMs) locally or in the cloud. It provides a user-friendly interface and supports various LLM models, including those from OpenAI, Hugging Face, and others.</p><p><strong>LlamaIndex</strong>: A python library that simplifies the process of building and managing large language model (LLM) applications. It provides a flexible framework for organizing and querying information, making it easier to leverage the power of LLMs for various tasks.</p><p><strong><em>The complete RAG flow involves the following 4 main steps:</em></strong></p><ol><li><em>Document Ingestion</em>: Load documents from various file types and store them in a vector database.</li><li><em>Indexing</em>: Create indexes for the ingested documents to facilitate efficient retrieval.</li><li><em>Query Processing</em>: When a query is received, retrieve relevant documents from the vector database.</li><li><em>Response Generation</em>: Use the retrieved documents to generate a response.</li></ol><p><strong><em>The RAG steps converted using Llamaindx as follows.</em></strong></p><ol><li>Loading data as Documents</li><li>Parsing Documents into coherent Nodes &amp; Building an optimized index from Nodes</li><li>Running queries over the index to retrieve relevant Nodes</li><li>Synthesizing the final response</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tV_dzc7I7aMtNL_W52WTUA.jpeg" /><figcaption>Reference from <a href="https://lightning.ai/">LightPlus Editor</a></figcaption></figure><p><strong>PreRequisites:</strong></p><p>Run ollama locally by downloading the binary or docker container from the link.</p><p><a href="https://ollama.com/">Ollama · Run AI models locally and in the cloud</a></p><p><strong>LlamaIndex implementation:</strong></p><ol><li>Loading data as Documents</li></ol><pre>from llama_index.readers.json import JSONReader<br>from llama_index.core import Settings, PromptTemplate, VectorStoreIndex, SimpleDirectoryReader, \<br>    StorageContext, load_index_from_storage<br><br>file_path = &quot;./SwaggerPetstore&quot;<br>reader = JSONReader()<br># documents = SimpleDirectoryReader(file_path, filename_as_id=True).load_data()<br>docs = reader.load_data(input_file=file_path, extra_info={})</pre><p>2. Parsing Documents into coherent Nodes &amp; Building an optimized index from Nodes</p><pre>from llama_index.core.ingestion import IngestionPipeline, IngestionCache<br>from llama_index.embeddings.huggingface import HuggingFaceEmbedding<br>from llama_index.core import Settings, PromptTemplate, VectorStoreIndex, SimpleDirectoryReader, \<br>    StorageContext, load_index_from_storage<br><br><br>INDEX_STORAGE = &quot;index_storage&quot;<br>CACHE_FILE = &quot;cache_file&quot;<br>CHROMA_DB_PATH = &quot;chrom_db&quot;<br><br>def ingest_pipeline(documents):<br>    try:<br>        cached_hashes = IngestionCache.from_persist_path(CACHE_FILE)<br>        print(&quot;Cache file found. Running using cache...&quot;)<br>    except:<br>        cached_hashes = &quot;&quot;<br>        print(&quot;No cache file found. Running without...&quot;)<br><br>    embed_model = HuggingFaceEmbedding(model_name=&quot;BAAI/bge-large-en-v1.5&quot;, trust_remote_code=True)<br><br>    Settings.embed_model = embed_model<br><br>    pipeline = IngestionPipeline(<br>        transformations=[<br>            TokenTextSplitter(chunk_size=1024, chunk_overlap=20),<br>            embed_model<br>        ],<br>        cache=cached_hashes<br>    )<br>    nodes = pipeline.run(documents=documents)<br>    pipeline.cache.persist(CACHE_FILE)<br>    return nodes<br><br>def chroma_client():<br>    # chroma_client = chromadb.EphemeralClient(chromadb.config.Settings(anonymized_telemetry=False))<br>    chroma_client = chromadb.PersistentClient(path=CHROMA_DB_PATH,<br>                                              settings=chromadb.config.Settings(anonymized_telemetry=False))<br>    chroma_collection = chroma_client.get_or_create_collection(&quot;swagger_catalog&quot;)<br>    return chroma_collection<br><br>def build_indexes(nodes):<br>    try:<br>        storage_context = StorageContext.from_defaults(persist_dir=INDEX_STORAGE)<br>        vector_index = load_index_from_storage(storage_context, index_id=&quot;vector&quot;)<br>        print(&quot;All indices loaded from storage.&quot;)<br>    except Exception as e:<br>        print(f&quot;Error occurred while loading indices: {e}&quot;)<br>        vector_store = ChromaVectorStore(chroma_collection=chroma_client())<br>        storage_context = StorageContext.from_defaults(vector_store=vector_store)<br>        vector_index = VectorStoreIndex(nodes, vector_store=vector_store, storage_context=storage_context)<br>        vector_index.set_index_id(&quot;vector&quot;)<br>        storage_context.persist(persist_dir=INDEX_STORAGE)<br>        print(&quot;New indexes created and persisted.&quot;)<br>    return vector_index</pre><p>3. Running queries over the index to retrieve relevant Nodes</p><pre> <br>query_engine = index.as_query_engine(streaming=True, similarity_top_k=3)</pre><p>4. Synthesizing the final response</p><pre>qa_prompt_tmpl_str = (<br>                            &quot;Context information is below.\n&quot;<br>                            &quot;---------------------\n&quot;<br>                            &quot;{context_str}\n&quot;<br>                            &quot;---------------------\n&quot;<br>                            &quot;Given the context information above I want you to think step by step to answer the query in a crisp manner, incase case you don&#39;t know the answer say &#39;I don&#39;t know!&#39;.\n&quot;<br>                            &quot;Query: {query_str}\n&quot;<br>                            &quot;Answer: &quot;<br>                        )<br>qa_prompt_tmpl = PromptTemplate(qa_prompt_tmpl_str)<br>query_engine.update_prompts({&quot;response_synthesizer:text_qa_template&quot;: qa_prompt_tmpl})<br><br>streaming_response = query_engine.query(prompt)</pre><p>StreamLit WebUI with complete code:</p><pre>import os<br><br>import base64<br>import gc<br>import tempfile<br>import uuid<br>import logging<br>import sys<br>import json<br>import chromadb<br><br>from llama_index.core import Settings, PromptTemplate, VectorStoreIndex, SimpleDirectoryReader, \<br>    StorageContext, load_index_from_storage<br>from llama_index.llms.ollama import Ollama<br>from llama_index.readers.json import JSONReader<br>from llama_index.embeddings.huggingface import HuggingFaceEmbedding<br>from llama_index.core.ingestion import IngestionPipeline, IngestionCache<br>from llama_index.core.text_splitter import TokenTextSplitter<br>from llama_index.vector_stores.chroma import ChromaVectorStore<br>import streamlit as st<br><br># Constants<br>INDEX_STORAGE = &quot;index_storage&quot;<br>CACHE_FILE = &quot;cache_file&quot;<br>CHROMA_DB_PATH = &quot;chrom_db&quot;<br>EMBEDDED_MODEL_DOWNLOAD_PATH = &quot;embed_model&quot;<br><br># Logging configuration<br>logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)<br>logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))<br><br><br>def chroma_client():<br>    # chroma_client = chromadb.EphemeralClient(chromadb.config.Settings(anonymized_telemetry=False))<br>    chroma_client = chromadb.PersistentClient(path=CHROMA_DB_PATH,<br>                                              settings=chromadb.config.Settings(anonymized_telemetry=False))<br>    chroma_collection = chroma_client.get_or_create_collection(&quot;self_service_catalog&quot;)<br>    return chroma_collection<br><br><br>def view_chroma_data():<br>    chroma_collection = chroma_client()<br>    data = chroma_collection.get()<br>    formatted_data = &quot;\n&quot;.join([json.dumps(item, indent=2) for item in data])<br>    st.markdown(f&quot;### ChromaDB Data\n```json\n{formatted_data}\n```&quot;)<br><br><br>def initialize_session():<br>    if &quot;id&quot; not in st.session_state:<br>        st.session_state.id = uuid.uuid4()<br>        st.session_state.file_cache = {}<br><br><br>def load_llm():<br>    return Ollama(model=&quot;llama3.1&quot;, request_timeout=120.0)<br><br><br>def ingest_documents(filePath):<br>    documents = SimpleDirectoryReader(filePath, filename_as_id=True).load_data()<br>    for doc in documents:<br>        print(doc.id_)<br>    return documents<br><br>def ingest_pipeline(documents):<br>    try:<br>        cached_hashes = IngestionCache.from_persist_path(CACHE_FILE)<br>        print(&quot;Cache file found. Running using cache...&quot;)<br>    except:<br>        cached_hashes = &quot;&quot;<br>        print(&quot;No cache file found. Running without...&quot;)<br>    #os.environ[&#39;REQUESTS_CA_BUNDLE&#39;] = &quot;True&quot;<br>    embed_model = HuggingFaceEmbedding(model_name=&quot;BAAI/bge-large-en-v1.5&quot;, trust_remote_code=True, cache_folder=EMBEDDED_MODEL_DOWNLOAD_PATH)<br><br>    Settings.embed_model = embed_model<br><br>    pipeline = IngestionPipeline(<br>        transformations=[<br>            TokenTextSplitter(chunk_size=1024, chunk_overlap=20),<br>            embed_model<br>        ],<br>        cache=cached_hashes<br>    )<br>    nodes = pipeline.run(documents=documents)<br>    pipeline.cache.persist(CACHE_FILE)<br>    return nodes<br><br><br>def build_indexes(nodes):<br>    try:<br>        storage_context = StorageContext.from_defaults(persist_dir=INDEX_STORAGE)<br>        vector_index = load_index_from_storage(storage_context, index_id=&quot;vector&quot;)<br>        print(&quot;All indices loaded from storage.&quot;)<br>    except Exception as e:<br>        print(f&quot;Error occurred while loading indices: {e}&quot;)<br>        vector_store = ChromaVectorStore(chroma_collection=chroma_client())<br>        storage_context = StorageContext.from_defaults(vector_store=vector_store)<br>        vector_index = VectorStoreIndex(nodes, vector_store=vector_store, storage_context=storage_context)<br>        vector_index.set_index_id(&quot;vector&quot;)<br>        storage_context.persist(persist_dir=INDEX_STORAGE)<br>        print(&quot;New indexes created and persisted.&quot;)<br>    return vector_index<br><br><br>def reset_chat():<br>    st.session_state.messages = []<br>    st.session_state.context = None<br>    gc.collect()<br><br><br>def display_pdf(file):<br>    st.markdown(&quot;### PDF Preview&quot;)<br>    base64_pdf = base64.b64encode(file.read()).decode(&quot;utf-8&quot;)<br>    pdf_display = f&quot;&quot;&quot;&lt;iframe src=&quot;data:application/pdf;base64,{base64_pdf}&quot; width=&quot;400&quot; height=&quot;100%&quot; type=&quot;application/pdf&quot; style=&quot;height:100vh; width:100%&quot;&gt;&lt;/iframe&gt;&quot;&quot;&quot;<br>    st.markdown(pdf_display, unsafe_allow_html=True)<br><br><br>def main():<br>    initialize_session()<br>    session_id = st.session_state.id<br><br>    with st.sidebar:<br>        st.header(&quot;Add your documents!&quot;)<br>        uploaded_file = st.file_uploader(&quot;Choose your `.json` file&quot;, type=&quot;json&quot;)<br><br>        if uploaded_file:<br>            try:<br>                with tempfile.TemporaryDirectory() as temp_dir:<br>                    file_path = os.path.join(temp_dir, uploaded_file.name)<br>                    with open(file_path, &quot;wb&quot;) as f:<br>                        f.write(uploaded_file.getvalue())<br><br>                    file_key = f&quot;{session_id}-{uploaded_file.name}&quot;<br>                    st.write(&quot;Indexing your document...&quot;)<br><br>                    if file_key not in st.session_state.get(&#39;file_cache&#39;, {}):<br>                        if os.path.exists(temp_dir):<br>                            reader = JSONReader()<br>                        else:<br>                            st.error(&#39;Could not find the file you uploaded, please check again...&#39;)<br>                            st.stop()<br><br>                        llm = load_llm()<br>                        Settings.llm = llm<br><br>                        docs = reader.load_data(input_file=file_path, extra_info={})<br>                        nodes = ingest_pipeline(docs)<br>                        index = build_indexes(nodes)<br>                        query_engine = index.as_query_engine(streaming=True, similarity_top_k=3)<br><br>                        qa_prompt_tmpl_str = (<br>                            &quot;Context information is below.\n&quot;<br>                            &quot;---------------------\n&quot;<br>                            &quot;{context_str}\n&quot;<br>                            &quot;---------------------\n&quot;<br>                            &quot;Given the context information above I want you to think step by step to answer the query in a crisp manner, incase case you don&#39;t know the answer say &#39;I don&#39;t know!&#39;.\n&quot;<br>                            &quot;Query: {query_str}\n&quot;<br>                            &quot;Answer: &quot;<br>                        )<br>                        qa_prompt_tmpl = PromptTemplate(qa_prompt_tmpl_str)<br>                        query_engine.update_prompts({&quot;response_synthesizer:text_qa_template&quot;: qa_prompt_tmpl})<br><br>                        st.session_state.file_cache[file_key] = query_engine<br>                    else:<br>                        query_engine = st.session_state.file_cache[file_key]<br><br>                    st.success(&quot;Ready to Chat!&quot;)<br>                    view_chroma_data()<br>            except Exception as e:<br>                print(e)<br>                st.error(f&quot;An error occurred: {e}&quot;)<br>                st.stop()<br><br>    col1, col2 = st.columns([6, 1])<br>    with col1:<br>        st.header(&quot;Chat With Swagger Spec&quot;)<br>    with col2:<br>        st.button(&quot;Clear ↺&quot;, on_click=reset_chat)<br><br>    if &quot;messages&quot; not in st.session_state:<br>        reset_chat()<br><br>    for message in st.session_state.messages:<br>        with st.chat_message(message[&quot;role&quot;]):<br>            st.markdown(message[&quot;content&quot;])<br><br>    if prompt := st.chat_input(&quot;What&#39;s up?&quot;):<br>        st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>        with st.chat_message(&quot;user&quot;):<br>            st.markdown(prompt)<br><br>        with st.chat_message(&quot;assistant&quot;):<br>            message_placeholder = st.empty()<br>            full_response = &quot;&quot;<br>            streaming_response = query_engine.query(prompt)<br><br>            for chunk in streaming_response.response_gen:<br>                full_response += chunk<br>                message_placeholder.markdown(full_response + &quot;▌&quot;)<br><br>            message_placeholder.markdown(full_response)<br>        st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: full_response})<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Run the app using ``` streamlit run swaggerqueryengine.py ```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBXDZo32GBWMv_sbKEa9zw.jpeg" /></figure><p>Conclusion:</p><p>We used Ollama library to run the LLama3.1 LLM models to run locally, and we used Llamaindex to build the pipeline and streamlit library to build a webui and able to ask any questions related to uploaded swagger file and get the response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44fa8bbda139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing Virtual Threads in Java: Unlocking Simplicity and Scalability.]]></title>
            <link>https://satishkumarandey.medium.com/embracing-virtual-threads-in-java-unlocking-simplicity-and-scalability-0e3050341946?source=rss-8a774c28484c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e3050341946</guid>
            <category><![CDATA[jdk21]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[jdk-19]]></category>
            <dc:creator><![CDATA[Satish Kumar Andey]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 07:36:47 GMT</pubDate>
            <atom:updated>2024-02-01T07:37:24.019Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong>:</h3><p>Anyone working on improving the TPS of their microservice in Java knows the pain of managing threads in concurrent server applications and faces issues like below.</p><ol><li>Complex Thread management</li><li>Lack of high-level abstractions</li><li>Difficulty in debugging</li><li>Limited scalability</li><li>Shared state, etc</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntWAgX5SdDZIY-tWlTxnwA.png" /><figcaption>AI-generated Virtual Threads image from <a href="https://pixlr.com/">https://pixlr.com/</a></figcaption></figure><h3><strong>Project Loom:</strong></h3><p>Project Loom is an OpenJDK project focused on simplifying concurrency in Java through the introduction of lightweight user-mode threads called virtual threads.</p><h3>Platform Threads:</h3><ol><li>Platform threads are a thin wrapper around an OS thread in Java</li><li>It exclusively runs Java code on its underlying OS thread throughout its entire lifespan.</li><li>Availability of the platform threads is constrained by the number of OS threads.</li><li>Platform threads have a substantial thread stack and other resources managed by the operating system.</li></ol><h3><strong>Virtual Threads:</strong></h3><ol><li>Virtual threads are instances of java.lang.Thread, like platform threads.</li><li>They are not tied to a specific OS thread, offering more flexibility.</li><li>It still runs code on the OS thread, but when a virtual thread encounters a blocking I/O operation, it gets suspended, freeing the associated OS thread for other tasks.</li><li>Implemented similar to virtual memory mapping, many virtual threads to a limited number of OS threads.</li><li>Virtual threads are typically short-lived and have a shallow call stack, handling tasks like a single HTTP client call or a JDBC query.</li><li>It&#39;s suitable for tasks that spend a significant time blocked, waiting for I/O operations, but not intended for prolonged CPU-intensive operations.</li></ol><blockquote><em>Note</em>: <em>Virtual threads are not faster threads; they do not run code any faster than platform threads. They exist to provide scale (higher throughput), not speed (lower latency).</em></blockquote><h3><strong>Creating a Virtual Threads:</strong></h3><pre># Start thread directly<br>Thread thread = Thread.ofVirtual().start(() -&gt; System.out.println(&quot;Hello&quot;));<br>thread.join();<br><br>Runnable task = () -&gt; { System.out.println(&quot;Running virtual thread&quot;);};<br><br># Start virtual thread in a convenient way<br>Thread.startVirtualThread(task)<br><br># Create unstarted virtual thread named virtual-1<br>Thread thread = Thread.ofVirtual().name(&quot;virtual-1&quot;).unstarted(task);<br>thread.start();</pre><p>Virtual thread with Builder</p><pre> try {<br>        Thread.Builder builder = Thread.ofVirtual().name(&quot;virtual-1&quot;);<br>        Runnable task = () -&gt; {<br>            System.out.println(&quot;Running virtual thread&quot;);<br>        };<br>        Thread t = builder.start(task);<br>        System.out.println(&quot;Thread t name: &quot; + t.getName());<br>        t.join();<br>    } catch (InterruptedException e) {<br>        e.printStackTrace();<br>    }<br><br></pre><p>Virtual threads with Executors:</p><pre>try (<br>    ExecutorService myExecutor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    Future&lt;?&gt; future = myExecutor.submit(() -&gt; System.out.println(&quot;Running thread&quot;));<br>    future.get();<br>    System.out.println(&quot;Task completed&quot;);<br>} catch (InterruptedException | ExecutionException e) {<br>    e.printStackTrace();<br>}   <br>or <br><br>ThreadFactory factory = Thread.ofVirtual().factory();<br>ExecutorService factoryservice = Executors.newThreadPerTaskExecutor(factory);</pre><p>Other thread properties:</p><ol><li>Thread.isVirtual() will be used to check the virtual thread.</li><li>The <a href="https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html#setPriority(int)">Thread.setPriority(int)</a> method does not affect virtual threads, which always have a priority of Thread.NORM_PRIORITY.</li><li>The <a href="https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html#setDaemon(boolean)">Thread.setDaemon(boolean)</a> the method does not affect virtual threads, which are always daemon threads.</li><li><a href="https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html#getAllStackTraces()">Thread.getAllStackTraces()</a> now returns a map of all platform threads rather than a map of all threads.</li><li>The -XX:+PreserveFramePointer flag has a drastic negative impact on virtual thread performance.</li></ol><h3><strong>Conclusion:</strong></h3><p>Virtual threads are lightweight threads that reduce the effort of writing, maintaining, and debugging high-throughput concurrent applications.</p><p>References:</p><p><a href="https://docs.oracle.com/en/java/javase/20/core/virtual-threads.html#GUID-DC4306FC-D6C1-4BCC-AECE-48C32C1A8DAA">Core Libraries</a></p><p><a href="https://openjdk.org/jeps/436">https://openjdk.org/jeps/436</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e3050341946" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>