Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add create recipe view and link screens #48

Merged
merged 3 commits into from
Nov 7, 2023
Merged
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: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ replay_pid*
# End of https://www.toptal.com/developers/gitignore/api/java
*.wav
*.properties
!.vscode/launch.json
.vscode/launch.json
!gradle/wrapper/gradle-wrapper.jar
!gradle/wrapper/gradle-wrapper.properties
Binary file modified .gradle/8.0.2/executionHistory/executionHistory.bin
Binary file not shown.
Binary file modified .gradle/8.0.2/executionHistory/executionHistory.lock
Binary file not shown.
Binary file modified .gradle/8.0.2/fileHashes/fileHashes.bin
Binary file not shown.
Binary file modified .gradle/8.0.2/fileHashes/fileHashes.lock
Binary file not shown.
Binary file modified .gradle/8.0.2/fileHashes/resourceHashesCache.bin
Binary file not shown.
Binary file modified .gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
Binary file added .gradle/buildOutputCleanup/outputFiles.bin
Binary file not shown.
Binary file modified .gradle/file-system.probe
Binary file not shown.
9 changes: 5 additions & 4 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
"type": "java",
"name": "Current File",
"request": "launch",
"mainClass": "${file}"
"mainClass": "${file}",
"vmArgs": "--module-path 'C:/Users/allen/Desktop/CSE110/CSE110-MiniProject/javafx-sdk-21/lib' --add-modules javafx.controls,javafx.base,javafx.fxml,javafx.graphics,javafx.media,javafx.web --add-opens=javafx.graphics/javafx.scene=ALL-UNNAMED --add-exports javafx.base/com.sun.javafx.event=ALL-UNNAMED"
},
{
"type": "java",
"name": "App",
"name": "Main",
"request": "launch",
"mainClass": "View.java",
//"vmArgs": "--module-path 'C:\\Users\\Christophian S\\Desktop\\javafx-sdk-21\\lib' --add-modules javafx.controls,javafx.fxml"
"mainClass": "Main.java",
//"vmArgs": "--module-path '/Users/kesler_anderson/cse-110-project-team-39/lib' --add-modules javafx.controls,javafx.fxml"
},
{
"type": "java",
Expand Down
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"java.project.referencedLibraries": [
"lib/**/*.jar"
],
"java.configuration.updateBuildConfiguration": "interactive"
"java.configuration.updateBuildConfiguration": "interactive",
"java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx2G -Xms100m -Xlog:disable"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified app/build/tmp/compileJava/previous-compilation-data.bin
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified app/build/tmp/compileTestJava/previous-compilation-data.bin
Binary file not shown.
4 changes: 3 additions & 1 deletion app/src/main/java/code/client/Model/ITextToRecipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import java.net.URISyntaxException;

public interface ITextToRecipe {
String buildPrompt(String input);

String getChatGPTResponse(String input) throws IOException, InterruptedException, URISyntaxException;

Recipe mapResponseToRecipe(String responseText);
}

8 changes: 8 additions & 0 deletions app/src/main/java/code/client/Model/IVoiceToText.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package code.client.Model;

import java.io.IOException;
import java.net.URISyntaxException;

public interface IVoiceToText {
String processAudio() throws IOException, URISyntaxException;
}
6 changes: 3 additions & 3 deletions app/src/main/java/code/client/Model/TextToRecipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ public Recipe mapResponseToRecipe(String responseText) {
return recipe;
}

private String buildPrompt(String input) {
public String buildPrompt(String input) {
StringBuilder prompt = new StringBuilder();
prompt.append("I am a student on a budget with a busy schedule and I need to quickly cook a meal.")
prompt.append("I am a student on a budget with a busy schedule and I need to quickly cook a meal. ")
.append(input)
.append("Make a recipe using only these ingredients plus condiments.")
.append("Make a recipe using only these ingredients plus condiments. ")
.append("Remember to first include a title, then a list of ingredients, and then a list of instructions.");
return prompt.toString();
}
Expand Down
146 changes: 146 additions & 0 deletions app/src/main/java/code/client/Model/VoiceToText.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package code.client.Model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONException;

public class VoiceToText implements IVoiceToText {
private static final String API_ENDPOINT = "https://api.openai.com/v1/audio/transcriptions";
private static final String TOKEN = "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";
private static final String MODEL = "whisper-1";

// https://stackoverflow.com/questions/25334139/how-to-mock-a-url-connection
@Override
public String processAudio() throws IOException, URISyntaxException {
// Create file object from file path
File file = new File("recording.wav");
HttpURLConnection connection = sendHttpRequest(file);

// Get response code
int responseCode = connection.getResponseCode();
String response;

// Check response code and handle response accordingly
if (responseCode == HttpURLConnection.HTTP_OK) {
response = handleSuccessResponse(connection);
} else {
response = handleErrorResponse(connection);
}

// Disconnect connection
connection.disconnect();

return response;
}

private HttpURLConnection sendHttpRequest(File file) throws IOException, URISyntaxException {
URL url = new URI(API_ENDPOINT).toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

// Set up request headers
String boundary = "Boundary-" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("Authorization", "Bearer " + TOKEN);

// Set up output stream to write request body
OutputStream outputStream = connection.getOutputStream();

// Write model parameter to request body
writeParameterToOutputStream(outputStream, "model", MODEL, boundary);

// Write file parameter to request body
writeFileToOutputStream(outputStream, file, boundary);

// Write closing boundary to request body
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());

// Flush and close output stream
outputStream.flush();
outputStream.close();

return connection;
}

// Helper method to write a parameter to the output stream in multipart form
// data format
private static void writeParameterToOutputStream(
OutputStream outputStream,
String parameterName,
String parameterValue,
String boundary) throws IOException {
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(
("Content-Disposition: form-data; name=\"" + parameterName + "\"\r\n\r\n").getBytes());
outputStream.write((parameterValue + "\r\n").getBytes());
}

// Helper method to write a file to the output stream in multipart form data
// format
private static void writeFileToOutputStream(
OutputStream outputStream,
File file,
String boundary) throws IOException {
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(
("Content-Disposition: form-data; name=\"file\"; filename=\"" +
file.getName() +
"\"\r\n").getBytes());
outputStream.write(("Content-Type: audio/mpeg\r\n\r\n").getBytes());

FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
}

// Helper method to handle a successful response
private static String handleSuccessResponse(HttpURLConnection connection)
throws IOException, JSONException {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

JSONObject responseJson = new JSONObject(response.toString());

String generatedText = responseJson.getString("text");
System.out.println("Transcription Result: " + generatedText);
return generatedText;

}

// Helper method to handle an error response
private static String handleErrorResponse(HttpURLConnection connection)
throws IOException, JSONException {
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(connection.getErrorStream()));
String errorLine;
StringBuilder errorResponse = new StringBuilder();
while ((errorLine = errorReader.readLine()) != null) {
errorResponse.append(errorLine);
}
errorReader.close();
String errorResult = errorResponse.toString();
System.out.println("Error Result: " + errorResult);
return errorResult;
}

}
57 changes: 57 additions & 0 deletions app/src/main/java/code/client/View/DetailsAppFrame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package code.client.View;

import java.util.ArrayList;

import code.client.Model.Recipe;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class DetailsAppFrame {
private ArrayList<Scene> scenes;
private Stage primaryStage;

public Scene getScene() {
VBox root = new VBox();
root.setSpacing(20);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: #F0F8FF;");

VBox setupContainer = new VBox();
setupContainer.setSpacing(10);

// Hardcoded value for now, recipe value for it should be changing
Recipe temp = new Recipe("1", "Fried Chicken and Egg Fried Rice");
temp.addIngredient("2 chicken breasts, diced");
temp.addIngredient("2 large eggs");
temp.addIngredient("2 cups cooked rice");
temp.addIngredient("2 tablespoons vegetable oil");
temp.addInstruction("1. Heat the vegetable oil in a large pan over medium-high heat.");

RecipeDetailsUI details = new RecipeDetailsUI(temp);

TextField title = details.getTitleField();
title.setAlignment(Pos.CENTER);
title.setStyle("-fx-font-weight: bold; -fx-font-size: 20;");
root.getChildren().add(title);

setupContainer.getChildren().add(details);
root.getChildren().add(setupContainer);

return new Scene(root, 700, 600);
}

/**
* This method provides the UI holder with the different scenes that can be
* switched between.
*
* @param primaryStage - Main stage that has the window
* @param scenes - list of different scenes to switch between.
*/
public void setScenes(Stage primaryStage, ArrayList<Scene> scenes) {
this.scenes = scenes;
this.primaryStage = primaryStage;
}
}
46 changes: 35 additions & 11 deletions app/src/main/java/code/client/View/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@

package code.client.View;

import javafx.scene.layout.StackPane;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
Expand Down Expand Up @@ -124,7 +122,6 @@ public void toggleSelected() {
}
}


class RecipeList extends VBox {

RecipeList() {
Expand Down Expand Up @@ -168,8 +165,7 @@ public void loadRecipes() {
this.getChildren().add(recipe);
}
reader.close();
}
catch (IOException e) {
} catch (IOException e) {
System.out.println("Recipes could not be loaded.");
}
this.updateRecipeIndices();
Expand All @@ -185,8 +181,7 @@ public void saveRecipes() {
writer.newLine();
}
writer.close();
}
catch (IOException e) {
} catch (IOException e) {
System.out.println("Recipes could not be saved.");
}
}
Expand Down Expand Up @@ -283,6 +278,8 @@ class AppFrame extends BorderPane {
private Footer footer;
private RecipeList recipeList;
private Button addButton, deleteButton, loadButton, saveButton, selectButton, sortButton, uploadButton;
private ArrayList<Scene> scenes;
private Stage primaryStage;

AppFrame() {
header = new Header();
Expand All @@ -306,6 +303,18 @@ class AppFrame extends BorderPane {
addListeners();
}

/**
* This method provides the UI holder with the different scenes that can be
* switched between.
*
* @param primaryStage - Main stage that has the window
* @param scenes - list of different scenes to switch between.
*/
public void setScenes(Stage primaryStage, ArrayList<Scene> scenes) {
this.scenes = scenes;
this.primaryStage = primaryStage;
}

public void addListeners() {
addButton.setOnAction(e -> {
Recipe recipe = new Recipe();
Expand All @@ -322,6 +331,7 @@ public void addListeners() {
});

recipeList.updateRecipeIndices();
primaryStage.setScene(scenes.get(1));
});

deleteButton.setOnAction(e -> {
Expand All @@ -347,9 +357,26 @@ public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
AppFrame root = new AppFrame();
Scene home = new Scene(root, 700, 600);

NewRecipeUI audioCapture = new NewRecipeUI();
Scene speaking = audioCapture.getScene();

DetailsAppFrame chatGPTed = new DetailsAppFrame();
Scene details = chatGPTed.getScene();

ArrayList<Scene> scenes = new ArrayList<Scene>();
scenes.add(home);
scenes.add(speaking);
scenes.add(details);

// Can create observer, subject interface here
root.setScenes(primaryStage, scenes);
audioCapture.setScenes(primaryStage, scenes);
chatGPTed.setScenes(primaryStage, scenes);

primaryStage.setTitle("Recipe Management App");
primaryStage.setScene(new Scene(root, 700, 600));
primaryStage.setScene(home);
primaryStage.setResizable(false);
primaryStage.show();
}
Expand All @@ -358,6 +385,3 @@ public static void main(String[] args) {
launch(args);
}
}



Loading