# Go to python.org/downloads → download Python 3.11 # During install: CHECK "Add Python to PATH" box # Verify install — open Command Prompt and run: python --version # Should show: Python 3.11.x
# Open Terminal and run:
brew install python@3.11
python3 --version
VS Code is where you'll write and run your Python scripts. Download from code.visualstudio.com
# In VS Code: View → Terminal # Create your project folder: mkdir jewelry_ai_system cd jewelry_ai_system # Create virtual environment (keeps libraries clean): python -m venv venv # Activate it: # Windows: venv\Scripts\activate # Mac/Linux: source venv/bin/activate # You'll see (venv) in your terminal — good!
anthropic==0.34.0 google-auth==2.28.0 google-auth-oauthlib==1.2.0 google-api-python-client==2.120.0 requests==2.31.0 beautifulsoup4==4.12.3 gspread==6.0.2 python-dotenv==1.0.1 schedule==1.2.1 pandas==2.2.0
pip install -r requirements.txt
# Copy this, fill in your actual keys
ANTHROPIC_API_KEY=sk-ant-api03-XXXXXXXXXXXXXXXXXXXXXXXXXX
GMAIL_SENDER_EMAIL=yourname@gmail.com
SERPAPI_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GOOGLE_SHEETS_ID=1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms
YOUR_COMPANY_NAME=Sharma Jewellers
YOUR_CATALOG_URL=https://yourwebsite.com/catalog
YOUR_PHONE=+91-9876543210
YOUR_CITY=Jaipur
.env venv/ __pycache__/ *.pyc credentials.json token.json
""" Jewelry AI Automation System Runs daily at 6 AM — research, leads, emails, follow-ups """ import os, json, requests, schedule, time from datetime import datetime, timedelta from dotenv import load_dotenv import anthropic from gmail_helper import send_email, check_replies from sheets_helper import log_lead, get_followup_leads, update_lead_status load_dotenv() client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) TODAY = datetime.now().strftime("%B %d, %Y") # ═══════════════════════════════════════ # STEP 1: MARKET RESEARCH # ═══════════════════════════════════════ def fetch_jewelry_trends(): """Search for today's jewelry market trends""" serpapi_key = os.getenv("SERPAPI_KEY") queries = [ "jewelry trends India 2025 wholesale", "gold jewelry demand today India", "bridal jewelry trending this month" ] all_results = [] for q in queries: r = requests.get("https://serpapi.com/search", params={ "q": q, "api_key": serpapi_key, "num": 5 }) data = r.json() snippets = [x.get("snippet", "") for x in data.get("organic_results", [])] all_results.extend(snippets) return " | ".join(all_results[:12]) def analyze_market(raw_data): """Claude analyzes market data and returns insights""" with open("prompts/market_analyst.txt") as f: system = f.read().replace("{TODAY_DATE}", TODAY) response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1500, system=system, messages=[{"role": "user", "content": f"Here is today's raw market data:\n\n{raw_data}\n\nAnalyze and give me the JSON output."}] ) return json.loads(response.content[0].text) # ═══════════════════════════════════════ # STEP 2: LEAD GENERATION # ═══════════════════════════════════════ def find_jewelry_leads(market_insights): """Find 20 B2B leads from web search""" top_items = market_insights.get("trending_items", []) serpapi_key = os.getenv("SERPAPI_KEY") lead_queries = [ "jewelry retailer store Delhi contact email", "bridal jewelry boutique Mumbai email", "wholesale jewelry buyer Bangalore contact", "fashion accessories store India email wholesale" ] raw_leads = [] for q in lead_queries: r = requests.get("https://serpapi.com/search", params={ "q": q, "api_key": serpapi_key, "num": 8 }) data = r.json() for result in data.get("organic_results", []): raw_leads.append({ "title": result.get("title"), "link": result.get("link"), "snippet": result.get("snippet") }) return qualify_leads(raw_leads[:30], market_insights) def qualify_leads(raw_leads, market_insights): """Claude qualifies and scores leads""" with open("prompts/lead_qualifier.txt") as f: system = f.read() response = client.messages.create( model="claude-sonnet-4-5", max_tokens=3000, system=system, messages=[{"role": "user", "content": f"Qualify these leads. Return top 20 as JSON array.\n\nLeads:\n{json.dumps(raw_leads)}\n\nToday's trending products:\n{market_insights.get('trending_items', [])}"}] ) return json.loads(response.content[0].text) # ═══════════════════════════════════════ # STEP 3: WRITE AND SEND EMAILS # ═══════════════════════════════════════ def write_and_send_emails(leads, market_insights): """Write personalized email for each lead and send""" with open("prompts/email_writer.txt") as f: system = f.read() system = system.replace("{COMPANY_NAME}", os.getenv("YOUR_COMPANY_NAME")) system = system.replace("{CATALOG_URL}", os.getenv("YOUR_CATALOG_URL")) system = system.replace("{PHONE}", os.getenv("YOUR_PHONE")) sent_count = 0 for lead in leads[:20]: if not lead.get("email"): continue response = client.messages.create( model="claude-haiku-4-5", max_tokens=600, system=system, messages=[{"role": "user", "content": f"Write cold email for this lead:\n{json.dumps(lead)}\n\nToday's top trending item to mention:\n{market_insights['trending_items'][0] if market_insights.get('trending_items') else 'premium gold jewelry'}"}] ) email_data = json.loads(response.content[0].text) send_email( to=lead["email"], subject=email_data["subject"], body=email_data["body"] + "\n\n" + email_data.get("ps_line", "") ) lead["email_sent_date"] = TODAY lead["followup_date"] = (datetime.now() + timedelta(days=3)).strftime("%Y-%m-%d") lead["email_subject"] = email_data["subject"] log_lead(lead) sent_count += 1 time.sleep(3) return sent_count # ═══════════════════════════════════════ # STEP 4: FOLLOW-UPS # ═══════════════════════════════════════ def send_followups(): """Check who needs follow-up and send""" leads_to_followup = get_followup_leads() with open("prompts/followup_writer.txt") as f: system = f.read().replace("{COMPANY_NAME}", os.getenv("YOUR_COMPANY_NAME")) for lead in leads_to_followup: days_ago = lead.get("days_since_first_email", 3) response = client.messages.create( model="claude-haiku-4-5", max_tokens=400, system=system.replace("{DAYS_AGO}", str(days_ago)) .replace("{LEAD_TYPE}", lead.get("lead_quality", "warm")) .replace("{FIRST_EMAIL_SUBJECT}", lead.get("email_subject", "")), messages=[{"role": "user", "content": f"Write follow-up for: {lead['company_name']}"}] ) fu_data = json.loads(response.content[0].text) send_email(lead["email"], fu_data["subject"], fu_data["body"]) update_lead_status(lead["email"], "followup_sent") time.sleep(2) # ═══════════════════════════════════════ # DAILY JOB — runs everything # ═══════════════════════════════════════ def daily_job(): print(f"[{datetime.now()}] Starting daily jewelry automation...") print("→ Fetching market trends...") raw_data = fetch_jewelry_trends() print("→ Analyzing with Claude...") insights = analyze_market(raw_data) print(f" Top trend: {insights.get('trending_items', ['N/A'])[0]}") print("→ Finding leads...") leads = find_jewelry_leads(insights) print(f" Found {len(leads)} qualified leads") print("→ Writing and sending emails...") sent = write_and_send_emails(leads, insights) print(f" Sent {sent} emails") print("→ Processing follow-ups...") send_followups() print("✓ Daily job complete!") # Schedule to run at 6 AM every day schedule.every().day.at("06:00").do(daily_job) if __name__ == "__main__": print("Jewelry AI System started. Waiting for 6 AM...") daily_job() # Run once immediately for testing while True: schedule.run_pending() time.sleep(60)
import os, base64 from email.mime.text import MIMEText from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from google.auth.transport.requests import Request SCOPES = ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.readonly'] def get_gmail_service(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) return build('gmail', 'v1', credentials=creds) def send_email(to, subject, body): service = get_gmail_service() sender = os.getenv("GMAIL_SENDER_EMAIL") message = MIMEText(body) message['to'] = to message['from'] = sender message['subject'] = subject raw = base64.urlsafe_b64encode(message.as_bytes()).decode() service.users().messages().send(userId='me', body={'raw': raw}).execute() print(f" ✓ Email sent to {to}")
import os, gspread from datetime import datetime, timedelta from google.oauth2.credentials import Credentials def get_sheet(): creds = Credentials.from_authorized_user_file('token.json') gc = gspread.authorize(creds) return gc.open_by_key(os.getenv("GOOGLE_SHEETS_ID")).sheet1 def log_lead(lead): sheet = get_sheet() row = [ lead.get("company_name"), lead.get("contact_name"), lead.get("email"), lead.get("phone"), lead.get("city"), lead.get("lead_quality"), lead.get("best_product_fit"), lead.get("email_sent_date"), lead.get("followup_date"), lead.get("email_subject"), "sent" ] sheet.append_row(row) def get_followup_leads(): sheet = get_sheet() today = datetime.now().strftime("%Y-%m-%d") records = sheet.get_all_records() return [r for r in records if r.get("followup_date") <= today and r.get("status") == "sent"] def update_lead_status(email, status): sheet = get_sheet() cell = sheet.find(email) if cell: sheet.update_cell(cell.row, 11, status)
# Make sure you're in your project folder with venv activated cd jewelry_ai_system source venv/bin/activate # Mac/Linux # venv\Scripts\activate # Windows # Run the system once (for testing) python main.py # First run: browser will open for Gmail permission # Click "Allow" → it saves token.json → never asks again
To run automatically every day without keeping your PC on, deploy to a small cloud server.
# 1. Create account at railway.app # 2. Install Railway CLI: npm install -g @railway/cli # 3. Login and deploy: railway login railway init railway up # 4. Set environment variables in Railway dashboard # (same as your .env file — paste each key) # 5. Your system now runs 24/7 in the cloud! # Cost: Free tier
0 6 * * * cd ~/jewelry_ai_system && python main.py