Skip to content

Commit

Permalink
refactored code.
Browse files Browse the repository at this point in the history
  • Loading branch information
dashluu committed Dec 6, 2023
1 parent a7d8fe8 commit b92071e
Showing 38 changed files with 187 additions and 293 deletions.
2 changes: 1 addition & 1 deletion app/src/main/java/code/App.java
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@ private void drawUI(Stage primaryStage) throws IOException, URISyntaxException {
view.setScene(login);
Controller controller = new Controller(view, model);

ServerConnection connection = new ServerConnection("localhost", 8100);
ServerConnection connection = new ServerConnection(AppConfig.SERVER_HOST, AppConfig.SERVER_PORT);

if (connection.isOnline()) {
// System.out.println("Server is online");
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package code.client.Model;
package code;

import javax.sound.sampled.AudioFileFormat;

@@ -25,12 +25,11 @@ public class AppConfig {
public static final String SERVER_HOST = "localhost";
public static final int SERVER_PORT = 8100;
public static final String SERVER_URL = "http://" + SERVER_HOST + ":" + SERVER_PORT;
public static final String RECIPE_PATH = "/recipe";
public static final String RECIPE_PATH = "/recipes";
public static final String ACCOUNT_PATH = "/accounts";
public static final String CHATGPT_PATH = "/chatgpt";
public static final String DALLE_PATH = "/dalle";
public static final String WHISPER_PATH = "/whisper";
// sharing
public static final String SHARE_PATH = "/recipes/";
public static final String SHARE_LINK = "http://localhost:8100/recipes/";
public static final String SHARE_PATH = "/share";
}
1 change: 0 additions & 1 deletion app/src/main/java/code/Server.java
Original file line number Diff line number Diff line change
@@ -2,7 +2,6 @@

import java.io.IOException;

import code.client.Model.AppConfig;
import code.server.AppServer;
import code.server.BaseServer;
import code.server.mocking.MockServer;
40 changes: 23 additions & 17 deletions app/src/main/java/code/client/Controllers/Controller.java
Original file line number Diff line number Diff line change
@@ -23,6 +23,7 @@
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.util.Duration;
import code.AppConfig;
import code.client.Model.*;
import code.client.View.AppAlert;
import code.client.View.AppFrameMic;
@@ -39,7 +40,7 @@ public class Controller {
private Account account;
private Model model;
private View view;
private Format format = new Format();
private final ResponseToRecipe responseToRecipe = new ResponseToRecipe();
private IRecipeDb recipeDb;
private RecipeCSVWriter recipeWriter;
private RecipeCSVReader recipeReader;
@@ -261,12 +262,12 @@ private void handleDetailedViewFromNewRecipeButton(ActionEvent event) {
try {
Thread thread = new Thread(() -> {
String responseText = model.performChatGPTRequest("GET", mealType, ingredients);
Recipe chatGPTrecipe = format.mapResponseToRecipe(mealType, responseText);
chatGPTrecipe.setAccountId(account.getId());
chatGPTrecipe.setImage(model.performDallERequest("GET", chatGPTrecipe.getTitle()));

Recipe recipe = responseToRecipe.getRecipe(responseText);
recipe.setMealTag(mealType);
recipe.setAccountId(account.getId());
recipe.setImage(model.performDallERequest("GET", recipe.getTitle()));
// Changes UI to Detailed Recipe Screen
view.goToDetailedView(chatGPTrecipe, false);
view.goToDetailedView(recipe, false);
view.getDetailedView().getRecipeDetailsUI().setEditable(false);
handleDetailedViewListeners();
});
@@ -349,11 +350,18 @@ private void deleteGivenRecipe(Recipe recipe) throws IOException {
private void handleShareButton(ActionEvent event) {
Recipe shownRecipe = this.view.getDetailedView().getDisplayedRecipe();
String id = shownRecipe.getId();
Hyperlink textArea = new Hyperlink(AppConfig.SHARE_LINK + account.getUsername() + "/" + id);
String shareLink = new StringBuilder(AppConfig.SERVER_URL)
.append(AppConfig.SHARE_PATH)
.append("/")
.append(account.getUsername())
.append("/")
.append(id)
.toString();
Hyperlink textArea = new Hyperlink(shareLink);
textArea.setOnAction(action -> {
try {
java.awt.Desktop.getDesktop() // Format: localhost:8100/recipes/username/recipeID
.browse(new URL(AppConfig.SHARE_LINK + account.getUsername() + "/" + id).toURI());
// Format: localhost:8100/recipes/username/recipeID
java.awt.Desktop.getDesktop().browse(new URL(shareLink).toURI());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
@@ -412,15 +420,13 @@ private void handleRefreshButton(ActionEvent event) throws URISyntaxException, I
view.goToLoading();
try {
Thread thread = new Thread(() -> {
String responseText = model.performChatGPTRequest("GET", mealType,
ingredients);
Recipe chatGPTrecipe = format.mapResponseToRecipe(mealType, responseText);
chatGPTrecipe.setAccountId(account.getId());
chatGPTrecipe.setImage(model.performDallERequest("GET",
chatGPTrecipe.getTitle()));

String responseText = model.performChatGPTRequest("GET", mealType, ingredients);
Recipe recipe = responseToRecipe.getRecipe(responseText);
recipe.setMealTag(mealType);
recipe.setAccountId(account.getId());
recipe.setImage(model.performDallERequest("GET", recipe.getTitle()));
// Changes UI to Detailed Recipe Screen
view.goToDetailedView(chatGPTrecipe, false);
view.goToDetailedView(recipe, false);
view.getDetailedView().getRecipeDetailsUI().setEditable(false);
handleDetailedViewListeners();
});
2 changes: 2 additions & 0 deletions app/src/main/java/code/client/Model/AppAudioRecorder.java
Original file line number Diff line number Diff line change
@@ -3,6 +3,8 @@
import java.io.*;
import javax.sound.sampled.*;

import code.AppConfig;

public class AppAudioRecorder extends BaseAudioRecorder {
private AudioFormat audioFormat;
private TargetDataLine targetDataLine;
3 changes: 3 additions & 0 deletions app/src/main/java/code/client/Model/Model.java
Original file line number Diff line number Diff line change
@@ -13,6 +13,9 @@
import java.net.URLConnection;
import java.net.URI;
import java.nio.file.*;

import code.AppConfig;

import java.net.URLEncoder;

public class Model {
Original file line number Diff line number Diff line change
@@ -1,23 +1,12 @@
package code.client.Controllers;
package code.client.Model;

import code.server.Recipe;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class Format {
public String buildPrompt(String mealType, String ingredients) {
StringBuilder prompt = new StringBuilder();
prompt.append("I am a student on a budget with a busy schedule and I need to quickly cook a ")
.append(mealType)
.append(". ")
.append(ingredients)
.append(" Make a recipe using only these ingredients plus condiments. ")
.append("Please give me a recipe in the following format with no comments after the instructions. Title: Ingredients: Instructions:");
return prompt.toString();
}

public Recipe mapResponseToRecipe(String mealType, String responseText) {
public class ResponseToRecipe {
public Recipe getRecipe(String responseText) {
// Split the tokens into lines
String[] tokenArr = responseText.split("\n");
List<String> tokenList = new ArrayList<>(Arrays.asList(tokenArr));
@@ -28,33 +17,32 @@ public Recipe mapResponseToRecipe(String mealType, String responseText) {
if (tokenList.get(i).isBlank()) {
tokenList.remove(i);
} else {
tokenList.set(i, tokenList.get(i).trim());
++i;
}
}

// Create a new recipe with a title
// Parse recipe's title and create a new recipe
String title = tokenList.get(0);
if (title.contains("Title:")) {
title = title.replaceAll("Title:", "");
}
Recipe recipe = new Recipe(title.trim(), mealType);
Recipe recipe = new Recipe(title, null);
// Parse recipe's ingredients
String ingredient;
boolean parse = false;

for (i = 0; !tokenList.get(i).contains("Instructions"); ++i) {
ingredient = tokenList.get(i).trim();
ingredient = tokenList.get(i);
if (ingredient.contains("Ingredients")) {
parse = true;
} else if (parse) {
ingredient = removeDashFromIngredient(tokenList.get(i).trim());
ingredient = removeDashFromIngredient(tokenList.get(i));
recipe.addIngredient(ingredient);
}
}

// Parse recipe's instructions
String instruction;
for (i += 1; i < tokenList.size(); ++i) {
instruction = removeNumberFromInstruction(tokenList.get(i).trim());
instruction = removeNumberFromInstruction(tokenList.get(i));
recipe.addInstruction(instruction);
}

2 changes: 1 addition & 1 deletion app/src/main/java/code/client/View/Ingredients.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package code.client.View;

import code.client.Model.*;
import code.AppConfig;
import java.io.File;
import javafx.scene.control.*;
import javafx.scene.image.Image;
2 changes: 1 addition & 1 deletion app/src/main/java/code/client/View/LoadingUI.java
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@
import javafx.geometry.Insets;
import java.io.File;

import code.client.Model.AppConfig;
import code.AppConfig;

public class LoadingUI extends VBox {
private final Label loadingLabel;
2 changes: 1 addition & 1 deletion app/src/main/java/code/client/View/MealType.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package code.client.View;

import code.client.Model.*;
import code.AppConfig;
import java.io.File;

import javafx.scene.control.*;
2 changes: 1 addition & 1 deletion app/src/main/java/code/client/View/OfflineUI.java
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@
import javafx.geometry.Insets;
import java.io.File;

import code.client.Model.AppConfig;
import code.AppConfig;

public class OfflineUI extends VBox {
private final Label offlineLabel;
1 change: 0 additions & 1 deletion app/src/main/java/code/client/View/RecipeListUI.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package code.client.View;

import javafx.geometry.Pos;
import javafx.scene.layout.*;
import java.io.*;
import java.util.List;
14 changes: 9 additions & 5 deletions app/src/main/java/code/server/AppServer.java
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
import com.mongodb.client.MongoDatabase;
import com.sun.net.httpserver.*;

import code.client.Model.AppConfig;
import code.AppConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
@@ -17,13 +17,13 @@
public class AppServer extends BaseServer {
private IRecipeDb recipeDb;
private AccountMongoDB accountMongoDB;

private final static int NUM_THREADS = 10;
private HttpServer httpServer;
private MongoClient mongoClient;

public AppServer(String hostName, int port) {
super(hostName, port);
MongoClient mongoClient = MongoClients.create(AppConfig.MONGODB_CONN);
mongoClient = MongoClients.create(AppConfig.MONGODB_CONN);
MongoDatabase mongoDb = mongoClient.getDatabase(AppConfig.MONGO_DB);
MongoCollection<Document> userCollection = mongoDb.getCollection(AppConfig.MONGO_USER_COLLECTION);
MongoCollection<Document> recipeCollection = mongoDb.getCollection(AppConfig.MONGO_RECIPE_COLLECTION);
@@ -44,7 +44,8 @@ public void start() throws IOException {
httpServer.createContext(AppConfig.RECIPE_PATH, new RecipeRequestHandler(recipeDb));
httpServer.createContext(AppConfig.ACCOUNT_PATH, new AccountRequestHandler(accountMongoDB));
httpServer.createContext(AppConfig.SHARE_PATH, new ShareRequestHandler(accountMongoDB, recipeDb));
httpServer.createContext(AppConfig.CHATGPT_PATH, new ChatGPTRequestHandler());
TextToRecipe textToRecipe = new ChatGPTService();
httpServer.createContext(AppConfig.CHATGPT_PATH, new ChatGPTRequestHandler(textToRecipe));
httpServer.createContext(AppConfig.DALLE_PATH, new DallERequestHandler());
httpServer.createContext(AppConfig.WHISPER_PATH, new WhisperRequestHandler());
// set the executor
@@ -57,7 +58,10 @@ public void start() throws IOException {
@Override
public void stop() {
if (httpServer != null) {
httpServer.stop(0); // Stop the server gracefully
// Close the mongo db connection
mongoClient.close();
// Stop the server gracefully
httpServer.stop(0);
System.out.println("Server stopped");
}
}
61 changes: 7 additions & 54 deletions app/src/main/java/code/server/ChatGPTRequestHandler.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
package code.server;

import code.client.Model.AppConfig;
import code.client.Controllers.Format;
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;

public class ChatGPTRequestHandler extends TextToRecipe implements HttpHandler {
private static final String API_ENDPOINT = "https://api.openai.com/v1/completions";
private static final String MODEL = "text-davinci-003";
private static final int MAX_TOKENS = 500;
private static final double TEMPERATURE = 1.;
public class ChatGPTRequestHandler implements HttpHandler {
private final TextToRecipe textToRecipe;

public ChatGPTRequestHandler(TextToRecipe textToRecipe) {
this.textToRecipe = textToRecipe;
}

@Override
public void handle(HttpExchange httpExchange) throws IOException {
@@ -30,7 +24,7 @@ public void handle(HttpExchange httpExchange) throws IOException {
String[] typeIngredients = value.split("::");
String mealType = typeIngredients[0];
String ingredients = typeIngredients[1];
response = getResponse(mealType, ingredients);
response = textToRecipe.getResponse(mealType, ingredients);
} catch (IndexOutOfBoundsException e) {
response = "Provide valid meal type or ingredients";
e.printStackTrace();
@@ -45,45 +39,4 @@ public void handle(HttpExchange httpExchange) throws IOException {
outStream.write(response.getBytes());
outStream.close();
}

private String getResponse(String mealType, String ingredients)
throws IOException, InterruptedException, URISyntaxException {
// Set request parameters
Format format = new Format();
String prompt = format.buildPrompt(mealType, ingredients);

// Create a request body which you will pass into request object
JSONObject requestBody = new JSONObject();
requestBody.put("model", MODEL);
requestBody.put("prompt", prompt);
requestBody.put("max_tokens", MAX_TOKENS);
requestBody.put("temperature", TEMPERATURE);

// Create the HTTP Client
HttpClient client = HttpClient.newHttpClient();

// Create the request object
HttpRequest request = HttpRequest
.newBuilder()
.uri(URI.create(API_ENDPOINT))
.header("Content-Type", "application/json")
.header("Authorization", String.format("Bearer %s", AppConfig.API_KEY))
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.build();

HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString());

// Process the response
String responseBody = response.body();
JSONObject responseJson = new JSONObject(responseBody);
JSONArray choices = responseJson.getJSONArray("choices");
String responseText = choices.getJSONObject(0).getString("text");
return responseText;
}

@Override
public void setSampleRecipe(String recipe) {
}
}
Loading

0 comments on commit b92071e

Please sign in to comment.