Spaces:
Runtime error
Runtime error
Download app.py from adwhytahumans/CRM_FastAPI_React: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/adwhytahumans/CRM_FastAPI_React/resolve/main/app.py
- Command line
-
hf download hf://spaces/adwhytahumans/CRM_FastAPI_React/app.py
-
curl -L -o app.py https://huggingface.co/spaces/adwhytahumans/CRM_FastAPI_React/resolve/main/app.py
15.1 kB
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, EmailStr, ConfigDict | |
| from typing import Optional, List, Literal | |
| from enum import Enum | |
| import uvicorn | |
| import groq | |
| from datetime import datetime | |
| import os | |
| from dotenv import load_dotenv | |
| import logging | |
| import csv | |
| import json | |
| from secret_manager import get_secret | |
| # Configure logging | |
| logging.basicConfig(level=logging.DEBUG) | |
| logger = logging.getLogger(__name__) | |
| # Load environment variables from .env file | |
| load_dotenv() | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="100x Elite CRM", | |
| description="CRM system for managing learner enrollments in 100x Elite courses", | |
| version="1.0.0" | |
| ) | |
| # Add CORS middleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["http://localhost:5173", "http://localhost:5174"], # Frontend URLs | |
| allow_credentials=True, | |
| allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], | |
| allow_headers=["Content-Type", "Accept", "Authorization"], | |
| expose_headers=["Content-Type", "Accept"], | |
| max_age=3600, | |
| ) | |
| # Initialize Groq client | |
| # groq_api_key = os.getenv("GROQ_API_KEY") | |
| # Replace the existing groq_api_key line with: | |
| groq_api_key = get_secret() | |
| if not groq_api_key: | |
| raise ValueError("GROQ_API_KEY not found in environment or Hugging Face secrets") | |
| logger.debug(f"Debug: Groq API Key loaded: {'Yes' if groq_api_key else 'No'}") | |
| if not groq_api_key: | |
| raise ValueError("GROQ_API_KEY environment variable is not set") | |
| client = groq.Groq(api_key=groq_api_key) | |
| logger.debug("Debug: Groq client initialized successfully") | |
| # Enum for course options | |
| class Course(str, Enum): | |
| AI_FILMMAKING = "AI Filmmaking" | |
| AI_MUSIC = "AI Music Composition" | |
| AI_MICROSAAS = "AI Micro SaaS App Building" | |
| # Enum for budget type | |
| class BudgetType(str, Enum): | |
| COMPANY = "company" | |
| SELF = "self" | |
| # Pydantic v2+ model for a learner (input) | |
| class LearnerIn(BaseModel): | |
| model_config = ConfigDict(from_attributes=True) | |
| name: str | |
| email: EmailStr | |
| phone: Optional[str] = None | |
| course: Course | |
| # Extended fields for qualification | |
| country: str | |
| goal: str | |
| budget: BudgetType | |
| webinar_join: datetime | |
| webinar_leave: datetime | |
| asked_q: bool | |
| referred: bool | |
| past_touchpoints: int | |
| # Pydantic v2+ model for a learner (output, with id and qualification) | |
| class LearnerOut(LearnerIn): | |
| id: int | |
| engaged_mins: Optional[int] = None # Make engaged_mins optional | |
| score: int | |
| reasoning: str | |
| status: Literal["Qualified", "Nurture"] | |
| # CSV file path | |
| CSV_FILE = "learners.csv" | |
| # Ensure CSV file exists with headers | |
| def init_csv(): | |
| if not os.path.exists(CSV_FILE): | |
| with open(CSV_FILE, 'w', newline='') as f: | |
| writer = csv.DictWriter(f, fieldnames=[ | |
| 'id', 'name', 'email', 'phone', 'course', 'country', 'goal', | |
| 'budget', 'webinar_join', 'webinar_leave', 'asked_q', | |
| 'referred', 'past_touchpoints', 'engaged_mins', 'score', | |
| 'reasoning', 'status' | |
| ]) | |
| writer.writeheader() | |
| # Initialize CSV file | |
| init_csv() | |
| # Helper functions for CSV operations | |
| def read_learners(): | |
| learners = {} | |
| with open(CSV_FILE, 'r', newline='') as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| # Convert string values to appropriate types | |
| row['id'] = int(row['id']) | |
| row['asked_q'] = row['asked_q'].lower() == 'true' | |
| row['referred'] = row['referred'].lower() == 'true' | |
| row['past_touchpoints'] = int(row['past_touchpoints']) | |
| row['engaged_mins'] = int(row['engaged_mins']) | |
| row['score'] = int(row['score']) | |
| row['course'] = Course[row['course']] | |
| row['budget'] = BudgetType[row['budget']] | |
| learners[row['id']] = row | |
| return learners | |
| def write_learners(learners): | |
| with open(CSV_FILE, 'w', newline='') as f: | |
| writer = csv.DictWriter(f, fieldnames=[ | |
| 'id', 'name', 'email', 'phone', 'course', 'country', 'goal', | |
| 'budget', 'webinar_join', 'webinar_leave', 'asked_q', | |
| 'referred', 'past_touchpoints', 'engaged_mins', 'score', | |
| 'reasoning', 'status' | |
| ]) | |
| writer.writeheader() | |
| for learner in learners.values(): | |
| # Convert enum values to strings | |
| learner_copy = learner.copy() | |
| learner_copy['course'] = learner_copy['course'].name | |
| learner_copy['budget'] = learner_copy['budget'].name | |
| writer.writerow(learner_copy) | |
| def get_next_id(): | |
| learners = read_learners() | |
| return max(learners.keys(), default=0) + 1 | |
| def calculate_engagement_minutes(join_time: datetime, leave_time: datetime) -> int: | |
| """Calculate engagement minutes from join and leave times.""" | |
| delta = leave_time - join_time | |
| return int(delta.total_seconds() / 60) | |
| def qualify_learner(learner_data: dict) -> dict: | |
| """Use Groq LLM to qualify the learner and generate score and reasoning.""" | |
| try: | |
| # Prepare the prompt for the LLM | |
| prompt = f"""You are a lead qualification system. Based on the following learner data, calculate a qualification score and provide reasoning. | |
| FIT CALCULATION (40% of total score): | |
| Evaluate these specific criteria: | |
| 1. Goal-Course Alignment (20 points): | |
| - Perfect alignment (e.g., "Become an AI PM" for AI course): 20 points | |
| - Related goal (e.g., "Learn AI" for AI course): 15 points | |
| - Somewhat related: 10 points | |
| - Unrelated: 0 points | |
| 2. Country Fit (10 points): | |
| - Target market (US, UK, Canada, Australia): 10 points | |
| - Secondary market (India, Singapore): 8 points | |
| - Other markets: 5 points | |
| 3. Background Relevance (10 points): | |
| - Tech/Product background: 10 points | |
| - Related field: 7 points | |
| - Other background: 3 points | |
| OTHER CRITERIA: | |
| - Engagement (25%): Webinar interaction and questions | |
| - Intent (20%): Stated goals alignment | |
| - Budget (10%): Financial capability | |
| - Past Touchpoints (5%): Previous interactions | |
| Learner Data: | |
| - Name: {learner_data['name']} | |
| - Goal: {learner_data['goal']} | |
| - Country: {learner_data['country']} | |
| - Course: {learner_data['course']} | |
| - Budget: {learner_data['budget']} | |
| - Webinar Duration: {learner_data['engaged_mins']} minutes | |
| - Asked Questions: {learner_data['asked_q']} | |
| - Referred: {learner_data['referred']} | |
| - Past Touchpoints: {learner_data['past_touchpoints']} | |
| IMPORTANT: You must respond in EXACTLY this format, with no additional text: | |
| Score: [number between 0-100] | |
| Reasoning: [brief explanation including fit breakdown] | |
| Status: [Qualified if score >= 70, Nurture if score < 70] | |
| Example response: | |
| Score: 85 | |
| Reasoning: Strong fit (35/40): Perfect goal-course alignment (20), target market (10), tech background (5). High engagement (20/25), clear intent (15/20), self-funded (10/10), multiple touchpoints (5/5). | |
| Status: Qualified | |
| """ | |
| logger.debug("Sending prompt to Groq LLM...") | |
| # Call Groq LLM | |
| response = client.chat.completions.create( | |
| model="meta-llama/llama-4-scout-17b-16e-instruct", | |
| messages=[{"role": "user", "content": prompt}] | |
| ) | |
| # Parse the response | |
| result = response.choices[0].message.content | |
| logger.debug(f"Raw LLM response: {result}") | |
| # Split into lines and clean up | |
| lines = [line.strip() for line in result.strip().split('\n') if line.strip()] | |
| logger.debug(f"Parsed lines: {lines}") | |
| if len(lines) < 3: | |
| raise ValueError(f"Unexpected response format. Got {len(lines)} lines, expected 3. Response: {result}") | |
| # Extract score, reasoning, and status | |
| score_line = next((line for line in lines if line.startswith('Score:')), None) | |
| reasoning_line = next((line for line in lines if line.startswith('Reasoning:')), None) | |
| status_line = next((line for line in lines if line.startswith('Status:')), None) | |
| if not all([score_line, reasoning_line, status_line]): | |
| raise ValueError(f"Missing required fields in response. Response: {result}") | |
| score = int(score_line.split(':')[1].strip()) | |
| reasoning = reasoning_line.split(':')[1].strip() | |
| status = status_line.split(':')[1].strip() | |
| if status not in ["Qualified", "Nurture"]: | |
| raise ValueError(f"Invalid status: {status}. Must be 'Qualified' or 'Nurture'") | |
| logger.debug(f"Parsed qualification: score={score}, status={status}") | |
| return { | |
| "score": score, | |
| "reasoning": reasoning, | |
| "status": status | |
| } | |
| except Exception as e: | |
| logger.error(f"Error in qualify_learner: {str(e)}", exc_info=True) | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Error qualifying learner: {str(e)}" | |
| ) | |
| def get_all_learners(): | |
| """Get all enrolled learners.""" | |
| try: | |
| learners = [] | |
| for lid, learner in read_learners().items(): | |
| # Calculate engaged_mins if not present | |
| if 'engaged_mins' not in learner: | |
| try: | |
| learner['engaged_mins'] = calculate_engagement_minutes( | |
| learner['webinar_join'], | |
| learner['webinar_leave'] | |
| ) | |
| except Exception as e: | |
| logger.warning(f"Could not calculate engaged_mins for learner {lid}: {str(e)}") | |
| learner['engaged_mins'] = 0 # Set a default value | |
| # Ensure all required fields are present | |
| if 'score' not in learner: | |
| learner['score'] = 0 | |
| if 'reasoning' not in learner: | |
| learner['reasoning'] = "No reasoning available" | |
| if 'status' not in learner: | |
| learner['status'] = "Nurture" | |
| # Create a copy of the learner dict without the id field | |
| learner_data = learner.copy() | |
| learner_data.pop('id', None) # Remove id if it exists | |
| # Create LearnerOut with the correct id | |
| learners.append(LearnerOut(id=lid, **learner_data)) | |
| return learners | |
| except Exception as e: | |
| logger.error(f"Error in get_all_learners: {str(e)}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def create_learner(learner: LearnerIn): | |
| """Create a new learner enrollment with qualification.""" | |
| try: | |
| logger.debug(f"Received learner data: {learner.model_dump()}") | |
| learners = read_learners() | |
| try: | |
| # Calculate engagement minutes | |
| join_time = learner.webinar_join | |
| leave_time = learner.webinar_leave | |
| engaged_mins = calculate_engagement_minutes(join_time, leave_time) | |
| logger.debug(f"Calculated engagement minutes: {engaged_mins}") | |
| except Exception as e: | |
| logger.error(f"Error calculating engagement minutes: {str(e)}") | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Invalid datetime format: {str(e)}" | |
| ) | |
| # Prepare data for qualification | |
| learner_data = learner.model_dump() | |
| learner_data['engaged_mins'] = engaged_mins | |
| logger.debug(f"Prepared learner data for qualification: {learner_data}") | |
| try: | |
| # Get qualification from LLM | |
| qualification = qualify_learner(learner_data) | |
| logger.debug(f"Received qualification: {qualification}") | |
| except Exception as e: | |
| logger.error(f"Error in qualification: {str(e)}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Error qualifying learner: {str(e)}" | |
| ) | |
| # Create new learner with qualification | |
| new_learner = { | |
| 'id': get_next_id(), | |
| **learner.model_dump(), | |
| 'engaged_mins': engaged_mins, | |
| 'score': qualification['score'], | |
| 'reasoning': qualification['reasoning'], | |
| 'status': qualification['status'] | |
| } | |
| logger.debug(f"Created new learner object: {new_learner}") | |
| try: | |
| # Save to CSV | |
| learners[new_learner['id']] = new_learner | |
| write_learners(learners) | |
| logger.debug(f"Successfully saved learner to CSV with ID: {new_learner['id']}") | |
| except Exception as e: | |
| logger.error(f"Error saving to CSV: {str(e)}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Error saving learner data: {str(e)}" | |
| ) | |
| return new_learner | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Unexpected error in create_learner: {str(e)}", exc_info=True) | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Unexpected error: {str(e)}" | |
| ) | |
| def update_learner(learner_id: int, learner: LearnerIn): | |
| """Update learner information by ID.""" | |
| learners = read_learners() | |
| if learner_id not in learners: | |
| raise HTTPException(status_code=404, detail="Learner not found") | |
| # Calculate engagement minutes | |
| join_time = datetime.fromisoformat(learner.webinar_join) | |
| leave_time = datetime.fromisoformat(learner.webinar_leave) | |
| engaged_mins = int((leave_time - join_time).total_seconds() / 60) | |
| # Prepare data for qualification | |
| learner_data = learner.dict() | |
| learner_data['engaged_mins'] = engaged_mins | |
| # Get qualification from LLM | |
| qualification = qualify_learner(learner_data) | |
| # Update learner | |
| learners[learner_id] = { | |
| 'id': learner_id, | |
| **learner.dict(), | |
| 'engaged_mins': engaged_mins, | |
| 'score': qualification['score'], | |
| 'reasoning': qualification['reasoning'], | |
| 'status': qualification['status'] | |
| } | |
| # Save to CSV | |
| write_learners(learners) | |
| return learners[learner_id] | |
| def delete_learner(learner_id: int): | |
| """Delete a learner by ID.""" | |
| learners = read_learners() | |
| if learner_id not in learners: | |
| raise HTTPException(status_code=404, detail="Learner not found") | |
| del learners[learner_id] | |
| write_learners(learners) | |
| return {"message": "Learner deleted successfully"} | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=8000) |