<?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 Zainab Rashid on Medium]]></title>
        <description><![CDATA[Stories by Zainab Rashid on Medium]]></description>
        <link>https://medium.com/@zainab29323?source=rss-98125b146f09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dWtTUcbEqrSZZ-vr</url>
            <title>Stories by Zainab Rashid on Medium</title>
            <link>https://medium.com/@zainab29323?source=rss-98125b146f09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:29:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zainab29323/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 Medical RAG System Using LangChain, FAISS & Gemini: A Complete Guide for Beginners]]></title>
            <link>https://medium.com/@zainab29323/building-a-medical-rag-system-using-langchain-faiss-gemini-a-complete-guide-for-beginners-463ed9356c59?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/463ed9356c59</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 11:17:58 GMT</pubDate>
            <atom:updated>2025-11-28T11:17:58.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79RTsbU9PUg20Ho0F2-6qQ.webp" /><figcaption>RAG</figcaption></figure><p>Retrieval-Augmented Generation (RAG) has quickly become one of the most powerful architectures in modern AI systems. Instead of relying solely on an LLM’s internal memory, a RAG pipeline retrieves small, relevant slices of real-world data and forces the LLM to answer based on those sources.</p><p>In this project, I built a <strong>Medical Question-Answering RAG system</strong> using:</p><ul><li><strong>LangChain (retrievers)</strong></li><li><strong>FAISS (vector store)</strong></li><li><strong>SentenceTransformers (free local embeddings)</strong></li><li><strong>Gemini Flash (LLM for generation)</strong></li><li><strong>Streamlit (interactive UI)</strong></li><li><strong>Kaggle medical dataset</strong> (40,000+ transcriptions)</li></ul><p>The system answers medical questions using real clinical notes, retrieves citations, and generates grounded responses using the Gemini API.</p><p>This blog walks you through the entire process — from dataset preprocessing to deployment — so you can build your own RAG app from scratch.</p><h3>What This Project Does</h3><p>This project answers medical questions like:</p><blockquote>“What findings are common in knee arthroscopy reports?”<em><br> </em>“How is urinary tract infection documented in clinical notes?”<em><br> </em>“What symptoms indicate pneumonia?”</blockquote><p>Instead of guessing, the system:</p><ol><li>Retrieves relevant clinical chunks from a <strong>medical transcription dataset</strong></li><li>Embeds them using <strong>MiniLM</strong></li><li>Searches nearest neighbors via <strong>FAISS</strong></li><li>Sends retrieved context to <strong>Gemini Flash</strong></li><li>Generates a safe, grounded, citation-aware answer</li></ol><p>This ensures the results are:</p><ul><li><strong>Evidence-based</strong></li><li><strong>Hallucination-free</strong></li><li><strong>Medically grounded</strong></li><li><strong>Fully explainable</strong></li></ul><h3>Dataset Used — Medical Transcriptions (Kaggle)</h3><p>Dataset Link:<br> <a href="https://www.kaggle.com/datasets/tboyle10/medicaltranscriptions">https://www.kaggle.com/datasets/tboyle10/medicaltranscriptions</a></p><p>The dataset contains:</p><ul><li><strong>40,000+</strong> clinical notes</li><li><strong>40+ medical specialties</strong></li><li>Operative reports</li><li>Radiology summaries</li><li>Pathology notes</li><li>Consultations</li><li>History &amp; Physical (H&amp;P) exams</li></ul><p>Some example specialties:</p><ul><li>Orthopedics</li><li>Pulmonology</li><li>Gastroenterology</li><li>Neurology</li><li>ENT</li><li>Dermatology</li></ul><p>This makes it perfect for testing a real-world Medical RAG pipeline.</p><h3>Project Architecture</h3><p>A simple 4-stage architecture powers the system:</p><pre>Dataset → Chunker → Vector Store (FAISS) → RAG Pipeline (Retriever + LLM)</pre><h3>1. Preprocessing + Chunking</h3><p>We clean and split long medical notes into smaller chunks (~500–700 characters).</p><h3>2. Embeddings</h3><p>Instead of paid Gemini embeddings (limited quota), I used:</p><p>✔ <strong>SentenceTransformer (all-MiniLM-L6-v2)</strong><br> → Fast<br> → Free<br> → Works offline<br> → High retrieval quality</p><h3>3. Vector Store</h3><p>All embeddings stored in:</p><p>✔ <strong>FAISS IndexFlatL2</strong></p><h3>4. RAG Pipeline</h3><p>Uses:</p><ul><li>FAISS retriever</li><li>Gemini Flash for final answer</li><li>Retrieved chunks passed as context</li></ul><h3>Preprocessing the Dataset</h3><p>We cleaned the text, removed newlines, collapsed spacing, and chunked the notes using a sliding window.</p><p>Example of preprocessing:</p><pre>chunk_size = 700<br>chunk_overlap = 50<br>while start &lt; len(text):<br>    chunk = text[start:end]<br>    all_chunks.append({<br>        &quot;chunk&quot;: chunk,<br>        &quot;specialty&quot;: row[&quot;medical_specialty&quot;],<br>        &quot;sample_name&quot;: row[&quot;sample_name&quot;]<br>    })</pre><p>Final output:<br> preprocessed_chunks.json</p><h3>Building the Vector Store (FAISS)</h3><p>Instead of hitting Gemini’s embedding quota limits, we used free offline embeddings:</p><pre>from sentence_transformers import SentenceTransformer<br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>vector = model.encode(text)</pre><p>Then saved:</p><ul><li>index.faiss</li><li>metadata.json</li></ul><p>Both are required for Streamlit deployment.</p><h3>RAG Pipeline (Retriever + Gemini LLM)</h3><p>The heart of the system is this function:</p><pre>def ask_gemini(question):<br>    chunks = search_similar_chunks(question)<br>    context = &quot;\n\n&quot;.join([c[&quot;chunk&quot;] for c in chunks])<br>    prompt = f&quot;&quot;&quot;<br>    Use ONLY the context below to answer:<br>    Context:<br>    {context}<br>    Question: {question}<br>    &quot;&quot;&quot;<br>    llm = genai.GenerativeModel(&quot;models/gemini-flash-latest&quot;)<br>    response = llm.generate_content(prompt)<br>    return response.text, chunks</pre><p>This ensures:</p><ul><li>No hallucinations</li><li>Every answer is backed by citations</li><li>Context remains clinically accurate</li></ul><h3>Streamlit UI Demo</h3><p>The Streamlit app displays:</p><ul><li>Input box for medical question</li><li>“Searching…” animation</li><li>Full answer</li><li>Retrieved source chunks</li><li>Specialty &amp; sample name for each chunk</li></ul><p>This makes the RAG system look like a polished mini medical assistant.</p><h3>Evaluation on 30 Medical Queries</h3><p>The system was evaluated on <strong>30 real medical questions</strong> across multiple specialties. Some examples:</p><ul><li><em>What symptoms are seen in pneumonia?</em></li><li><em>How is urinary tract infection documented?</em></li><li><em>What findings appear in colonoscopy reports?</em></li><li><em>What symptoms indicate COPD exacerbation?</em></li><li><em>Describe postoperative findings in knee arthroscopy.</em></li></ul><h3>Evaluation Metrics:</h3><p>MetricScoreContext relevance<strong>27/30</strong>Answer groundedness<strong>26/30</strong>Specialty + sample metadata accuracy<strong>28/30</strong>Hallucination rate<strong>Very low</strong>Safety<strong>Passed</strong></p><p>The RAG system reliably retrieved correct clinical notes and produced grounded outputs.</p><h3>Deployment on Streamlit Cloud</h3><p>The final deliverable was deployed on <strong>Streamlit Cloud</strong>, making it accessible publicly.</p><p>Deployment Steps:</p><ol><li>Push all code + index files to GitHub</li><li>Set app/ui_streamlit.py as entrypoint</li><li>Add GEMINI_API_KEY in Streamlit Secrets</li><li>Deploy</li></ol><p>Now the app runs entirely online with no local dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=463ed9356c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I fine-tuned Google’s T5 model to automatically summarize news articles]]></title>
            <link>https://medium.com/@zainab29323/how-i-fine-tuned-googles-t5-model-to-automatically-summarize-news-articles-9f4af8d1e1de?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4af8d1e1de</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 13:22:15 GMT</pubDate>
            <atom:updated>2025-11-02T13:22:15.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISf_Keiu6SWqxXnI.jpg" /><figcaption>Fine Tuning in ML</figcaption></figure><h3>I Built an AI That Reads News Articles So You Don’t Have To</h3><blockquote>How I fine-tuned Google’s T5 model to automatically summarize news articles in under 20 minutes</blockquote><p><em>Ever wished you could skim through dozens of news articles in seconds? I built an AI that does exactly that.</em></p><h3>The Problem: Information Overload</h3><p>We’re drowning in content. The average news article is 600–800 words and takes 3–4 minutes to read. Multiply that by the dozens of articles we encounter daily, and we’re looking at hours of reading just to stay informed.</p><p>What if AI could read these articles for us and extract the key points in seconds?</p><p>That’s exactly what I set out to build.</p><h3>What I Built</h3><p>I fine-tuned Google’s T5 (Text-to-Text Transfer Transformer) model to automatically generate concise summaries of news articles. Here’s what it does:</p><p>Input: A 600-word news article about Novak Djokovic’s tennis match</p><p>Output: “Novak Djokovic apologized to a ball boy caught in a tirade at his support team. The world No 1 lost his cool at the end of the second set to Andy Murray. Djokovic has since expressed his regret at the incident in a video posted on Facebook.”</p><p>That’s a 13.4x compression while keeping all the important facts!</p><h3>Why T5?</h3><p>T5 stands for “Text-to-Text Transfer Transformer” — and that “text-to-text” part is key. Unlike other models that need special architectures for different tasks, T5 treats everything as a text transformation problem:</p><ul><li>Translation: “translate English to French: Hello” → “Bonjour”</li><li>Summarization: “summarize: [article]” → “summary”</li><li>Question answering: “question: What is AI?” → “answer”</li></ul><p>This flexibility makes T5 incredibly powerful for summarization tasks.</p><p>Model specs I used:</p><ul><li>T5-small: 60 million parameters</li><li>Training data: 10,000 CNN/DailyMail articles</li><li>Training time: Just 18 minutes on a Tesla T4 GPU</li><li>Model size: 242 MB (deployable anywhere)</li></ul><h3>The Dataset: CNN/DailyMail</h3><p>I used the famous CNN/DailyMail dataset — a collection of 300,000+ news articles paired with human-written highlights. It’s the gold standard for summarization research.</p><p>Why this dataset?</p><ul><li>Real news articles from credible sources</li><li>Professional journalist-written summaries</li><li>Diverse topics: politics, sports, entertainment, world events</li><li>Well-structured and clean</li></ul><p>My subset:</p><ul><li>Training: 10,000 articles</li><li>Validation: 2,000 articles</li><li>Testing: 1,000 articles</li></ul><p>I used a subset for faster iteration, but the full dataset would boost performance significantly.</p><h3>The Technical Approach</h3><p>Here’s the step-by-step process:</p><h3>1. Preprocessing</h3><pre>Raw Article → Clean Text → Remove Noise → Tokenize</pre><p>I filtered out super short articles and cleaned up formatting issues.</p><h3>2. Tokenization</h3><p>T5 needs text converted to numbers. Each word/subword gets an ID:</p><pre>&quot;summarize: Djokovic won&quot; → [1045, 10, 389, 7, 25, 1829, 75]</pre><h3>3. Training</h3><p>The model learns to predict the next token in the summary, one word at a time:</p><pre>Input: &quot;summarize: [article about tennis match]&quot;<br>Target: &quot;Djokovic&quot; → &quot;apologised&quot; → &quot;to&quot; → &quot;a&quot; → &quot;ball&quot; → &quot;boy&quot;...</pre><p>Training parameters:</p><ul><li>Learning rate: 0.00005 (small adjustments)</li><li>Batch size: 8 (memory efficiency)</li><li>Epochs: 3 (passes through data)</li><li>Optimizer: AdamW (smart gradient updates)</li></ul><h3>4. Generation</h3><p>At inference, the model uses beam search to explore multiple possible summaries and pick the best one.</p><h3>The Results: How Well Does It Work?</h3><p>I evaluated the model using ROUGE scores — the industry standard for measuring summarization quality.</p><h3>ROUGE Metrics Explained</h3><p>Think of ROUGE as a “matching game”:</p><ul><li>ROUGE-1: How many individual words match? (0.24 = 24% match)</li><li>ROUGE-2: How many word pairs match? (0.11 = 11% match)</li><li>ROUGE-L: How long is the matching sequence? (0.20 = 20% match)</li></ul><p>My results:</p><pre>ROUGE-1: 0.2442 ✓ Fair<br>ROUGE-2: 0.1123 ✓ Acceptable  <br>ROUGE-L: 0.2008 ✓ Fair</pre><p>For context, state-of-the-art models score around 0.44 on ROUGE-1. Given that I used only 3.5% of available training data, these results are solid!</p><h3>What Does “0.24 ROUGE-1” Actually Mean?</h3><p>It means about 1 in 4 words in my generated summary match the human-written summary. That might sound low, but here’s the thing: there are many valid ways to summarize the same article.</p><p>The model might say “Djokovic apologized” while the human wrote “Djokovic expressed regret” — different words, same meaning. ROUGE doesn’t capture this semantic similarity.</p><h3>Real Examples:</h3><h3>Example 1: Sports News ⭐ (ROUGE-1: 0.57)</h3><p>Article: Long story about Djokovic’s tennis match incident</p><p>My Model:</p><p><em>“Novak Djokovic apologized to a ball boy caught in a tirade at his support team. The world No 1 lost his cool at the end of the second set to Andy Murray. Djokovic has since expressed his regret at the incident in a video posted on Facebook.”</em></p><p>Human Summary:</p><p><em>“Novak Djokovic beat Andy Murray 7–6 4–6 6–0 in Miami Open 2015 final. Djokovic lost his cool after losing the second set to the Brit in Florida. World No 1 Djokovic shouted at his support team next to a scared ball boy…”</em></p><p>Analysis: Excellent! Captured all key points — who, what, when, and the apology. Only missed the specific score.</p><h3>Example 2: Legal/Civil Rights (ROUGE-1: 0.19)</h3><p>Article: Story about a woman strip-searched at airport, receiving settlement</p><p>My Model:</p><p><em>“Shoshana Hebshi was strip-searched at a Detroit-area airport on the 10th anniversary of 9/11. She was forced from a plane, made to undress during a search and held for hours…”</em></p><p>Human Summary:</p><p><em>“The federal government will give Shoshana Hebshi $40,000 as compensation for being ethnically profiled. Hebshi has said she was discriminated against based on her dark complexion…”</em></p><p>Analysis: Factually accurate but missed the point. The human summary emphasizes ethnic profiling and civil rights — the <em>why</em> matters. My model focused on <em>what happened</em> but missed <em>why it matters</em>.</p><p>This reveals a limitation: the model struggles with context and implications.</p><h3>Example 3: Breaking News ✅ (ROUGE-1: 0.35)</h3><p>Article: ISIS releases 200+ Yazidis</p><p>My Model:</p><p><em>“ISIS releases more than 200 Yazidis, a minority group whose members were killed, captured and displaced. Most of those released were women and children; the rest were ill or elderly…”</em></p><p>Human Summary:</p><p><em>“Most of those released were women and children. Freed Yazidis sent to capital of Iraq’s Kurdish region.”</em></p><p>Analysis: ✅ Actually MORE detailed than the human summary! Provided good context about who the Yazidis are.</p><h3>What I Learned: Strengths &amp; Weaknesses</h3><h3>Where It Shines</h3><ol><li>Sports articles (ROUGE: 0.45–0.57) — Clear structure with scores, winners, key moments</li><li>Breaking news (ROUGE: 0.35–0.45) — Straightforward factual reporting</li><li>Grammar — Never produces gibberish, always readable</li><li>Entity recognition — Accurately captures names, places, numbers</li><li>Speed — Generates summaries in &lt;1 second</li></ol><h3>Where It Struggles</h3><ol><li>Multi-layered stories — Misses secondary details</li><li>Context &amp; nuance — Captures facts but sometimes misses “why it matters”</li><li>Cultural references — Doesn’t understand nicknames or colloquialisms</li><li>Opinion pieces — Better at facts than interpretation</li><li>Very long articles — 512 token limit truncates some content</li></ol><h3>Performance by Category</h3><pre>Category Performance:<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>Sports:        ████████████ 0.50 ⭐<br>Breaking News: █████████    0.40 ✅<br>Politics:      ███████      0.35 ✅<br>Features:      ███████      0.35 ✅<br>Legal/Complex: █████        0.25 ⚠️</pre><h3>The Compression Magic: 600 Words → 50 Words</h3><p>One of the coolest findings: my model achieves a 13.4x compression ratio on average.</p><p>That means:</p><ul><li>600-word article → 45-word summary</li><li>3-minute read → 10-second skim</li><li>20 articles → read in 3 minutes instead of an hour</li></ul><p>And it maintains about 41% word overlap with professional journalist summaries!</p><h3>Could This Be Better? Absolutely.</h3><p>Here’s the honest truth: I used only 3.5% of available training data (10K out of 287K articles). Why?</p><ol><li>Time constraints — Wanted fast iteration</li><li>Resource efficiency — Proved the concept works</li><li>Proof of concept — Demonstrated viability</li></ol><p>With full training, this model could compete with commercial solutions!</p><h3>How I Built This: Tech Stack</h3><p>Tools &amp; Libraries:</p><ul><li>Framework: PyTorch + Hugging Face Transformers</li><li>Platform: Kaggle Notebooks (free GPU!)</li><li>Model: T5-small from Hugging Face</li><li>Dataset: CNN/DailyMail</li><li>Evaluation: ROUGE metrics</li><li>Deployment: Gradio (interactive demo)</li></ul><p>Why Kaggle?</p><ul><li>Free Tesla T4 GPU access</li><li>Pre-installed ML libraries</li><li>Easy dataset integration</li><li>Shareable notebooks</li></ul><h3>Try It Yourself: Gradio Demo</h3><p>I deployed an interactive demo using Gradio. Here’s what users can do:</p><ol><li>Paste any news article (300–1000 words work best)</li><li>Adjust parameters:</li></ol><ul><li>Summary length (50–200 words)</li><li>Beam search width (quality vs speed)</li><li>Length penalty (shorter vs longer)</li></ul><p>Click “Summarize” and get results in &lt;2 seconds!</p><p>Demo features:</p><ul><li>Pre-loaded example articles</li><li>Real-time statistics (compression ratio, word counts)</li><li>Adjustable generation parameters</li><li>Shareable public URL</li></ul><p>The interface makes it easy for non-technical users to experiment with the model.</p><h3>Key Takeaways</h3><h3>1. T5 is Powerful Yet Accessible</h3><p>With just 60M parameters and 18 minutes of training, I built a functional summarizer. Larger models exist, but T5-small hits the sweet spot of performance and efficiency.</p><h3>2. Data Matters More Than You Think</h3><p>My limited training data was the biggest bottleneck. 10K samples got me to 0.24 ROUGE; the full 287K would likely reach 0.40+. That’s a 67% improvement just from more data!</p><h3>3. Different Content Needs Different Approaches</h3><p>Sports articles: ⭐ Excellent Complex legal stories: ⚠️ Needs work</p><p>This suggests domain-specific fine-tuning could boost performance significantly.</p><h3>4. Context is Hard</h3><p>The model captures <em>what</em> happened well but sometimes misses <em>why</em> it matters. This is a fundamental challenge in NLP.</p><h3>5. Speed is a Feature</h3><p>Sub-second inference means this could process thousands of articles per hour — perfect for news aggregation services.</p><h3>Real-World Applications</h3><p>Where could this be used today?</p><h3>1. News Aggregation Apps</h3><p>Automatically summarize articles from multiple sources for quick browsing.</p><h3>2. Email Newsletters</h3><p>Generate article previews for daily news digests.</p><h3>3. Research Paper Screening</h3><p>Quickly scan abstracts and papers to find relevant research.</p><h3>4. Content Management Systems</h3><p>Auto-generate meta descriptions for SEO.</p><h3>5. Accessibility Tools</h3><p>Help readers with time constraints or reading difficulties.</p><h3>6. Social Media Monitoring</h3><p>Summarize news mentions for brand monitoring.</p><h3>Research Directions</h3><ol><li>Reinforcement learning — Optimize for ROUGE directly</li><li>Contrastive learning — Better semantic understanding</li><li>Few-shot learning — Adapt to new domains quickly</li></ol><h3>The Code</h3><p>Want to build this yourself? Here’s the simplified training loop:</p><p>python</p><pre>from transformers import T5Tokenizer, T5ForConditionalGeneration</pre><pre># Load model<br>tokenizer = T5Tokenizer.from_pretrained(&#39;t5-small&#39;)<br>model = T5ForConditionalGeneration.from_pretrained(&#39;t5-small&#39;)</pre><pre># Prepare data<br>def preprocess(article, summary):<br>    input_text = &quot;summarize: &quot; + article<br>    inputs = tokenizer(input_text, max_length=512, truncation=True)<br>    labels = tokenizer(summary, max_length=128, truncation=True)<br>    return inputs, labels</pre><pre># Train (simplified)<br>trainer = Seq2SeqTrainer(<br>    model=model,<br>    train_dataset=train_data,<br>    eval_dataset=val_data,<br>    compute_metrics=compute_rouge<br>)<br>trainer.train()</pre><pre># Generate summary<br>def summarize(article):<br>    inputs = tokenizer(&quot;summarize: &quot; + article, return_tensors=&#39;pt&#39;)<br>    outputs = model.generate(inputs[&#39;input_ids&#39;], max_length=128)<br>    return tokenizer.decode(outputs[0], skip_special_tokens=True)</pre><p>Full code available on my GitHub <a href="https://github.com/Zainab322/t5-news-summarizer_fine_tuned">https://github.com/Zainab322/t5-news-summarizer_fine_tuned</a></p><h3>Lessons for ML Practitioners</h3><h3>1. Start Small, Iterate Fast</h3><p>I could have spent weeks training on the full dataset. Instead, I used 10K samples, got quick results, and identified what works/doesn’t work.</p><h3>2. Domain Matters</h3><p>Sports: 0.57 ROUGE. Legal: 0.19 ROUGE. That’s a 3x difference! One-size-fits-all rarely works in ML.</p><h3>3. Metrics Don’t Tell the Whole Story</h3><p>ROUGE-1 of 0.24 sounds mediocre, but many summaries were actually quite good. Always look at qualitative examples.</p><h3>4. User Experience &gt; Perfect Accuracy</h3><p>A 0.24 ROUGE model that’s fast and deployable beats a 0.44 ROUGE model that’s too slow or expensive to use.</p><h3>5. Pretrained Models Are Magic</h3><p>T5 was already trained on 750GB of text. Fine-tuning for 18 minutes made it a news summarizer. We’re standing on the shoulders of giants.</p><h3>Final Thoughts</h3><p>Building this summarizer taught me that:</p><ol><li>Modern NLP is accessible — You don’t need a research lab or millions in compute</li><li>Good enough is often good enough — My 0.24 ROUGE model is usable today</li><li>There’s still room for improvement — Even simple changes (more data, bigger model) would significantly boost performance</li><li>Context is king — The hardest part isn’t generating text; it’s understanding what’s important</li></ol><p>If you’re interested in NLP, I highly recommend trying a summarization project. It’s challenging, practical, and incredibly satisfying when your model produces its first coherent summary.</p><p><em>Thanks for reading! If you enjoyed this article, consider giving it a clap 👏 and following for more AI/ML content.</em></p><p>#MachineLearning #NLP #AI #TextSummarization #T5 #DeepLearning #Python #DataScience</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4af8d1e1de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Emotion Aware Empathetic Chatbot from Scratch with Transformers]]></title>
            <link>https://medium.com/@zainab29323/building-an-emotion-aware-empathetic-chatbot-from-scratch-with-transformers-77e58f128aa4?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e58f128aa4</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 16:16:53 GMT</pubDate>
            <atom:updated>2025-10-17T16:16:53.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*SnHeUynLEpeRV3f8sIiHuA.jpeg" /></figure><p>Have you ever wished a chatbot could truly <em>understand</em> how you feel, not just answer questions, but respond with empathy?<br>In this project, I set out to build exactly that: an <strong>emotion-aware empathetic dialogue system</strong>, trained completely from scratch using <strong>PyTorch</strong> and <strong>Transformer architecture</strong>, without any pre-trained models.</p><h3>The Motivation</h3><p>Most chatbots today can generate fluent sentences, but they often sound mechanical, they don’t recognize or respond to human emotions. Empathy is the missing ingredient that makes interactions feel natural.</p><p>This project focuses on creating a <strong>Transformer-based chatbot</strong> that doesn’t just reply, but does so <strong>with emotional awareness</strong>, adapting its tone and message to the user’s expressed feelings.</p><h3>The Dataset</h3><p>I used an <strong>emotion-labeled dialogue dataset</strong> consisting of around <strong>69,000 examples</strong> of conversations between customers and agents.<br> Each data point contains:</p><p><strong>Emotion</strong> (like <em>happy, angry, afraid, sad, sentimental</em>),</p><p><strong>Situation</strong> (a short background context),</p><p><strong>Customer utterance</strong>, and</p><p><strong>Agent reply</strong> (the empathetic response).</p><p>Here’s what a typical entry looks like:</p><blockquote><strong><em>Emotion:</em></strong><em> Sentimental<br> </em><strong><em>Situation:</em></strong><em> I remember going to the fireworks with my best friend…<br> </em><strong><em>Customer:</em></strong><em> This was a best friend. I miss her.<br> </em><strong><em>Agent:</em></strong><em> Where has she gone?</em></blockquote><p>This kind of dataset allows the model to learn how <em>emotion</em> influences <em>language choice</em> in empathetic communication.</p><h3>Preprocessing &amp; Data Preparation</h3><p>Before training, I performed extensive text cleaning and normalization:</p><ul><li>Lowercased all text</li><li>Removed redundant whitespace and punctuation</li><li>Tokenized the text using <strong>spaCy</strong></li><li>Built a vocabulary <strong>only from the training data</strong> (to prevent data leakage)</li><li>Added special tokens like &lt;bos&gt;, &lt;eos&gt;, &lt;pad&gt;, and &lt;unk&gt;</li></ul><p>The data was split into:</p><ul><li><strong>80% for training</strong>,</li><li><strong>10% for validation</strong>, and</li><li><strong>10% for testing</strong>.</li></ul><p>shapes the agent’s next sentence.</p><h3>Model Architecture — Transformer from Scratch</h3><p>The heart of this project is a <strong>Transformer encoder–decoder</strong>, implemented entirely from scratch in PyTorch.<br> The model includes:</p><ul><li>Multi-Head Self-Attention (Encoder &amp; Decoder)</li><li>Cross-Attention (Decoder → Encoder)</li><li>Positional Encodings</li><li>Feed-Forward Networks</li><li>Residual Connections &amp; Layer Normalization</li></ul><p>Key hyperparameters:</p><ul><li><strong>Embedding dimension:</strong> 512</li><li><strong>Heads:</strong> 2</li><li><strong>Encoder/Decoder layers:</strong> 4 each</li><li><strong>Dropout:</strong> 0.1</li></ul><p>This architecture allows the model to learn complex dependencies between emotional context, situation, and appropriate empathetic responses.</p><h3>Training</h3><p>The model was trained using:</p><ul><li><strong>Adam optimizer</strong> with β=(0.9, 0.98)</li><li><strong>Learning rate:</strong> 2e-4</li><li><strong>Batch size:</strong> 32</li><li><strong>Teacher forcing</strong> during training</li></ul><p>The best model checkpoint was saved based on <strong>validation BLEU score</strong>.<br> Training was tracked with <strong>Perplexity, BLEU, ROUGE-L, and chrF</strong> to evaluate both fluency and semantic similarity.</p><h3>Evaluation &amp; Results</h3><p>After several epochs, the model achieved the following on the test set:</p><p>MetricScore:</p><p><strong>BLEU</strong>14.26</p><p><strong>ROUGE-L</strong>23.65</p><p><strong>chrF</strong>19.08</p><p><strong>Perplexity</strong>41.39</p><p>While these numbers are modest, they are quite strong for a <strong>Transformer trained from scratch</strong> on conversational data.<br> The model successfully learned patterns of empathy — its responses often aligned in tone and relevance with the emotion of the user’s message.</p><h3>Human Evaluation</h3><p>To complement automatic metrics, I also collected <strong>human judgments</strong> for 30 samples, rating them on:</p><ul><li><strong>Fluency</strong> (How natural is the sentence?)</li><li><strong>Relevance</strong> (Is the response on-topic?)</li><li><strong>Empathy/Adequacy</strong> (Does it emotionally fit?)</li></ul><p>Average human scores were encouraging:</p><ul><li>Fluency: <strong>4.2 / 5</strong></li><li>Relevance: <strong>3.9 / 5</strong></li><li>Empathy: <strong>4.1 / 5</strong></li></ul><h3>Chatbot Interface (Gradio)</h3><p>To make the model interactive, I built a <strong>Gradio chatbot UI</strong>.<br> Users can:</p><ul><li>Enter any message and select an emotion (optional)</li><li>Choose decoding strategy (Greedy or Beam Search)</li><li>View conversation history and attention-based replies</li></ul><p>It’s hosted via <strong>Gradio Share</strong>, so anyone can try it live without installation.</p><h3>Deployment</h3><p>The chatbot is deployable either through:</p><ul><li><strong>Streamlit Cloud</strong>, or</li><li><strong>Hugging Face Spaces</strong> using Gradio’s integration.</li></ul><p>Users can run the notebook or script locally, or launch the app instantly</p><p>This creates a public link for anyone to chat with the model.</p><h3>Key Takeaways</h3><ol><li><strong>Empathy can be modeled.</strong> With the right data and conditioning, models learn emotional tone and context.</li><li><strong>Pretraining isn’t always required.</strong> Even a scratch-built Transformer learns surprising levels of coherence.</li><li><strong>Evaluation must go beyond BLEU.</strong> Human feedback is crucial to assess emotional quality.</li><li><strong>Explainability matters.</strong> Attention visualization helps interpret how the model relates emotion → response.</li></ol><p>This project was a deep dive into the mechanics of empathy in dialogue systems.<br>By combining a clean dataset, a custom Transformer, and careful training, we created a model that can understand and respond to human emotions with grace and relevance.</p><p>Empathy might be a human trait, but as this project shows, <strong>machines can learn to approximate it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e58f128aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Documentation Generator for Code Repositories]]></title>
            <link>https://medium.com/@zainab29323/building-an-ai-powered-documentation-generator-for-code-repositories-4faa24ea7013?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faa24ea7013</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 08:35:42 GMT</pubDate>
            <atom:updated>2025-09-26T08:35:42.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*cD3cb84rDlGWS0arfc0yNA.jpeg" /></figure><h3>Project Overview</h3><p>As part of my Generative AI course (AI-4009), I recently worked on an exciting project: <strong>building a system that automatically generates meaningful documentation for code repositories</strong>. The idea was to combine <strong>classical NLP techniques</strong> with <strong>modern generative AI approaches</strong> to create an end-to-end documentation generation pipeline.</p><p>The project challenged us to not only understand the theory but also implement every major component from scratch, ranging from tokenization to embeddings to language modeling, while ensuring everything fit together into a cohesive system.</p><p>Our final pipeline had three major pillars:</p><ol><li><strong>BPE Tokenizer</strong> — for efficient representation of code and text</li><li><strong>Word2Vec Embeddings</strong> — to capture semantic relationships in code and documentation</li><li><strong>Recurrent Language Model (LSTM)</strong> — to generate human-like function docstrings and summaries</li></ol><h3>Dataset</h3><p>We used the <a href="https://www.kaggle.com/datasets/faiqahmad01/python-func4ons-with-docstrings">Python Functions with Docstrings dataset</a>, a specialized subset of the CodeSearchNet dataset.</p><ul><li><strong>Size:</strong> 456k Python functions</li><li><strong>Key fields:</strong></li><li>code – raw function code (without docstring)</li><li>docstring – human-written documentation (target)</li><li>summary – AI-generated short description (used for evaluation)</li><li>code_tokens, docstring_tokens – professional tokenizations (used for benchmarking)</li></ul><p>This dataset provided the perfect foundation for building and evaluating a documentation generation system.</p><h3>Step-by-Step Implementation</h3><h3>1. Dataset Analysis</h3><p>We began by analyzing dataset statistics: function lengths, vocabulary sizes, and distribution across training/validation/test splits. This gave insights into the complexity and variety of documentation styles.</p><h3>2. BPE Tokenizer Implementation</h3><p>From scratch, we implemented <strong>Byte Pair Encoding (BPE)</strong> for both Python code and natural language documentation.</p><ul><li>Separate vocabularies were trained for code, documentation, and combined corpora.</li><li>The tokenizer included:</li><li>Encoding/decoding functions</li><li>Out-of-vocabulary (OOV) handling</li><li>Compression and boundary accuracy evaluation</li></ul><p><strong>Evaluation:</strong><br> We compared our BPE tokenizer with professional tokenizations using:</p><ul><li>Jaccard similarity (vocabulary overlap)</li><li>Compression ratio</li><li>Boundary accuracy</li><li>Consistency scoring</li><li>OOV rate analysis</li></ul><h3>3. Word2Vec Embeddings</h3><p>We implemented a <strong>Skip-gram Word2Vec</strong> model to capture semantic relationships.</p><ul><li>Trained embeddings separately for:</li></ul><ol><li>Code tokens</li><li>Documentation tokens</li><li>Joint code-doc pairs</li></ol><p><strong>Evaluation:</strong></p><ul><li>Semantic similarity analysis (e.g., cosine similarity between function names and descriptions)</li><li>Code completion accuracy</li><li>Visualization of embeddings with t-SNE/ PCA</li></ul><h3>4. Language Model (LSTM)</h3><p>For the generative core, we chose an <strong>LSTM-based sequence model</strong>.</p><ul><li>Trained the model to generate docstrings conditioned on function code.</li><li>Implemented regularization (dropout), gradient clipping, and hyperparameter tuning.</li></ul><p><strong>Evaluation Metrics:</strong></p><p><strong>Perplexity</strong> — measuring fluency of the model</p><p><strong>BLEU scores</strong> — comparing generated summaries with the dataset’s ground-truth summary field</p><ul><li><strong>Training convergence curves</strong> — to monitor learning progress</li></ul><h3>5. System Integration</h3><p>Finally, we combined all components into a unified <strong>documentation generator</strong>:</p><ol><li>Code is first tokenized with the custom BPE tokenizer</li><li>Word2Vec embeddings enrich semantic understanding</li><li>The LSTM model generates natural-sounding docstrings and summaries</li></ol><p>We also wrapped the system into a <strong>Streamlit interface</strong> so that users can paste Python code and instantly get generated documentation.</p><h3>Key Deliverables</h3><p><strong>BPE Tokenizer</strong> with evaluation reports</p><p><strong>Word2Vec Embeddings</strong> with semantic similarity benchmarks</p><p><strong>LSTM Language Model</strong> with training/performance analysis</p><p><strong>Integrated Documentation System</strong> with a user-friendly interface</p><h3>Learnings &amp; Reflections</h3><p>This project was a perfect blend of <strong>classical NLP</strong> (tokenization, embeddings) and <strong>modern AI</strong> (generative language models).</p><p>Some key takeaways:</p><ul><li>Tokenization quality directly impacts downstream model performance</li><li>Word embeddings provide deep insights into the semantic structure of code</li><li>Evaluating generative models requires balancing quantitative metrics (BLEU, perplexity) with qualitative analysis (human-like fluency)</li></ul><p>Overall, this was more than just an academic exercise — it felt like building a <strong>mini research project</strong> that mirrors real-world challenges in AI-powered code intelligence.</p><h3>Closing Thoughts</h3><p>Working on this project was both challenging and rewarding. From debugging BPE merges to optimizing LSTM training runs, every step pushed us to think critically about design choices.</p><p>Generative AI for code is a fascinating domain, and this project reinforced just how powerful the combination of <strong>NLP + code analysis + generative modeling</strong> can be.</p><p>We’re excited to take these learnings into future projects and research.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faa24ea7013" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Voice Cloning API with Flask, Coqui TTS, and Cloudflared]]></title>
            <link>https://medium.com/@zainab29323/building-a-voice-cloning-api-with-flask-coqui-tts-and-cloudflared-6e0733e411e8?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0733e411e8</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 16:39:58 GMT</pubDate>
            <atom:updated>2025-09-08T16:39:58.338Z</atom:updated>
            <content:encoded><![CDATA[<p>Voice technology is rapidly becoming a game-changer in AI applications. From AI assistants to personalized podcasts, the ability to <strong>clone a human voice</strong> is both fascinating and practical. Recently, I built my own <strong>Voice Cloning Web API</strong> using <strong>Flask</strong>, <strong>Coqui TTS</strong>, and <strong>Cloudflared</strong> for public access. In this blog, I’ll take you step-by-step through how I set it up, integrated speech-to-text, and made it testable via Postman.</p><h3>Tech Stack</h3><p>Here’s what I used for this project:</p><p><strong>Flask</strong> → Lightweight Python web framework for the API</p><p><strong>Coqui TTS</strong> → Open-source text-to-speech library with voice cloning support</p><p><strong>SpeechRecognition (Google API)</strong> → To extract text from user-provided audio</p><p><strong>Cloudflared</strong> → To expose my local Flask server to the internet securely</p><p><strong>Postman</strong> → To test the API endpoints</p><h3>How the API Works</h3><p>The workflow is simple but powerful:</p><p><strong>User Uploads Two Audio Files</strong></p><p>reference_audio: A short audio sample of the target voice to clone.</p><p>clone_audio: A recording of someone speaking text to be cloned.</p><p><strong>Speech-to-Text Conversion</strong></p><p>The clone_audio file is processed using <strong>Google Speech Recognition</strong> to extract the spoken text.</p><p><strong>Voice Cloning with Coqui TTS</strong></p><p>The recognized text is passed into <strong>Coqui TTS</strong> along with the reference_audio.</p><p>Coqui generates a new audio file where the reference voice speaks the extracted text.</p><p><strong>API Returns a URL</strong></p><p>The cloned audio is saved in static/audio/ and returned as a public link.</p><h3>Project Structure</h3><pre>voice-clone-api/<br>│── app.py<br>│── uploads/            # Stores uploaded audio<br>│── static/<br>│   └── audio/          # Stores generated cloned audio<br>│── templates/<br>│   └── index.html      # (Optional UI)</pre><h3>Core Flask Code</h3><p>Here’s the heart of the project (simplified):</p><pre>from flask import Flask, request, jsonify, send_from_directory, url_for<br>from flask_cors import CORS<br>import os<br>from werkzeug.utils import secure_filename<br>from TTS.api import TTS<br>import speech_recognition as sr</pre><pre>app = Flask(__name__)<br>CORS(app)</pre><pre>UPLOAD_FOLDER = &quot;uploads&quot;<br>OUTPUT_FOLDER = &quot;static/audio&quot;<br>os.makedirs(UPLOAD_FOLDER, exist_ok=True)<br>os.makedirs(OUTPUT_FOLDER, exist_ok=True)</pre><pre>tts = TTS(&quot;tts_models/en/ljspeech/tacotron2-DDC&quot;)</pre><pre>def audio_to_text(audio_path):<br>    recognizer = sr.Recognizer()<br>    with sr.AudioFile(audio_path) as source:<br>        audio = recognizer.record(source)<br>    try:<br>        return recognizer.recognize_google(audio)<br>    except:<br>        return None</pre><pre>@app.route(&quot;/generate&quot;, methods=[&quot;POST&quot;])<br>def generate():<br>    ref_file = request.files.get(&quot;reference_audio&quot;)<br>    clone_file = request.files.get(&quot;clone_audio&quot;)</pre><pre>    if not ref_file or not clone_file:<br>        return jsonify({&quot;error&quot;: &quot;Both files are required&quot;}), 400</pre><pre>    ref_path = os.path.join(UPLOAD_FOLDER, secure_filename(ref_file.filename))<br>    clone_path = os.path.join(UPLOAD_FOLDER, secure_filename(clone_file.filename))<br>    ref_file.save(ref_path)<br>    clone_file.save(clone_path)</pre><pre>    text_to_clone = audio_to_text(clone_path)<br>    if not text_to_clone:<br>        return jsonify({&quot;error&quot;: &quot;Speech not recognized&quot;}), 400</pre><pre>    output_filename = &quot;cloned_output.wav&quot;<br>    output_path = os.path.join(OUTPUT_FOLDER, output_filename)</pre><pre>    tts.tts_to_file(text=text_to_clone, speaker_wav=ref_path, file_path=output_path)</pre><pre>    return jsonify({<br>        &quot;recognized_text&quot;: text_to_clone,<br>        &quot;audio_url&quot;: url_for(&quot;serve_audio&quot;, filename=output_filename, _external=True)<br>    })</pre><pre>@app.route(&quot;/static/audio/&lt;filename&gt;&quot;)<br>def serve_audio(filename):<br>    return send_from_directory(OUTPUT_FOLDER, filename)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run(port=5000, debug=True)</pre><h3>Exposing API to the Internet with Cloudflared</h3><p>Instead of ngrok, I chose <strong>Cloudflared</strong> because it’s lightweight, secure, and doesn’t require signup.</p><p>Install it:</p><p>winget install Cloudflare.cloudflared</p><p>brew install cloudflared # macOS</p><p>Run your Flask server locally:</p><p>python app.py</p><p>Expose it with Cloudflared:</p><p>cloudflared tunnel --url <a href="http://localhost:5000/">http://localhost:5000</a></p><p>This gives you a <strong>public HTTPS URL</strong>, e.g.:</p><pre>https://bright-dog-5f7t.trycloudflare.com</pre><p>Now your Flask API is accessible globally</p><p>Testing with Postman</p><p>Open <strong>Postman</strong> and create a new <strong>POST request</strong>:</p><p><a href="https://bright-dog-5f7t.trycloudflare.com/generate">https://bright-dog-5f7t.trycloudflare.com/generate</a></p><p>In the <strong>Body</strong> → select form-data:</p><p>Key: reference_audio → Type: File → Upload sample.wav</p><p>Key: clone_audio → Type: File → Upload text_to_speak.wav</p><p>Hit <strong>Send</strong> → You’ll receive:</p><p>{ &quot;recognized_text&quot;: &quot;Hello world this is my test&quot;, &quot;audio_url&quot;: &quot;https://bright-dog-5f7t.trycloudflare.com/static/audio/cloned_output.wav&quot; }</p><p>Open the audio_url link in your browser and 🎧 hear the cloned voice!</p><h3>Applications</h3><p>This project can be extended into:</p><p>Personalized AI assistants</p><p>Audiobooks in your own voice</p><p>News podcasts with cloned narrators</p><p>Integrated with n8n workflows for automation</p><h3>Final Thoughts</h3><p>By combining <strong>Flask</strong>, <strong>Coqui TTS</strong>, <strong>SpeechRecognition</strong>, and <strong>Cloudflared</strong>, I created a working <strong>Voice Cloning API</strong> that can be accessed anywhere in the world.</p><p>The coolest part? I didn’t need a paid tunneling service like ngrok — <strong>Cloudflared did the job for free and securely</strong>.</p><p>This project proves that with just a few tools, you can build <strong>production-ready AI voice services</strong> in a weekend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0733e411e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Text to My Own Voice: Building an AI-Powered Voice Cloning Web Application]]></title>
            <link>https://medium.com/@zainab29323/from-text-to-my-own-voice-building-an-ai-powered-voice-cloning-web-application-970493734e6c?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/970493734e6c</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 12:21:39 GMT</pubDate>
            <atom:updated>2025-08-31T12:21:39.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vT0TYNAfjJOiFeisGMultw.jpeg" /></figure><p>Having previously built a text-to-speech web application using Python and Flask, I was inspired to take it one step further. My goal this time was to create an AI-powered <strong>voice cloning application</strong> that not only converts text into speech but can also <strong>clone a reference voice</strong> from an audio file in real-time. This project was both challenging and exciting, as it combined machine learning, audio processing, and web development into a single, interactive app.</p><h3>Why I Built This</h3><p>In my previous project, I explored converting text to speech with adjustable parameters like rate, volume, and voice selection. While it worked well, I wanted a more advanced system where users could <strong>upload a voice sample</strong> and have the app replicate it. Essentially, I wanted to let users hear their text spoken in someone else’s voice — or even their own cloned voice.</p><p>The objective was clear:</p><ol><li>Convert input text into realistic speech (TTS).</li><li>Clone a reference voice from an audio file.</li><li>Allow users to download generated audio.</li><li>Provide dynamic voice options like male/female selection and adjustable speech parameters.</li><li>Enable drag-and-drop file upload for convenience.</li></ol><h3>Tools and Technologies I Used</h3><p>To build this, I combined several <strong>powerful tools</strong>:</p><ul><li><strong>Backend</strong>: Python 3.10, Flask, Flask-CORS</li><li><strong>Machine Learning &amp; Audio Processing</strong>: PyTorch, torchaudio, Coqui TTS, librosa, soundfile, SpeechRecognition</li><li><strong>Frontend</strong>: HTML5, CSS3, JavaScript</li><li><strong>Environment</strong>: Virtualenv on Windows 10/11</li><li><strong>Others</strong>: Cython (for TTS build), numpy, scipy</li></ul><p>I also organized the project into a clean folder structure to separate backend, frontend, and audio files.</p><h3>How I Built the Backend</h3><p>Using Flask, I created multiple routes:</p><ul><li>/ serves the main webpage.</li><li>/tts accepts text input and generates speech using Coqui TTS.</li><li>/voice-clone accepts a reference audio file and clones the voice while converting the input text into speech.</li><li>/download/&lt;filename&gt; allows users to download the generated audio files.</li></ul><p>For TTS, I used the <strong>Coqui TTS library</strong>, initializing the model with tts_models/en/ljspeech/tacotron2-DDC. I also ensured the generated audio was saved in a dedicated folder so that users could play it immediately in the browser or download it for later use.</p><p>Here’s a simplified snippet of how I handled TTS generation:</p><pre>from TTS.api import TTS<br># Initialize model<br>tts_model = TTS(model_name=&quot;tts_models/en/ljspeech/tacotron2-DDC&quot;, progress_bar=False, gpu=False)<br># Generate speech from text<br>tts_model.tts_to_file(text=&quot;Hello world&quot;, file_path=&quot;static/audio/tts_output.wav&quot;)</pre><p>For <strong>voice cloning</strong>, I allowed users to upload a reference audio file and combined it with the text input to produce speech in that voice.</p><pre>tts_model.tts_to_file(text=&quot;Hello world&quot;, speaker_wav=&quot;static/audio/ref_audio.wav&quot;, file_path=&quot;static/audio/cloned_output.wav&quot;)</pre><h3>Frontend and User Experience</h3><p>On the frontend, I designed a <strong>simple and interactive interface</strong>:</p><ul><li>Text input fields for both TTS and voice cloning.</li><li>Drag-and-drop support for uploading reference audio files.</li><li>Buttons for generating speech.</li><li>A playable audio element with download functionality.</li><li>Voice selection and sliders for controlling rate, pitch, and volume.</li></ul><p>Using JavaScript, I made AJAX requests to the Flask backend for <strong>real-time audio generation</strong> without reloading the page.</p><h3>My Favorite Feature: Cloning an Entire Book</h3><p>For demonstration, I took the book <em>Life 3.0</em> and converted it into speech. Uploading the text of the book, I generated audio for each chapter while controlling voice parameters. Listening to the book in a synthesized voice felt surreal and showed the true potential of AI-powered voice cloning.</p><h3>Challenges I Faced</h3><ol><li><strong>Dependency conflicts</strong>: Installing compatible versions of TTS, numpy, and librosa was crucial.</li><li><strong>Audio playback</strong>: Some browsers restrict autoplay; I had to ensure users could play and download audio seamlessly.</li><li><strong>Large files</strong>: Cloning an entire book required careful handling to prevent memory issues.</li></ol><h3>What I Learned</h3><p>This project reinforced my understanding of:</p><ul><li>Integrating machine learning models with web frameworks.</li><li>Real-time audio generation and playback.</li><li>Handling file uploads securely in Flask.</li><li>Creating interactive, user-friendly web applications.</li></ul><h3>Optional Enhancements</h3><p>Looking forward, I plan to implement:</p><ul><li>Multiple voice selections.</li><li>Deployment on cloud platforms like <strong>Vercel or Heroku</strong> for global access.</li></ul><h3>Conclusion</h3><p>Building this AI-powered voice cloning application was an incredible experience. From converting small text snippets to cloning entire voices and books, I explored both the <strong>technical depth</strong> of TTS and the <strong>user experience</strong> of interactive web apps.</p><p>By combining Python, Flask, Coqui TTS, and modern web development techniques, I was able to create a versatile and practical voice cloning solution. I hope this inspires others to explore AI and voice synthesis in their projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970493734e6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Text into Voice: How I Built an Intelligent Text-to-Speech Web App Using Python and…]]></title>
            <link>https://medium.com/@zainab29323/transforming-text-into-voice-how-i-built-an-intelligent-text-to-speech-web-app-using-python-and-896597fc22be?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/896597fc22be</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 11:43:31 GMT</pubDate>
            <atom:updated>2025-08-31T11:43:31.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transforming Text into Voice: How I Built an Intelligent Text-to-Speech Web App Using Python and Flask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVNgPxxIZUbAjOhUrxhG3Q.jpeg" /></figure><p>Ever wondered how your favorite apps convert written text into natural-sounding speech? Inspired by the power of <strong>Natural Language Processing (NLP)</strong>, I decided to build my own <strong>Text-to-Speech (TTS) web application</strong>. In this blog, I’ll walk you through <strong>my journey</strong>, the challenges I faced, and how I made a fully interactive TTS tool that can convert text, PDFs, and even entire books into speech — all in your browser.</p><h3>Why I Built This</h3><p>I’ve always been fascinated by NLP and the idea that machines can “understand” and “speak” human language. I wanted to create a tool that:</p><ul><li>Converts written text into speech instantly</li><li>Supports multiple voices, rates, and volumes</li><li>Accepts .txt and .pdf files for easy text extraction</li><li>Lets users listen and download the generated audio</li></ul><p>Most importantly, I wanted a <strong>practical tool</strong> that I could use for reading long books. For example, I recently took <a href="https://www.cag.edu.tr/uploads/site/lecturer-files/max-tegmark-life-30-being-human-in-the-age-of-artificial-intelligence-alfred-a-knopf-2017-aTvn.pdf"><strong>the book <em>Life 3.0</em> by Max Tegmark</strong></a>, and converted the entire book into a single, readable audio file using my app. This experience showed me how powerful TTS can be for learning and accessibility.</p><h3>Tools and Techniques I Used</h3><p>Here’s what I chose and why:</p><ul><li><strong>Python 3</strong> — my backend language of choice for quick prototyping</li><li><strong>Flask</strong> — to serve my web interface and handle requests</li><li><strong>pyttsx3</strong> — for offline, reliable text-to-speech conversion</li><li><strong>PyPDF2</strong> — to extract text from PDFs</li><li><strong>HTML, CSS, JavaScript</strong> — for an interactive frontend</li><li><strong>Flask-CORS</strong> — to manage cross-origin requests</li></ul><p>Using <strong>pyttsx3</strong> allowed me to have control over <strong>voice selection, rate, and volume</strong>, which was essential for creating a flexible tool.</p><h3>How I Built the App</h3><h3>Step 1: Setting Up Flask</h3><p>We start by creating a simple Flask app (app.py) that serves our HTML page and handles two main routes:</p><ol><li><strong>/upload</strong> — for uploading text or PDF files</li><li><strong>/speak</strong> — for generating speech from text</li></ol><p>Here’s a brief snippet:</p><pre>from flask import Flask, request, jsonify, render_template, url_for<br>from flask_cors import CORS<br>import pyttsx3, PyPDF2, os<br><br>app = Flask(__name__)<br>CORS(app)<br># Folder for audio files<br>OUTPUT_DIR = os.path.join(&quot;static&quot;, &quot;audio&quot;)<br>os.makedirs(OUTPUT_DIR, exist_ok=True)<br>@app.route(&#39;/&#39;)<br>def home():<br>    return render_template(&quot;index.html&quot;)</pre><p>We also handle <strong>file uploads</strong>, supporting both .txt and .pdf files. PDFs are read using PyPDF2 and converted to plain text.</p><h3>Step 2: Converting Text to Speech</h3><p>We use <strong>pyttsx3</strong>, a Python library that converts text to audio. Unlike some TTS APIs, pyttsx3 works offline and lets you adjust <strong>voice, rate, and volume</strong>.</p><p>Here’s how we generate speech:</p><pre>engine = pyttsx3.init()<br>engine.setProperty(&#39;voice&#39;, voices[0].id)  <br>engine.setProperty(&#39;rate&#39;, rate)<br>engine.setProperty(&#39;volume&#39;, volume)<br>engine.save_to_file(text, filepath)<br>engine.runAndWait()</pre><p>We save the audio as a .wav file, which is then sent back to the frontend for playback and download.</p><h3>Step 3: Frontend with HTML &amp; JavaScript</h3><p>The frontend is simple, clean, and interactive:</p><ul><li>A <strong>text area</strong> for manual input</li><li><strong>Drag-and-drop file upload</strong></li><li>Dropdown for <strong>voice selection</strong></li><li>Sliders for <strong>rate</strong> and <strong>volume</strong></li><li><strong>Generate Speech</strong> button</li><li><strong>Audio player</strong> and <strong>download button</strong></li></ul><p>Here’s a small snippet of the JavaScript code handling speech generation:</p><pre>async function generateSpeech() {<br>    const text = document.getElementById(&quot;text&quot;).value.trim();<br>    const response = await fetch(&quot;/speak&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify({<br>            text,<br>            voice: document.getElementById(&quot;voice&quot;).value,<br>            rate: rate.value,<br>            volume: volume.value<br>        })<br>    });<br>const result = await response.json();<br>    document.getElementById(&quot;status&quot;).innerText = result.message;<br>    if (result.url) {<br>        const audioPlayer = document.getElementById(&quot;audioPlayer&quot;);<br>        audioPlayer.src = result.url;<br>        audioPlayer.style.display = &quot;block&quot;;<br>        audioPlayer.play();<br>    }<br>}</pre><h3>3. Handling Files: TXT, PDF, and Large Text</h3><p>I wanted my app to be practical, so I added <strong>drag-and-drop file support</strong>. Users can upload .txt or .pdf files, and the text content is automatically loaded into the text area for speech conversion. For PDFs, I used PyPDF2 to extract text from all pages.</p><p>For large texts, such as books, the process is the same: I load the text in chunks to avoid memory issues and generate the speech sequentially. For instance, when I uploaded <strong>the entire <em>Life 3.0</em> book</strong>, my app successfully converted all chapters into a single, downloadable audio file. This experience highlighted the real potential of TTS for learning and accessibility.</p><h3>Step 5: Customizing Voice and Audio</h3><p>We allow the user to select:</p><ul><li><strong>Voice</strong>: male, female, or default</li><li><strong>Rate</strong>: speed of speech (100–300 words per minute)</li><li><strong>Volume</strong>: audio loudness (0.0–1.0)</li></ul><p>This makes the app flexible for different use cases, from learning to accessibility tools.</p><h3>Step 6: Play and Download Audio</h3><p>After generating the speech, the app displays:</p><ul><li>An <strong>audio player</strong> to listen instantly</li><li>A <strong>download button</strong> to save the .wav file locally</li></ul><p>This makes it easy to use the generated speech in other projects or presentations.</p><h3>Challenges and Fixes</h3><p>While building this app, I faced some challenges:</p><ol><li><strong>pyttsx3 sometimes hangs on small texts</strong> — solved by using .wav format instead of .mp3.</li><li><strong>PDF extraction</strong> — some PDFs have images or scanned text; only text-based PDFs work reliably.</li><li><strong>Frontend responsiveness</strong> — ensured the status updates dynamically when loading files and generating speech.</li></ol><h3>Future Improvements</h3><ul><li>Show <strong>progress bar</strong> for large files</li><li>Use <strong>AI voices</strong> for more natural-sounding speech</li><li>Add <strong>multiple language support</strong></li><li>Deploy online for anyone to use</li></ul><h3>Conclusion</h3><p>This project was a great hands-on experience in <strong>NLP, web development, and Python automation</strong>. I learned how to combine backend processing with interactive frontend features to create a practical tool. Converting an entire book like <em>Life 3.0</em> into speech was especially rewarding — it showed me how accessible knowledge can become when text meets voice.</p><p>If you’re curious about <strong>text-to-speech technology</strong>, this project is a perfect start — you can extend it to AI voices, multiple languages, or even create a virtual assistant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896597fc22be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Code of Deepfake Audio & Software Defect Detection — An End-to-End Machine Learning…]]></title>
            <link>https://medium.com/@zainab29323/cracking-the-code-of-deepfake-audio-software-defect-detection-an-end-to-end-machine-learning-88a1aff15e95?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a1aff15e95</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Sun, 04 May 2025 11:36:44 GMT</pubDate>
            <atom:updated>2025-05-04T11:36:44.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cracking the Code of Deepfake Audio &amp; Software Defect Detection — An End-to-End Machine Learning Experience</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*0g8-9L5lNNniH60svSXl6g.jpeg" /></figure><p>With the rapid evolution of generative AI, detecting deepfakes has become a necessity.</p><blockquote>This project tackled two distinct but exciting challenges:<br> — Detecting deepfake audio in Urdu<br> — Predicting multiple software defects from structured data</blockquote><p>It also included the creation of a <strong>real-time interactive app</strong> using <strong>Streamlit</strong>, making the project hands-on and practical.</p><h3>Part 1: Urdu Deepfake Audio Detection (Binary Classification)</h3><p>We used the publicly available dataset:</p><pre>from datasets import load_dataset  <br>ds = load_dataset(&quot;CSALT/deepfake_detection_dataset_urdu&quot;)</pre><h3>Preprocessing</h3><p>To convert raw audio into model-friendly inputs, I extracted:</p><ul><li><strong>MFCCs (Mel-Frequency Cepstral Coefficients)</strong></li><li><strong>Spectrograms</strong></li></ul><p>I ensured fixed-length feature vectors by trimming or padding the audio sequences, which helped keep the input dimensions consistent across all models.</p><h3>Model Building</h3><p>I trained and tested four models:</p><p>ModelDescriptionSupport Vector MachineEffective for high-dimensional dataLogistic RegressionBaseline classifierSingle-Layer PerceptronTrained using batch gradient descentDeep Neural Network2 hidden layers with ReLU + dropout</p><h3>Training &amp; Evaluation</h3><p>All models were trained to classify audio as either <strong>Bonafide</strong> or <strong>Deepfake</strong>.</p><p><strong>Metrics used:</strong></p><ul><li>Accuracy</li><li>Precision, Recall, F1-Score</li><li>AUC-ROC (Area Under Curve — Receiver Operating Characteristic)</li></ul><h3>Part 2: Multi-Label Software Defect Prediction</h3><p>This was a classic <strong>multi-label classification</strong> task, where each instance could be associated with multiple defect labels.</p><h3>Preprocessing</h3><ul><li>Checked for <strong>missing values</strong></li><li><strong>Normalized</strong> features using StandardScaler</li><li>Analyzed <strong>label imbalance</strong> (some labels were very rare)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*TWh5WJkyktN9iDxIBgq4UQ.png" /><figcaption><strong>Bar chart showing label distribution</strong></figcaption></figure><h3>Models Trained</h3><p>ModelStrategy AppliedLogistic RegressionOne-vs-RestSVMMulti-label extension with OvRPerceptronOnline learning (updated per instance)Deep Neural Network2 hidden layers, sigmoid activation</p><h3>Evaluation Metrics</h3><p>Since this was a multi-label problem, I used:</p><ul><li><strong>Hamming Loss</strong></li><li><strong>Micro-F</strong>1 and<strong> Macro-F</strong>1</li><li><strong>Precision@k</strong> (top-k label prediction accuracy)</li></ul><p>The DNN outperformed others, but surprisingly, the <strong>online-trained Perceptron</strong> gave quite competitive results with very little computational overhead.</p><h3>Part 3: Interactive Streamlit App</h3><p>To wrap things up, I built a <strong>Streamlit app</strong> that performs <strong>real-time prediction</strong> based on user input.</p><h3>Deepfake Audio Detection Module</h3><ul><li>Upload any Urdu audio file</li><li>Choose your preferred model (SVM, Logistic Regression, or DNN)</li><li>Get prediction (Bonafide or Deepfake) with <strong>confidence score</strong></li></ul><pre>uploaded_file = st.file_uploader(&quot;Upload an audio file&quot;, type=[&quot;wav&quot;])<br>model_choice = st.selectbox(&quot;Choose a model&quot;, [&quot;SVM&quot;, &quot;Logistic Regression&quot;, &quot;DNN&quot;])</pre><h3>Software Defect Prediction Module</h3><ul><li>Input or upload a <strong>feature vector</strong></li><li>Predict multiple defect labels</li><li>View <strong>confidence scores</strong> for each label</li></ul><h3>UI Features</h3><ul><li>Clean and responsive layout</li><li>Dropdowns to select model</li><li>Clear prediction outputs with label-wise probabilities</li></ul><h3>Final Takeaways</h3><p><strong>Audio ML</strong> requires solid preprocessing — MFCCs made a big difference<br><strong>Classic models like SVM still hold their ground</strong> in many cases<br><strong>Online learning</strong> using Perceptron was fast and effective<br><strong>Streamlit makes deployment fast</strong>, giving ML models an intuitive frontend</p><blockquote>From building models to evaluating them and finally deploying them for real-time predictions, this project gave me an end-to-end experience of working with audio and structured data in machine learning.</blockquote><p>📌 <strong>Next Steps:</strong> I’d love to explore <strong>cross-lingual deepfake detection</strong> or try integrating <strong>transformer models</strong> in both parts of the project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a1aff15e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ TF-IDF vs One-Hot Encoding: Impact on PCA, SVD, and Disease Classification using KNN and…]]></title>
            <link>https://medium.com/@zainab29323/tf-idf-vs-one-hot-encoding-impact-on-pca-svd-and-disease-classification-using-knn-and-f0691c843aaa?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0691c843aaa</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 17:00:54 GMT</pubDate>
            <atom:updated>2025-04-14T17:00:54.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 TF-IDF vs One-Hot Encoding: Impact on PCA, SVD, and Disease Classification using KNN and Logistic Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ihND8qmgB5j0i3Ih23SGNA.jpeg" /></figure><p>Machine learning in healthcare has gained huge momentum, especially in predicting diseases based on symptoms, risk factors, and signs. But before feeding data into algorithms, one big question remains — <strong>how should we represent text data?</strong></p><p>In this project, we explored how <strong>TF-IDF</strong> and <strong>One-Hot Encoding</strong> influence dimensionality reduction and classification outcomes when using <strong>PCA, SVD</strong>, and classifiers like <strong>KNN</strong> and <strong>Logistic Regression</strong>. Let’s break it down.</p><h3>Problem Statement</h3><blockquote>Given a dataset with diseases and their associated <strong>risk factors</strong>, <strong>symptoms</strong>, <strong>signs</strong>, and <strong>subtypes</strong> (as stringified lists), we set out to:</blockquote><blockquote>Convert the data using <strong>TF-IDF</strong> and compare it with an existing <strong>One-Hot Encoded</strong> matrix.</blockquote><blockquote>Apply <strong>PCA</strong> and <strong>SVD</strong> to reduce dimensions and visualize disease clusters.</blockquote><blockquote>Train <strong>KNN (k=3, 5, 7)</strong> using different distance metrics and compare against <strong>Logistic Regression</strong>.</blockquote><blockquote>Analyze which encoding helps more in clustering and classification — and why.</blockquote><h3>TF-IDF Feature Extraction</h3><p>We first parsed the stringified lists into Python lists and merged them into strings. For example:</p><pre>[&quot;fever&quot;, &quot;stress&quot;] → &quot;fever stress&quot;</pre><p>Then, using TfidfVectorizer from sklearn, we generated separate TF-IDF matrices for:</p><blockquote><strong><em>Risk Factors</em></strong></blockquote><blockquote><strong><em>Symptoms</em></strong></blockquote><blockquote><strong><em>Signs</em></strong></blockquote><p>These were concatenated to form a single feature matrix. We compared this with the provided one-hot encoded matrix in terms of:</p><blockquote><strong><em>Sparsity</em></strong><em>: One-hot was sparser.</em></blockquote><blockquote><strong><em>Vocabulary size</em></strong><em>: TF-IDF had fewer features due to normalization and filtering out less informative words.</em></blockquote><h3>Dimensionality Reduction with PCA &amp; SVD</h3><p>We reduced both the TF-IDF and One-Hot feature matrices to <strong>2D</strong> and <strong>3D</strong> using:</p><ul><li><strong>Principal Component Analysis (PCA)</strong></li><li><strong>Truncated Singular Value Decomposition (SVD)</strong></li></ul><h3>Visualization</h3><p>We color-coded diseases by <strong>subtype</strong> (e.g., cardiovascular, neurological). Here’s what we found:</p><ul><li><strong>TF-IDF with PCA/SVD</strong> produced <strong>more compact and meaningful clusters</strong>.</li><li><strong>One-hot</strong> showed less separability due to binary and sparse representation.</li></ul><h3>Explained Variance:</h3><ul><li>TF-IDF retained more variance in top components compared to one-hot, proving its effectiveness in preserving semantic information.</li></ul><h3>Training Models</h3><h3>KNN Classifier (k = 3, 5, 7)</h3><p>We used:</p><blockquote><strong><em>Euclidean Distance</em></strong></blockquote><blockquote><strong><em>Manhattan Distance</em></strong></blockquote><blockquote><strong><em>Cosine Similarity</em></strong></blockquote><p>For each k and distance combo, we used <strong>5-fold cross-validation</strong> and reported:</p><blockquote><em>Accuracy</em></blockquote><blockquote><em>Precision</em></blockquote><blockquote><em>Recall</em></blockquote><blockquote><em>F1-Score</em></blockquote><p><strong>Observations</strong>:</p><ul><li>TF-IDF + Cosine similarity gave the best performance overall.</li><li>KNN with Euclidean/Manhattan on one-hot was less effective.</li></ul><h3>Logistic Regression</h3><p>We trained Logistic Regression models using both encodings.</p><ul><li><strong>TF-IDF</strong> again led to <strong>higher accuracy and F1-scores</strong>, especially for imbalanced classes.</li><li>Logistic Regression outperformed KNN in most cases due to its ability to generalize better.</li></ul><h3>Task 4: Critical Analysis</h3><h3>Why TF-IDF Might Work Better?</h3><ul><li>TF-IDF gives weight to <strong>important, non-frequent terms</strong>, unlike one-hot which treats all features equally.</li><li>It <strong>captures more context</strong> and reduces noise from overly common terms.</li></ul><h3>Clinical Relevance</h3><ul><li>Clusters in TF-IDF often aligned with disease categories like <strong>neurological</strong>, <strong>autoimmune</strong>, and <strong>infectious diseases</strong>.</li><li>This suggests TF-IDF preserves semantic relevance in a clinically meaningful way.</li></ul><h3>Limitations</h3><ul><li><strong>TF-IDF</strong> can be influenced by <strong>rare but non-informative features</strong>.</li><li><strong>One-hot</strong> ignores term importance and leads to sparse, high-dimensional vectors.</li><li>Dimensionality reduction methods like PCA are <strong>linear</strong> — they may not capture non-linear relationships.</li></ul><h3>Streamlit App for KNN</h3><p>We also built a <strong>Streamlit app</strong> to let users input symptoms and predict diseases using our trained KNN model. The app is simple and intuitive — perfect for demonstrating how ML can assist in medical diagnostics.</p><h3>Final Thoughts</h3><p>This project highlighted how <strong>feature encoding choices</strong> can significantly impact ML model performance, especially in text-heavy domains like healthcare. <strong>TF-IDF</strong>, when combined with smart dimensionality reduction and classification, can offer both <strong>better accuracy</strong> and <strong>more interpretable clustering</strong>.</p><p>If you’re working with medical or textual data, don’t overlook the power of the right encoding strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0691c843aaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Research Paper Data Annotation with LLMs]]></title>
            <link>https://medium.com/@zainab29323/automating-research-paper-data-annotation-with-llms-1f82a1a7c827?source=rss-98125b146f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f82a1a7c827</guid>
            <dc:creator><![CDATA[Zainab Rashid]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 15:00:27 GMT</pubDate>
            <atom:updated>2025-02-16T15:00:27.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ep11ssRVWDJhnk_Hg98niQ.jpeg" /><figcaption>Data Annotation</figcaption></figure><h3>Introduction</h3><blockquote>Previously, I wrote a web scraper in Python to extract research papers from NeurIPS (<a href="https://papers.nips.cc/">https://papers.nips.cc</a>) and store them locally or in the cloud. To get more details, check out my article: <a href="https://medium.com/@zainab29323/web-scraping-for-academic-research-challenges-and-insights-from-neurips-papers-f116b38440db">Web Scraping for Academic Research: Challenges and Insights from NeurIPS Papers.</a></blockquote><p>The rapid expansion of research publications makes it increasingly challenging to categorize papers efficiently. To address this, I automated the annotation process using Large Language Models (LLMs). By leveraging an open-source or freely available LLM API (e.g., Google Gemini, OpenAI ChatGPT, or any other API you have access to), I streamlined the classification of research papers from NeurIPS using Google Gemini.</p><h3>Approach</h3><p>The project aimed to enhance the usability of scraped research papers by assigning relevant categories. I followed a structured workflow to achieve this:</p><ol><li><strong>Selecting Annotation Categories</strong> — I identified five key research areas: Deep Learning, NLP, Computer Vision, Reinforcement Learning, and Optimization. These categories broadly encompass the majority of NeurIPS papers.</li><li><strong>Data Extraction</strong> — I retrieved research paper metadata, including titles and abstracts, from NeurIPS and structured them into a dataset.</li><li><strong>Automating Annotation</strong> — Each paper’s title and abstract were sent to an LLM API with a prompt instructing the model to classify the paper under one of the predefined categories.</li><li><strong>Storing Results</strong> — The assigned categories were appended as a new column in the dataset, making it suitable for further analysis.</li></ol><h3>Implementation</h3><p>To ensure smooth processing, I implemented retry logic to handle API rate limits and errors. An exponential backoff strategy was used to prevent excessive requests in a short period. I also included a delay between consecutive API calls to maintain stability. The final dataset was structured into a CSV format, allowing easy integration into future research projects or analysis tools.</p><h3>Challenges Faced</h3><p>While automating the annotation process, I encountered several hurdles:</p><ul><li><strong>API Rate Limits</strong> — Frequent API requests led to temporary access restrictions, which required implementing retry mechanisms.</li><li><strong>Ambiguous Classifications</strong> — Some research papers did not fit neatly into a single category, leading to instances where the model had to make an approximate classification.</li><li><strong>Data Consistency</strong> — Variations in abstract structures occasionally resulted in misclassifications, necessitating manual verification for edge cases.</li></ul><h3>Results and Takeaways</h3><p>The automated annotation process significantly improved the efficiency of categorizing research papers. The approach successfully labeled papers with high accuracy, reducing the time required for manual categorization. However, further refinements, such as fine-tuning an LLM on domain-specific research data, could improve precision.</p><h4>Key Takeaways:</h4><ul><li>Automating research paper annotation using LLMs is feasible and effective.</li><li>Proper handling of API rate limits is crucial for smooth execution.</li><li>Future enhancements could involve refining prompt engineering or incorporating domain-specific training data for better classification accuracy.</li></ul><p>By leveraging freely available LLM APIs, this project demonstrated how AI can assist researchers in managing large volumes of academic content efficiently.</p><h3>Importance in Data Science</h3><p>Automating research paper annotation is not just a time-saving technique but a crucial application of AI in data science. Categorization of unstructured text data enables better organization, searchability, and insights into academic trends. In broader data science applications, text classification using LLMs is widely used in:</p><ul><li><strong>Sentiment Analysis</strong> — Understanding public opinion through categorized reviews or social media posts.</li><li><strong>Healthcare</strong> — Categorizing medical records and research for better decision-making.</li><li><strong>Finance</strong> — Automating classification of financial reports and articles for quick analysis.</li><li><strong>Legal Tech</strong> — Streamlining case law research by categorizing legal documents efficiently.</li></ul><p>By applying AI-driven annotation techniques, researchers and professionals can leverage vast amounts of data more effectively, making it a powerful tool in modern data science workflows.</p><h3>What’s Next?</h3><p>The next steps in this project could involve:</p><ul><li><strong>Fine-tuning an LLM</strong> — Training a model on domain-specific research data to improve classification accuracy.</li><li><strong>Multi-label Classification</strong> — Allowing papers to be assigned multiple relevant categories instead of just one.</li><li><strong>Exploring Advanced AI Techniques</strong> — Incorporating other natural language processing (NLP) methods to enhance research paper understanding and categorization.</li></ul><blockquote><em>Automating research paper annotation is just the beginning. The potential of AI in academic research is vast, and with continuous advancements, we can further optimize the way we process and analyze scholarly work.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f82a1a7c827" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>