Skip to content

Commit

Permalink
✨ Ml Model applied
Browse files Browse the repository at this point in the history
  • Loading branch information
NimsHub committed Oct 11, 2023
1 parent e905f11 commit 7181cc6
Show file tree
Hide file tree
Showing 27 changed files with 5,492 additions and 4 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/on-premise-deployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ jobs:
conf:
- 'docker-compose.yml'
- 'nginx/**'
ml:
- 'src/main/resources/scripts/**'
- 'src/main/resources/models/**'
- 'src/main/resources/scalars/**'
- name: Set up JDK 17
if: steps.changes.outputs.src == 'true'
Expand Down Expand Up @@ -58,6 +62,17 @@ jobs:
source: "docker-compose.yml,nginx/**"
target: ${{ secrets.SERVER_TARGET_LOCATION }}

- name: Copy ML Files
if: steps.changes.outputs.ml == 'true'
uses: appleboy/scp-action@v0.1.4
with:
host: ${{ secrets.SERVER_IP }}
username: ${{ secrets.SERVER_USERNAME }}
port: ${{ secrets.SERVER_PORT }}
key: ${{ secrets.SERVER_KEY }}
source: "src/main/resources/scripts/**,src/main/resources/scalars/**,src/main/resources/models/**"
target: ${{ secrets.SERVER_TARGET_LOCATION }}

- name: Pull and Redeploy the Application
if: steps.changes.outputs.src == 'true' || steps.changes.outputs.conf == 'true'
uses: appleboy/ssh-action@v0.1.10
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ services:
MAIL_PORT: ${MAIL_PORT}
MAIL_USERNAME: ${MAIL_USERNAME}
MAIL_PASSWORD: ${MAIL_PASSWORD}
ML_ENABLED: ${ML_ENABLED}
SCRIPTS_LOCATION: ${SCRIPTS_LOCATION}
DATA_LOCATION: ${DATA_LOCATION}
PROCESS_DIRECTORY: ${PROCESS_DIRECTORY}
networks:
- network

Expand Down
11 changes: 11 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow-core-platform</artifactId>
<version>0.5.0</version>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.nimshub.biobeacon.activities;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
* @Author Nirmala : 11:October:2023
* This controller implements all end points required to handle the requests of Activity
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/activities")
public class ActivityController {
private final ActivityService activityService;
@GetMapping("/activity/{id}")
public ResponseEntity<ActivityTimeResponse> getActivityTimes(@PathVariable UUID id){
return new ResponseEntity<>(activityService.getActivityTime(id), HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.nimshub.biobeacon.activities;

import com.nimshub.biobeacon.exceptions.SessionNotFoundException;
import com.nimshub.biobeacon.session.Session;
import com.nimshub.biobeacon.session.SessionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
* @Author Nirmala : 11:October:2023
* This service implements all methods required to handle the business logic of Activity
*/
@Service
@RequiredArgsConstructor
public class ActivityService {
private final ActivityTimeRepository activityTimeRepository;
private final SessionRepository sessionRepository;

public ActivityTimeResponse getActivityTime(UUID id) {
Session session = sessionRepository.findBySessionId(id)
.orElseThrow(() -> new SessionNotFoundException("Session Not Found"));

ActivityTime activityTime = activityTimeRepository.findBySession(session)
.orElseThrow(() -> new SessionNotFoundException("Session Not Found"));


return ActivityTimeResponse.builder()
.cycling(activityTime.getCycling())
.pushUp(activityTime.getPushUp())
.squat(activityTime.getSquat())
.tableTennis(activityTime.getTableTennis())
.running(activityTime.getRunning())
.walking(activityTime.getWalking())
.build();
}
}
36 changes: 36 additions & 0 deletions src/main/java/com/nimshub/biobeacon/activities/ActivityTime.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.nimshub.biobeacon.activities;

import com.nimshub.biobeacon.session.Session;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* @Author Nirmala : 11:October:2023
* This entity class defines the all the properties of ActivityTime
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class ActivityTime {
@Id
@SequenceGenerator(name = "ActivityTime_SEQ", sequenceName = "ActivityTime_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ActivityTime_SEQ")
private Integer id;
@OneToOne(cascade = CascadeType.DETACH,fetch = FetchType.EAGER)
@JoinColumn(name = "session", referencedColumnName = "id", foreignKey =
@ForeignKey(name = "fk_session_id")
)
private Session session;
private Integer cycling;
private Integer pushUp;
private Integer running;
private Integer squat;
private Integer tableTennis;
private Integer walking;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.nimshub.biobeacon.activities;

import com.nimshub.biobeacon.activities.ActivityTime;
import com.nimshub.biobeacon.session.Session;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
* @Author Nirmala : 11:October:2023
* This interface implements all methods required database transactions for ActivityTime using Jpa
*/

@Repository
public interface ActivityTimeRepository extends JpaRepository<ActivityTime,Integer> {
Optional<ActivityTime> findBySession(Session session);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.nimshub.biobeacon.activities;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class ActivityTimeResponse {
private Integer cycling;
private Integer pushUp;
private Integer running;
private Integer squat;
private Integer tableTennis;
private Integer walking;
}
5 changes: 4 additions & 1 deletion src/main/java/com/nimshub/biobeacon/constants/Constants.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package com.nimshub.biobeacon.constants;

public class Constants {
public class Constants {
// creating a private constructor to hide the public implicit one
private Constants() {
throw new IllegalStateException("Constants class");
}
public static final String NO_DATA = "*";
public static final String BASH = "bash";
public static final String SCRIPT = "source env/bin/activate && python3 ";
public static final String COMMAND = "-c";
public static final String COMMA = ",";
public static final Integer CHUNK_SIZE = 4;
}
114 changes: 114 additions & 0 deletions src/main/java/com/nimshub/biobeacon/ml/ModelService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.nimshub.biobeacon.ml;

import com.nimshub.biobeacon.activities.ActivityTime;
import com.nimshub.biobeacon.activities.ActivityTimeRepository;
import com.nimshub.biobeacon.exceptions.SessionNotFoundException;
import com.nimshub.biobeacon.session.Session;
import com.nimshub.biobeacon.session.SessionRepository;
import com.nimshub.biobeacon.utils.Converters;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.nimshub.biobeacon.constants.Constants.*;


/**
* @Author Nirmala : 30:August:2023
* This service implements all methods required to handle the business logic of ModelService
*/
@Service
@RequiredArgsConstructor
public class ModelService {
private final ActivityTimeRepository activityTimeRepository;
private final SessionRepository sessionRepository;
Logger logger = LoggerFactory.getLogger(ModelService.class);

@Value("${ml.process-directory}")
String processDirectory;

public String doAnalyze() {

String outputCsv = "";
try {
String scriptName = "scripts/model5.py";

String[] command = {BASH, COMMAND, SCRIPT + scriptName};

ProcessBuilder processBuilder = new ProcessBuilder(command);

processBuilder.directory(new File(processDirectory));

Process process = processBuilder.start();

logger.info("Executing command : {}", Arrays.toString(command));

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
List<String> outputLines = new ArrayList<>();
while ((line = reader.readLine()) != null) {
outputLines.add(line);
}
String output = outputLines.subList(3, outputLines.size()).toString()
.replace(", ", "")
.replace("[", "")
.replace("]", "");

outputCsv = output.replace(" ", ",");
int exitCode = process.waitFor();

if (exitCode == 0) {
logger.info("Script executed successfully. Predicted output : {}", output);
} else {
logger.error("Script execution failed with exit code : {}", output);
}

} catch (IOException | InterruptedException e) {
e.printStackTrace();

}
return outputCsv;
}

public void predictActivities(Integer id) {
Converters converter = new Converters();
String output = doAnalyze();

List<String> predictionList = converter.getStringList(output);

int cyclingTime = Collections.frequency(predictionList, "0")*10;
int pushUpTime = Collections.frequency(predictionList, "1")*10;
int runTime = Collections.frequency(predictionList, "2")*10;
int squatTime = Collections.frequency(predictionList, "3")*10;
int tableTennisTime = Collections.frequency(predictionList, "4")*10;
int walkTime = Collections.frequency(predictionList, "5")*10;

Session session = sessionRepository.findById(id)
.orElseThrow(()-> new SessionNotFoundException("Session not found"));

ActivityTime activityTime = ActivityTime.builder()
.session(session)
.cycling(cyclingTime)
.pushUp(pushUpTime)
.running(runTime)
.squat(squatTime)
.tableTennis(tableTennisTime)
.walking(walkTime)
.build();

activityTimeRepository.save(activityTime);
}


}
Loading

0 comments on commit 7181cc6

Please sign in to comment.