From 67e6ed674dba018543002ad10f4bf2af9d6051da Mon Sep 17 00:00:00 2001 From: Mohamed Thousif Date: Sun, 12 Apr 2026 09:01:18 +0530 Subject: [PATCH] Completed AI project with Endee --- backend/.gitattributes | 2 + backend/.gitignore | 33 ++ backend/.mvn/wrapper/maven-wrapper.properties | 3 + backend/mvnw | 295 ++++++++++++++++++ backend/mvnw.cmd | 189 +++++++++++ backend/pom.xml | 102 ++++++ .../ResumeMatcherApplication.java | 15 + .../com/resumematcher/client/EndeeClient.java | 181 +++++++++++ .../com/resumematcher/config/AppConfig.java | 38 +++ .../com/resumematcher/config/EndeeConfig.java | 15 + .../controller/ResumeController.java | 111 +++++++ .../dto/request/JobDescriptionRequest.java | 16 + .../dto/request/ResumeUploadResponse.java | 0 .../dto/response/MatchResult.java | 16 + .../dto/response/ResumeMetadata.java | 17 + .../exception/BusinessException.java | 11 + .../exception/GlobalExceptionHandler.java | 72 +++++ .../resumematcher/model/ResumeDocument.java | 0 .../service/EmbeddingService.java | 124 ++++++++ .../service/ResumeMatcherService.java | 156 +++++++++ .../service/ResumeParserService.java | 143 +++++++++ .../src/main/resources/application-dev.yml | 0 .../src/main/resources/application.properties | 1 + backend/src/main/resources/application.yml | 42 +++ .../BackendApplicationTests.java | 13 + 25 files changed, 1595 insertions(+) create mode 100644 backend/.gitattributes create mode 100644 backend/.gitignore create mode 100644 backend/.mvn/wrapper/maven-wrapper.properties create mode 100644 backend/mvnw create mode 100644 backend/mvnw.cmd create mode 100644 backend/pom.xml create mode 100644 backend/src/main/java/com/resumematcher/ResumeMatcherApplication.java create mode 100644 backend/src/main/java/com/resumematcher/client/EndeeClient.java create mode 100644 backend/src/main/java/com/resumematcher/config/AppConfig.java create mode 100644 backend/src/main/java/com/resumematcher/config/EndeeConfig.java create mode 100644 backend/src/main/java/com/resumematcher/controller/ResumeController.java create mode 100644 backend/src/main/java/com/resumematcher/dto/request/JobDescriptionRequest.java create mode 100644 backend/src/main/java/com/resumematcher/dto/request/ResumeUploadResponse.java create mode 100644 backend/src/main/java/com/resumematcher/dto/response/MatchResult.java create mode 100644 backend/src/main/java/com/resumematcher/dto/response/ResumeMetadata.java create mode 100644 backend/src/main/java/com/resumematcher/exception/BusinessException.java create mode 100644 backend/src/main/java/com/resumematcher/exception/GlobalExceptionHandler.java create mode 100644 backend/src/main/java/com/resumematcher/model/ResumeDocument.java create mode 100644 backend/src/main/java/com/resumematcher/service/EmbeddingService.java create mode 100644 backend/src/main/java/com/resumematcher/service/ResumeMatcherService.java create mode 100644 backend/src/main/java/com/resumematcher/service/ResumeParserService.java create mode 100644 backend/src/main/resources/application-dev.yml create mode 100644 backend/src/main/resources/application.properties create mode 100644 backend/src/main/resources/application.yml create mode 100644 backend/src/test/java/com/resumematcher/BackendApplicationTests.java diff --git a/backend/.gitattributes b/backend/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/backend/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000000..667aaef0c8 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/backend/.mvn/wrapper/maven-wrapper.properties b/backend/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..c595b0093a --- /dev/null +++ b/backend/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip diff --git a/backend/mvnw b/backend/mvnw new file mode 100644 index 0000000000..bd8896bf22 --- /dev/null +++ b/backend/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/mvnw.cmd b/backend/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/backend/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/pom.xml b/backend/pom.xml new file mode 100644 index 0000000000..59cfd33b99 --- /dev/null +++ b/backend/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + + com.resumematcher + resume-matcher-backend + 1.0.0 + AI Resume Matcher + Semantic resume matching using Endee vector database + + + 17 + 1.18.30 + 0.12.0 + 2.9.1 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + com.theokanning.openai-gpt3-java + service + ${openai.version} + + + + + org.apache.tika + tika-core + ${apache.tika.version} + + + org.apache.tika + tika-parsers-standard-package + ${apache.tika.version} + + + + + org.apache.httpcomponents.client5 + httpclient5 + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/ResumeMatcherApplication.java b/backend/src/main/java/com/resumematcher/ResumeMatcherApplication.java new file mode 100644 index 0000000000..e75612060c --- /dev/null +++ b/backend/src/main/java/com/resumematcher/ResumeMatcherApplication.java @@ -0,0 +1,15 @@ +package com.resumematcher; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +@EnableConfigurationProperties +public class ResumeMatcherApplication { + public static void main(String[] args) { + SpringApplication.run(ResumeMatcherApplication.class, args); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/client/EndeeClient.java b/backend/src/main/java/com/resumematcher/client/EndeeClient.java new file mode 100644 index 0000000000..d7124b017a --- /dev/null +++ b/backend/src/main/java/com/resumematcher/client/EndeeClient.java @@ -0,0 +1,181 @@ +package com.resumematcher.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.resumematcher.config.EndeeConfig; +import com.resumematcher.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.*; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor +public class EndeeClient { + + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; + private final EndeeConfig endeeConfig; + + /** + * Creates an index in Endee if it doesn't already exist + */ + public void createIndexIfNotExists() { + try { + // Check if index exists + String checkUrl = endeeConfig.getBaseUrl() + "/v1/indexes/" + endeeConfig.getIndexName(); + try { + ResponseEntity response = restTemplate.getForEntity(checkUrl, JsonNode.class); + if (response.getStatusCode() == HttpStatus.OK) { + log.info("Index '{}' already exists", endeeConfig.getIndexName()); + return; + } + } catch (RestClientException e) { + log.info("Index '{}' not found, creating new one", endeeConfig.getIndexName()); + } + + // Create index + String createUrl = endeeConfig.getBaseUrl() + "/v1/indexes"; + ObjectNode requestBody = objectMapper.createObjectNode(); + requestBody.put("name", endeeConfig.getIndexName()); + requestBody.put("dimension", endeeConfig.getVectorDimension()); + requestBody.put("metric", endeeConfig.getSimilarityMetric()); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(requestBody.toString(), headers); + + ResponseEntity response = restTemplate.postForEntity(createUrl, entity, JsonNode.class); + + if (response.getStatusCode() == HttpStatus.CREATED || response.getStatusCode() == HttpStatus.OK) { + log.info("Successfully created index '{}'", endeeConfig.getIndexName()); + } else { + log.warn("Unexpected response while creating index: {}", response.getStatusCode()); + } + } catch (Exception e) { + log.error("Failed to create index: {}", e.getMessage()); + throw new BusinessException("Failed to initialize vector database: " + e.getMessage()); + } + } + + /** + * Inserts a vector with metadata into Endee + */ + public void insertVector(String id, List vector, Map metadata) { + try { + String url = endeeConfig.getBaseUrl() + "/v1/indexes/" + endeeConfig.getIndexName() + "/vectors"; + + ObjectNode requestBody = objectMapper.createObjectNode(); + requestBody.put("id", id); + + ArrayNode vectorArray = objectMapper.createArrayNode(); + for (Double value : vector) { + vectorArray.add(value); + } + requestBody.set("vector", vectorArray); + + ObjectNode metadataNode = objectMapper.valueToTree(metadata); + requestBody.set("metadata", metadataNode); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(requestBody.toString(), headers); + + ResponseEntity response = restTemplate.postForEntity(url, entity, JsonNode.class); + + if (response.getStatusCode() == HttpStatus.CREATED || response.getStatusCode() == HttpStatus.OK) { + log.debug("Successfully inserted vector with id: {}", id); + } else { + log.error("Failed to insert vector: {}", response.getStatusCode()); + throw new BusinessException("Failed to insert vector into Endee"); + } + } catch (Exception e) { + log.error("Error inserting vector: {}", e.getMessage()); + throw new BusinessException("Failed to store resume embedding: " + e.getMessage()); + } + } + + /** + * Searches for similar vectors in Endee + */ + public List searchSimilar(List queryVector, int topK) { + try { + String url = endeeConfig.getBaseUrl() + "/v1/indexes/" + endeeConfig.getIndexName() + "/search"; + + ObjectNode requestBody = objectMapper.createObjectNode(); + ArrayNode vectorArray = objectMapper.createArrayNode(); + for (Double value : queryVector) { + vectorArray.add(value); + } + requestBody.set("vector", vectorArray); + requestBody.put("topK", topK); + requestBody.put("includeMetadata", true); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(requestBody.toString(), headers); + + ResponseEntity response = restTemplate.postForEntity(url, entity, JsonNode.class); + + if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { + List results = new ArrayList<>(); + JsonNode resultsNode = response.getBody().get("results"); + + if (resultsNode != null && resultsNode.isArray()) { + for (JsonNode resultNode : resultsNode) { + EndeeSearchResult result = new EndeeSearchResult(); + result.setId(resultNode.get("id").asText()); + result.setScore(resultNode.get("score").asDouble()); + + if (resultNode.has("metadata")) { + JsonNode metadata = resultNode.get("metadata"); + Map metadataMap = objectMapper.convertValue(metadata, Map.class); + result.setMetadata(metadataMap); + } + + results.add(result); + } + } + + log.debug("Found {} similar vectors", results.size()); + return results; + } else { + log.error("Search failed with status: {}", response.getStatusCode()); + return new ArrayList<>(); + } + } catch (Exception e) { + log.error("Error searching vectors: {}", e.getMessage()); + throw new BusinessException("Failed to search similar resumes: " + e.getMessage()); + } + } + + /** + * Deletes a vector from Endee + */ + public void deleteVector(String id) { + try { + String url = endeeConfig.getBaseUrl() + "/v1/indexes/" + endeeConfig.getIndexName() + "/vectors/" + id; + restTemplate.delete(url); + log.debug("Deleted vector with id: {}", id); + } catch (Exception e) { + log.error("Error deleting vector: {}", e.getMessage()); + } + } + + @lombok.Data + public static class EndeeSearchResult { + private String id; + private double score; + private Map metadata; + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/config/AppConfig.java b/backend/src/main/java/com/resumematcher/config/AppConfig.java new file mode 100644 index 0000000000..d9a7329cfb --- /dev/null +++ b/backend/src/main/java/com/resumematcher/config/AppConfig.java @@ -0,0 +1,38 @@ +package com.resumematcher.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class AppConfig { + + @Bean + public RestTemplate restTemplate() { + CloseableHttpClient httpClient = HttpClients.custom() + .setMaxConnTotal(100) + .setMaxConnPerRoute(20) + .build(); + + HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClient); + factory.setConnectTimeout(30000); + factory.setReadTimeout(30000); + + return new RestTemplate(factory); + } + + @Bean + public ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/config/EndeeConfig.java b/backend/src/main/java/com/resumematcher/config/EndeeConfig.java new file mode 100644 index 0000000000..bb88a85174 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/config/EndeeConfig.java @@ -0,0 +1,15 @@ +package com.resumematcher.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "endee") +public class EndeeConfig { + private String baseUrl; + private String indexName; + private int vectorDimension; + private String similarityMetric; +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/controller/ResumeController.java b/backend/src/main/java/com/resumematcher/controller/ResumeController.java new file mode 100644 index 0000000000..4cc48ce359 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/controller/ResumeController.java @@ -0,0 +1,111 @@ +package com.resumematcher.controller; + +import com.resumematcher.dto.request.JobDescriptionRequest; +import com.resumematcher.dto.response.MatchResult; +import com.resumematcher.dto.response.ResumeMetadata; +import com.resumematcher.service.ResumeMatcherService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Slf4j +@RestController +@RequestMapping("/api") +@RequiredArgsConstructor +@CrossOrigin(origins = "http://localhost:5173") +public class ResumeController { + + private final ResumeMatcherService resumeMatcherService; + + /** + * Upload a resume file + */ + @PostMapping("/resumes/upload") + public ResponseEntity uploadResume( + @RequestParam("file") MultipartFile file) { + + log.info("Received resume upload request: {}", file.getOriginalFilename()); + + // Validate file + if (file.isEmpty()) { + throw new IllegalArgumentException("File is empty"); + } + + // Validate file type + String filename = file.getOriginalFilename(); + if (filename != null && !isValidFileType(filename)) { + throw new IllegalArgumentException("Invalid file type. Only PDF, DOC, DOCX, and TXT files are allowed"); + } + + ResumeMetadata metadata = resumeMatcherService.uploadResume(file); + return ResponseEntity.status(HttpStatus.CREATED).body(metadata); + } + + /** + * Match resumes against job description + */ + @PostMapping("/match") + public ResponseEntity> matchResumes( + @Valid @RequestBody JobDescriptionRequest request) { + + log.info("Received match request for job description (length: {} chars)", + request.getJobDescription().length()); + + List matches = resumeMatcherService.matchResumes( + request.getJobDescription(), + request.getTopK() + ); + + return ResponseEntity.ok(matches); + } + + /** + * Get all uploaded resumes + */ + @GetMapping("/resumes") + public ResponseEntity> getAllResumes() { + log.info("Fetching all resumes"); + List resumes = resumeMatcherService.getAllResumes(); + return ResponseEntity.ok(resumes); + } + + /** + * Get resume by ID + */ + @GetMapping("/resumes/{resumeId}") + public ResponseEntity getResume(@PathVariable String resumeId) { + log.info("Fetching resume: {}", resumeId); + ResumeMetadata resume = resumeMatcherService.getResume(resumeId); + if (resume == null) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(resume); + } + + /** + * Health check endpoint + */ + @GetMapping("/health") + public ResponseEntity> health() { + Map status = Map.of( + "status", "UP", + "service", "AI Resume Matcher", + "version", "1.0.0" + ); + return ResponseEntity.ok(status); + } + + private boolean isValidFileType(String filename) { + String extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase(); + return extension.equals("pdf") || extension.equals("doc") || + extension.equals("docx") || extension.equals("txt"); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/dto/request/JobDescriptionRequest.java b/backend/src/main/java/com/resumematcher/dto/request/JobDescriptionRequest.java new file mode 100644 index 0000000000..f8b6f11c23 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/dto/request/JobDescriptionRequest.java @@ -0,0 +1,16 @@ +package com.resumematcher.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import lombok.Data; + +@Data +public class JobDescriptionRequest { + @NotBlank(message = "Job description cannot be empty") + private String jobDescription; + + @Min(value = 1, message = "TopK must be at least 1") + @Max(value = 100, message = "TopK cannot exceed 100") + private int topK = 10; +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/dto/request/ResumeUploadResponse.java b/backend/src/main/java/com/resumematcher/dto/request/ResumeUploadResponse.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/src/main/java/com/resumematcher/dto/response/MatchResult.java b/backend/src/main/java/com/resumematcher/dto/response/MatchResult.java new file mode 100644 index 0000000000..c05485e9fa --- /dev/null +++ b/backend/src/main/java/com/resumematcher/dto/response/MatchResult.java @@ -0,0 +1,16 @@ +package com.resumematcher.dto.response; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class MatchResult { + private String resumeId; + private String candidateName; + private String filename; + private String email; + private String[] skills; + private double similarityScore; + private String matchGrade; +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/dto/response/ResumeMetadata.java b/backend/src/main/java/com/resumematcher/dto/response/ResumeMetadata.java new file mode 100644 index 0000000000..d6298e6e63 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/dto/response/ResumeMetadata.java @@ -0,0 +1,17 @@ +package com.resumematcher.dto.response; + +import lombok.Builder; +import lombok.Data; +import java.time.LocalDateTime; + +@Data +@Builder +public class ResumeMetadata { + private String id; + private String filename; + private String candidateName; + private String email; + private String[] skills; + private LocalDateTime uploadedAt; + private Long fileSize; +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/exception/BusinessException.java b/backend/src/main/java/com/resumematcher/exception/BusinessException.java new file mode 100644 index 0000000000..ec1aff5d87 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/exception/BusinessException.java @@ -0,0 +1,11 @@ +package com.resumematcher.exception; + +public class BusinessException extends RuntimeException { + public BusinessException(String message) { + super(message); + } + + public BusinessException(String message, Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/exception/GlobalExceptionHandler.java b/backend/src/main/java/com/resumematcher/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000000..b1dd8ad9b0 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/exception/GlobalExceptionHandler.java @@ -0,0 +1,72 @@ +package com.resumematcher.exception; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.multipart.MaxUploadSizeExceededException; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(BusinessException.class) + public ResponseEntity handleBusinessException(BusinessException ex) { + log.error("Business exception: {}", ex.getMessage()); + ErrorResponse error = new ErrorResponse("BUSINESS_ERROR", ex.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + log.error("Illegal argument: {}", ex.getMessage()); + ErrorResponse error = new ErrorResponse("INVALID_ARGUMENT", ex.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + + ErrorResponse error = new ErrorResponse("VALIDATION_ERROR", "Validation failed", errors); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + public ResponseEntity handleMaxSizeException(MaxUploadSizeExceededException ex) { + ErrorResponse error = new ErrorResponse("FILE_TOO_LARGE", "File size exceeds maximum allowed size (10MB)"); + return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(error); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGenericException(Exception ex) { + log.error("Unexpected error: {}", ex.getMessage(), ex); + ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); + } + + @lombok.Data + @lombok.AllArgsConstructor + static class ErrorResponse { + private String code; + private String message; + private Map details; + + ErrorResponse(String code, String message) { + this.code = code; + this.message = message; + this.details = new HashMap<>(); + } + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/model/ResumeDocument.java b/backend/src/main/java/com/resumematcher/model/ResumeDocument.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/src/main/java/com/resumematcher/service/EmbeddingService.java b/backend/src/main/java/com/resumematcher/service/EmbeddingService.java new file mode 100644 index 0000000000..68428043c7 --- /dev/null +++ b/backend/src/main/java/com/resumematcher/service/EmbeddingService.java @@ -0,0 +1,124 @@ +package com.resumematcher.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.resumematcher.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class EmbeddingService { + + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; + + @Value("${openai.api-key}") + private String openAiApiKey; + + @Value("${openai.model}") + private String model; + + @Value("${app.embedding.batch-size}") + private int batchSize; + + private final ExecutorService executorService = Executors.newFixedThreadPool(5); + + /** + * Generates embeddings for a single text + */ + public List generateEmbedding(String text) { + if (text == null || text.trim().isEmpty()) { + throw new BusinessException("Text cannot be empty for embedding generation"); + } + + try { + List texts = List.of(text); + List> embeddings = generateEmbeddings(texts); + return embeddings.isEmpty() ? new ArrayList<>() : embeddings.get(0); + } catch (Exception e) { + log.error("Failed to generate embedding: {}", e.getMessage()); + throw new BusinessException("Failed to generate text embedding: " + e.getMessage()); + } + } + + /** + * Generates embeddings for multiple texts in batch + */ + public List> generateEmbeddings(List texts) { + if (texts == null || texts.isEmpty()) { + return new ArrayList<>(); + } + + List> allEmbeddings = new ArrayList<>(); + + // Process in batches + for (int i = 0; i < texts.size(); i += batchSize) { + int end = Math.min(i + batchSize, texts.size()); + List batch = texts.subList(i, end); + List> batchEmbeddings = generateEmbeddingsBatch(batch); + allEmbeddings.addAll(batchEmbeddings); + } + + return allEmbeddings; + } + + /** + * Generates embeddings asynchronously + */ + public CompletableFuture> generateEmbeddingAsync(String text) { + return CompletableFuture.supplyAsync(() -> generateEmbedding(text), executorService); + } + + private List> generateEmbeddingsBatch(List texts) { + try { + String url = "https://api.openai.com/v1/embeddings"; + + Map requestBody = new HashMap<>(); + requestBody.put("model", model); + requestBody.put("input", texts); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setBearerAuth(openAiApiKey); + + HttpEntity entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers); + + ResponseEntity response = restTemplate.postForEntity(url, entity, JsonNode.class); + + if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { + JsonNode dataNode = response.getBody().get("data"); + List> embeddings = new ArrayList<>(); + + for (JsonNode item : dataNode) { + JsonNode embeddingNode = item.get("embedding"); + List embedding = new ArrayList<>(); + for (JsonNode value : embeddingNode) { + embedding.add(value.asDouble()); + } + embeddings.add(embedding); + } + + return embeddings; + } else { + throw new BusinessException("OpenAI API returned error: " + response.getStatusCode()); + } + } catch (Exception e) { + log.error("Failed to generate embeddings batch: {}", e.getMessage()); + throw new BusinessException("Failed to generate embeddings: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/service/ResumeMatcherService.java b/backend/src/main/java/com/resumematcher/service/ResumeMatcherService.java new file mode 100644 index 0000000000..71b7036bba --- /dev/null +++ b/backend/src/main/java/com/resumematcher/service/ResumeMatcherService.java @@ -0,0 +1,156 @@ +package com.resumematcher.service; + +import com.resumematcher.client.EndeeClient; +import com.resumematcher.dto.response.MatchResult; +import com.resumematcher.dto.response.ResumeMetadata; +import com.resumematcher.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ResumeMatcherService { + + private final EndeeClient endeeClient; + private final EmbeddingService embeddingService; + private final ResumeParserService parserService; + + // In-memory cache for resume metadata (in production, use a real database) + private final Map resumeCache = new ConcurrentHashMap<>(); + + /** + * Uploads and processes a resume + */ + public ResumeMetadata uploadResume(MultipartFile file) { + try { + // Extract text from resume + String resumeText = parserService.extractText(file); + + // Extract metadata + String email = parserService.extractEmail(resumeText); + String name = parserService.extractName(resumeText); + String[] skills = parserService.extractSkills(resumeText); + + // Generate embedding + List embedding = embeddingService.generateEmbedding(resumeText); + + // Create unique ID + String resumeId = UUID.randomUUID().toString(); + + // Prepare metadata + ResumeMetadata metadata = ResumeMetadata.builder() + .id(resumeId) + .filename(file.getOriginalFilename()) + .candidateName(name != null ? name : "Unknown Candidate") + .email(email) + .skills(skills) + .uploadedAt(LocalDateTime.now()) + .fileSize(file.getSize()) + .build(); + + // Store in Endee + Map endeeMetadata = new HashMap<>(); + endeeMetadata.put("resumeId", resumeId); + endeeMetadata.put("candidateName", metadata.getCandidateName()); + endeeMetadata.put("filename", metadata.getFilename()); + endeeMetadata.put("email", metadata.getEmail()); + endeeMetadata.put("skills", String.join(",", metadata.getSkills())); + endeeMetadata.put("uploadedAt", metadata.getUploadedAt().toString()); + + endeeClient.insertVector(resumeId, embedding, endeeMetadata); + + // Cache metadata + resumeCache.put(resumeId, metadata); + + log.info("Successfully uploaded resume: {} (ID: {})", file.getOriginalFilename(), resumeId); + return metadata; + + } catch (Exception e) { + log.error("Failed to upload resume: {}", e.getMessage()); + throw new BusinessException("Failed to process resume upload: " + e.getMessage()); + } + } + + /** + * Matches resumes against job description + */ + public List matchResumes(String jobDescription, int topK) { + try { + // Generate embedding for job description + List jobEmbedding = embeddingService.generateEmbedding(jobDescription); + + // Search in Endee + List searchResults = endeeClient.searchSimilar(jobEmbedding, topK); + + // Convert to match results + List matches = new ArrayList<>(); + for (EndeeClient.EndeeSearchResult result : searchResults) { + String resumeId = result.getId(); + double similarityScore = result.getScore() * 100; // Convert to percentage + + // Get metadata from cache or from result + ResumeMetadata metadata = resumeCache.get(resumeId); + if (metadata == null && result.getMetadata() != null) { + metadata = ResumeMetadata.builder() + .id(resumeId) + .candidateName((String) result.getMetadata().get("candidateName")) + .filename((String) result.getMetadata().get("filename")) + .email((String) result.getMetadata().get("email")) + .skills(((String) result.getMetadata().get("skills")).split(",")) + .build(); + } + + MatchResult match = MatchResult.builder() + .resumeId(resumeId) + .candidateName(metadata != null ? metadata.getCandidateName() : "Unknown") + .filename(metadata != null ? metadata.getFilename() : "Unknown") + .email(metadata != null ? metadata.getEmail() : null) + .skills(metadata != null ? metadata.getSkills() : new String[0]) + .similarityScore(similarityScore) + .matchGrade(getMatchGrade(similarityScore)) + .build(); + + matches.add(match); + } + + // Sort by similarity score descending + matches.sort((a, b) -> Double.compare(b.getSimilarityScore(), a.getSimilarityScore())); + + log.info("Found {} matches for job description", matches.size()); + return matches; + + } catch (Exception e) { + log.error("Failed to match resumes: {}", e.getMessage()); + throw new BusinessException("Failed to match resumes: " + e.getMessage()); + } + } + + /** + * Gets all uploaded resumes + */ + public List getAllResumes() { + return new ArrayList<>(resumeCache.values()); + } + + /** + * Gets resume by ID + */ + public ResumeMetadata getResume(String resumeId) { + return resumeCache.get(resumeId); + } + + private String getMatchGrade(double score) { + if (score >= 90) return "Excellent Match"; + if (score >= 75) return "Strong Match"; + if (score >= 60) return "Good Match"; + if (score >= 40) return "Potential Match"; + return "Low Match"; + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/resumematcher/service/ResumeParserService.java b/backend/src/main/java/com/resumematcher/service/ResumeParserService.java new file mode 100644 index 0000000000..9616c8933b --- /dev/null +++ b/backend/src/main/java/com/resumematcher/service/ResumeParserService.java @@ -0,0 +1,143 @@ +package com.resumematcher.service; + +import lombok.extern.slf4j.Slf4j; +import org.apache.tika.exception.TikaException; +import org.apache.tika.metadata.Metadata; +import org.apache.tika.parser.ParseContext; +import org.apache.tika.parser.pdf.PDFParser; +import org.apache.tika.parser.txt.TXTParser; +import org.apache.tika.parser.microsoft.ooxml.WordprocessingMLParser; +import org.apache.tika.sax.BodyContentHandler; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.xml.sax.SAXException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Slf4j +@Service +public class ResumeParserService { + + /** + * Extracts text from uploaded resume file + */ + public String extractText(MultipartFile file) { + String filename = file.getOriginalFilename(); + if (filename == null) { + throw new IllegalArgumentException("File name is missing"); + } + + String extension = getFileExtension(filename); + + try (InputStream inputStream = file.getInputStream()) { + BodyContentHandler handler = new BodyContentHandler(-1); // No character limit + Metadata metadata = new Metadata(); + ParseContext context = new ParseContext(); + + switch (extension.toLowerCase()) { + case "pdf": + PDFParser parser = new PDFParser(); + parser.parse(inputStream, handler, metadata, context); + break; + case "doc": + case "docx": + WordprocessingMLParser wordParser = new WordprocessingMLParser(); + wordParser.parse(inputStream, handler, metadata, context); + break; + case "txt": + TXTParser txtParser = new TXTParser(); + txtParser.parse(inputStream, handler, metadata, context); + break; + default: + throw new IllegalArgumentException("Unsupported file format: " + extension); + } + + String extractedText = handler.toString(); + log.info("Successfully extracted text from {} ({} characters)", filename, extractedText.length()); + return cleanText(extractedText); + + } catch (IOException | SAXException | TikaException e) { + log.error("Failed to extract text from resume: {}", e.getMessage()); + throw new RuntimeException("Failed to parse resume file: " + e.getMessage()); + } + } + + /** + * Extracts email from resume text + */ + public String extractEmail(String text) { + // Common email regex pattern + Pattern emailPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"); + Matcher matcher = emailPattern.matcher(text); + + if (matcher.find()) { + return matcher.group(); + } + return null; + } + + /** + * Extracts candidate name (simplified - looks for common name patterns) + */ + public String extractName(String text) { + // Look for patterns like "Name: John Doe" or common name formats + Pattern namePattern = Pattern.compile("(?:Name|Candidate)[:\\s]+([A-Z][a-z]+\\s+[A-Z][a-z]+)", Pattern.MULTILINE); + Matcher matcher = namePattern.matcher(text); + + if (matcher.find()) { + return matcher.group(1); + } + + // Fallback: first line might contain name + String firstLine = text.split("\n")[0].trim(); + if (firstLine.length() < 50 && firstLine.matches(".*[A-Z][a-z]+\\s+[A-Z][a-z]+.*")) { + return firstLine; + } + + return null; + } + + /** + * Basic skill extraction (can be enhanced with NLP) + */ + public String[] extractSkills(String text) { + String[] commonSkills = { + "Java", "Python", "JavaScript", "React", "Spring Boot", "Node.js", + "AWS", "Docker", "Kubernetes", "SQL", "MongoDB", "PostgreSQL", + "Machine Learning", "AI", "TensorFlow", "PyTorch", "REST API", + "Microservices", "Git", "CI/CD", "Agile", "Scrum" + }; + + java.util.List foundSkills = new java.util.ArrayList<>(); + String lowerText = text.toLowerCase(); + + for (String skill : commonSkills) { + if (lowerText.contains(skill.toLowerCase())) { + foundSkills.add(skill); + } + } + + return foundSkills.toArray(new String[0]); + } + + private String getFileExtension(String filename) { + int lastDot = filename.lastIndexOf('.'); + if (lastDot == -1) { + return ""; + } + return filename.substring(lastDot + 1); + } + + private String cleanText(String text) { + // Remove excessive whitespace + text = text.replaceAll("\\s+", " "); + // Remove special characters but keep basic punctuation + text = text.replaceAll("[^\\w\\s@.-]", " "); + // Normalize whitespace + text = text.trim(); + return text; + } +} \ No newline at end of file diff --git a/backend/src/main/resources/application-dev.yml b/backend/src/main/resources/application-dev.yml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties new file mode 100644 index 0000000000..3ca17a4e34 --- /dev/null +++ b/backend/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=backend diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml new file mode 100644 index 0000000000..b8593fe93c --- /dev/null +++ b/backend/src/main/resources/application.yml @@ -0,0 +1,42 @@ +spring: + application: + name: resume-matcher + servlet: + multipart: + max-file-size: 10MB + max-request-size: 10MB + +server: + port: 8080 + error: + include-message: always + include-binding-errors: always + +# Endee Vector Database Configuration +endee: + base-url: ${ENDEE_BASE_URL:http://localhost:8090} + index-name: ${ENDEE_INDEX_NAME:resume_embeddings} + vector-dimension: ${ENDEE_VECTOR_DIMENSION:1536} + similarity-metric: ${ENDEE_SIMILARITY_METRIC:cosine} + +# OpenAI Configuration +openai: + api-key: ${OPENAI_API_KEY:your-api-key-here} + model: ${OPENAI_EMBEDDING_MODEL:text-embedding-ada-002} + max-retries: 3 + +# Application Settings +app: + embedding: + batch-size: 10 + cache-enabled: true + resume: + max-file-size: 10485760 # 10MB + allowed-formats: pdf,doc,docx,txt + +logging: + level: + com.resumematcher: DEBUG + org.springframework.web: INFO + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n" \ No newline at end of file diff --git a/backend/src/test/java/com/resumematcher/BackendApplicationTests.java b/backend/src/test/java/com/resumematcher/BackendApplicationTests.java new file mode 100644 index 0000000000..27bec77304 --- /dev/null +++ b/backend/src/test/java/com/resumematcher/BackendApplicationTests.java @@ -0,0 +1,13 @@ +package com.resumematcher; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BackendApplicationTests { + + @Test + void contextLoads() { + } + +}