Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.venv
__pycache__
Binary file added PythonTask.pdf
Binary file not shown.
60 changes: 59 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,59 @@
# UrbanMatch-PythonTask
<<<<<<< HEAD
# Marriage Matchmaking App

## Brief Description
The Marriage Matchmaking App is a simple backend application designed to help users find potential matches based on their profile information. The app allows users to create, read, update, and delete profiles with details such as name, age, gender, email, city, and interests.

## What is Provided?
This project provides a basic skeleton for a FastAPI-based backend application.
#### Github repo: **https://github.com/abhishek-UM/UrbanMatch-PythonTask/tree/master**

The provided code includes:

### Basic Project Structure:

- **main.py** : The main application file with basic CRUD operations for user profiles.
- **models.py**: SQLAlchemy models defining the User schema.
- **database.py**: Database configuration and setup.
- **schemas.py**: Pydantic schemas for data validation and serialization.

### Functionality:

- Create User Endpoint: Create a new user profile.
- Read Users Endpoint: Retrieve a list of user profiles.
- Read User by ID Endpoint: Retrieve a user profile by ID.
- SQLite Database: The application uses SQLite as the database to store user profiles.

## What is Required?
### Tasks:
1. Add User Update Endpoint:
- Implement an endpoint to update user details by ID in the main.py file.
2. Add User Deletion Endpoint:
- Implement an endpoint to delete a user profile by ID.
3. Find Matches for a User:
- Implement an endpoint to find potential matches for a user based on their profile information.
4. Add Email Validation:
- Add validation to ensure the email field in user profiles contains valid email addresses.

## Instructions:
Implement the required endpoints and email validation:

1. Add the necessary code for the update, delete, match and validation endpoints
2. Test Your Implementation:
1. Verify that users can be updated and deleted correctly.
2. Check that matches are correctly retrieved for a given user.
3. Ensure email validation is working as expected.

## Submit Your Work:
Provide the updated code files (main.py, models.py, database.py, and schemas.py).
Include a brief report explaining your approach and any assumptions made.


### Prerequisites
- Python 3.7+
- FastAPI
- SQLAlchemy
- SQLite
=======
# UrbanMatch-PythonTask
>>>>>>> f167553ae8b55f1b45acad5e31b8664f61fad37c
12 changes: 12 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
176 changes: 176 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, Base
import models, schemas
from typing import List
from pydantic import EmailStr

app = FastAPI()

Base.metadata.create_all(bind=engine)


class MatchingAlgorithm:
WEIGHTS = {"age": 0.3, "location": 0.3, "interests": 0.4}

MAX_AGE_DIFF = 10

@staticmethod
def calculate_age_score(user_age: int, match_age: int) -> float:
"""Calculate age compatibility (0 to 1)"""
age_diff = abs(user_age - match_age)
if age_diff > MatchingAlgorithm.MAX_AGE_DIFF:
return 0
return 1 - (age_diff / MatchingAlgorithm.MAX_AGE_DIFF)

@staticmethod
def calculate_location_score(user_city: str, match_city: str) -> float:
"""Calculate location compatibility (0 or 1)"""
return 1.0 if user_city.lower() == match_city.lower() else 0.0

@staticmethod
def calculate_interests_score(
user_interests: List[str], match_interests: List[str]
) -> float:
"""Calculate interests compatibility (0 to 1)"""
user_interests_set = set(interest.lower() for interest in user_interests)
match_interests_set = set(interest.lower() for interest in match_interests)

if not user_interests_set or not match_interests_set:
return 0.0

common_interests = len(user_interests_set.intersection(match_interests_set))
total_interests = len(user_interests_set)

return common_interests / total_interests


def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()


@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
existing_user = (
db.query(models.User).filter(models.User.email == user.email).first()
)
if existing_user:
raise HTTPException(status_code=400, detail="Email already registered")

user_data = user.dict()
db_user = models.User(**user_data)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user


@app.get("/users/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
users = db.query(models.User).offset(skip).limit(limit).all()
return users


@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(models.User).filter(models.User.id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user


@app.put("/users/{user_id}", response_model=schemas.User)
def update_user(
user_id: int, user_update: schemas.UserUpdate, db: Session = Depends(get_db)
):
db_user = db.query(models.User).filter(models.User.id == user_id).first()
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")

if user_update.email and user_update.email != db_user.email:
existing_user = (
db.query(models.User).filter(models.User.email == user_update.email).first()
)
if existing_user:
raise HTTPException(status_code=400, detail="Email already registered")

update_data = user_update.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_user, key, value)

db.commit()
db.refresh(db_user)
return db_user


@app.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(models.User).filter(models.User.id == user_id).first()
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")

db.delete(db_user)
db.commit()
return {"message": "User deleted successfully"}


@app.get("/users/{user_id}/matches", response_model=List[schemas.UserMatch])
def find_matches(
user_id: int,
db: Session = Depends(get_db),
min_age: int = None,
max_age: int = None,
):
"""Find matches for a user"""
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")

matches_query = db.query(models.User).filter(
models.User.id != user_id,
models.User.gender != user.gender,
)

if min_age:
matches_query = matches_query.filter(models.User.age >= min_age)
if max_age:
matches_query = matches_query.filter(models.User.age <= max_age)

potential_matches = matches_query.all()
scored_matches = []

for match in potential_matches:
age_score = MatchingAlgorithm.calculate_age_score(user.age, match.age)
location_score = MatchingAlgorithm.calculate_location_score(
user.city, match.city
)
interests_score = MatchingAlgorithm.calculate_interests_score(
user.interests, match.interests
)

total_score = (
age_score * MatchingAlgorithm.WEIGHTS["age"]
+ location_score * MatchingAlgorithm.WEIGHTS["location"]
+ interests_score * MatchingAlgorithm.WEIGHTS["interests"]
)

if total_score > 0.5:
scored_matches.append(
{
"user": match,
"compatibility_score": round(total_score, 2),
"match_details": {
"age_compatibility": round(age_score, 2),
"location_compatibility": round(location_score, 2),
"interests_compatibility": round(interests_score, 2),
},
}
)

scored_matches.sort(key=lambda x: x["compatibility_score"], reverse=True)

return scored_matches
14 changes: 14 additions & 0 deletions models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from sqlalchemy import Column, Integer, String, JSON
from database import Base


class User(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
age = Column(Integer)
gender = Column(String)
email = Column(String, unique=True, index=True)
city = Column(String, index=True)
interests = Column(JSON)
42 changes: 42 additions & 0 deletions schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from pydantic import BaseModel, EmailStr
from typing import List, Optional, Dict


class UserBase(BaseModel):
name: str
age: int
gender: str
email: EmailStr
city: str
interests: List[str]


class UserCreate(UserBase):
pass


class UserUpdate(BaseModel):
name: Optional[str] = None
age: Optional[int] = None
email: Optional[EmailStr] = None
city: Optional[str] = None
interests: Optional[List[str]] = None


class MatchDetails(BaseModel):
age_compatibility: float
location_compatibility: float
interests_compatibility: float


class UserMatch(BaseModel):
user: "User"
compatibility_score: float
match_details: MatchDetails


class User(UserBase):
id: int

class Config:
orm_mode = True
Binary file added sql_app.db
Binary file not shown.
Binary file added test.db
Binary file not shown.