Skip to content

Commit 04bce3d

Browse files
committed
Refactor: Remove all comments from source code
1 parent 667bc54 commit 04bce3d

12 files changed

Lines changed: 17 additions & 118 deletions

File tree

demo-web/src/main/java/com/jpyrust/JPyRustBridge.java

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ public synchronized static void initialize(String workDirectory, String sourceSc
7979
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
8080
}
8181

82-
// Copy plugins directory
8382
Path pluginsSrc = Paths.get(sourceScriptDir, "plugins");
8483
Path pluginsDst = Paths.get(workDir, "plugins");
8584
if (Files.exists(pluginsSrc)) {
@@ -184,7 +183,6 @@ public String processNlp(String text) {
184183
}
185184

186185
public String processRegression(String jsonPoints) {
187-
// Input: "[[1, 2], [2, 4]]"
188186
String requestId = UUID.randomUUID().toString();
189187
byte[] inputBytes = jsonPoints.getBytes(StandardCharsets.UTF_8);
190188
ByteBuffer buffer = ByteBuffer.allocateDirect(inputBytes.length);
@@ -220,14 +218,8 @@ public byte[] processImage(ByteBuffer data, int length, int width, int height, i
220218
return processImage(workDir, data, length, width, height, channels);
221219
}
222220

223-
/**
224-
* Generic method to send any task to the Python daemon.
225-
* Useful for Status checks and Plugins.
226-
*/
227221
public String sendTask(String taskType, String metadata) {
228222
String requestId = UUID.randomUUID().toString();
229-
// Send dummy input (1 byte) as some tasks might expect it,
230-
// though STATUS/PLUGINS might primarily use metadata.
231223
byte[] dummyInput = "{}".getBytes(StandardCharsets.UTF_8);
232224

233225
ByteBuffer buffer = ByteBuffer.allocateDirect(dummyInput.length);

demo-web/src/main/java/com/jpyrust/demo/AIController.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ public class AIController {
1414

1515
@GetMapping("/chat")
1616
public Map<String, Object> chat(@RequestParam String message, @RequestParam int id) {
17-
// ... legacy code ...
1817
return Map.of("status", "success", "python_response", "Text AI is under maintenance.");
1918
}
2019

@@ -26,7 +25,6 @@ public Map<String, Object> analyzeSentiment(@RequestBody String text) {
2625

2726
@PostMapping("/regression")
2827
public Map<String, Object> performRegression(@RequestBody String jsonPoints) {
29-
// jsonPoints example: "[[1, 2], [2, 4], [3, 6]]"
3028
String result = bridge.processRegression(jsonPoints);
3129
return Map.of("result", result);
3230
}

demo-web/src/main/java/com/jpyrust/demo/AIImageController.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ public void init() {
4747

4848
@PostMapping(value = "/process-image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.IMAGE_JPEG_VALUE)
4949
public ResponseEntity<byte[]> processImage(@RequestParam("file") MultipartFile file) {
50-
// ... (keep existing YOLO logic) ...
5150
return processImageInternal(file, "YOLO");
5251
}
5352

@@ -60,10 +59,11 @@ private ResponseEntity<byte[]> processImageInternal(MultipartFile file, String m
6059
String requestId = UUID.randomUUID().toString();
6160
try {
6261
BufferedImage inputImage = ImageIO.read(file.getInputStream());
63-
if (inputImage == null) return ResponseEntity.badRequest().build();
62+
if (inputImage == null)
63+
return ResponseEntity.badRequest().build();
6464

65-
// Convert to BGR (OpenCV standard)
66-
BufferedImage bgrImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
65+
BufferedImage bgrImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(),
66+
BufferedImage.TYPE_3BYTE_BGR);
6767
bgrImage.getGraphics().drawImage(inputImage, 0, 0, null);
6868

6969
byte[] pixelData = ((DataBufferByte) bgrImage.getRaster().getDataBuffer()).getData();
@@ -74,14 +74,16 @@ private ResponseEntity<byte[]> processImageInternal(MultipartFile file, String m
7474

7575
JPyRustBridge bridge = new JPyRustBridge();
7676
byte[] resultData;
77-
77+
7878
if ("EDGE".equals(mode)) {
7979
resultData = bridge.processEdgeDetection(pixelData, bgrImage.getWidth(), bgrImage.getHeight(), 3);
8080
} else {
81-
resultData = bridge.processImage(workDir, directBuffer, pixelData.length, bgrImage.getWidth(), bgrImage.getHeight(), 3, requestId);
81+
resultData = bridge.processImage(workDir, directBuffer, pixelData.length, bgrImage.getWidth(),
82+
bgrImage.getHeight(), 3, requestId);
8283
}
8384

84-
if (resultData == null) return ResponseEntity.internalServerError().build();
85+
if (resultData == null)
86+
return ResponseEntity.internalServerError().build();
8587
return ResponseEntity.ok(resultData);
8688

8789
} catch (Exception e) {

demo-web/src/main/java/com/jpyrust/demo/DemoApplication.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ public static void main(String[] args) {
1616
@PostConstruct
1717
public void init() {
1818
System.out.println("Scheduling JPyRust initialization (non-blocking)...");
19-
// Run Python initialization in background thread so Tomcat can start
20-
// immediately
2119
CompletableFuture.runAsync(() -> {
2220
try {
2321
System.out.println("[Async] Starting JPyRust initialization...");

demo-web/src/main/java/com/jpyrust/demo/PluginController.java

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,8 @@ public class PluginController {
1313
@PostMapping("/{taskType}")
1414
public Map<String, Object> executePlugin(@PathVariable String taskType, @RequestBody Map<String, Object> payload) {
1515
try {
16-
// Convert payload values to simple metadata string if possible
17-
// For this sample, we assume payload has "args" list or we just send values
18-
// Example input: {"args": [1, 2]}
19-
2016
String metadata = "NONE";
2117
if (payload.containsKey("args")) {
22-
// simple space-joined args
2318
Object args = payload.get("args");
2419
if (args instanceof Iterable) {
2520
StringBuilder sb = new StringBuilder();

demo-web/src/main/java/com/jpyrust/demo/StatusController.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,13 @@ public Map<String, Object> getStatus() {
1919
try {
2020
String jsonResult = bridge.sendTask("STATUS", "NONE");
2121

22-
// If result starts with "ERROR", return error map
2322
if (jsonResult.startsWith("ERROR")) {
2423
return Map.of("status", "DOWN", "error", jsonResult);
2524
}
2625

27-
// Parse JSON string from Python
2826
try {
2927
return mapper.readValue(jsonResult, Map.class);
3028
} catch (Exception e) {
31-
// If not valid JSON (e.g. raw string), return as raw
3229
return Map.of("status", "UNKNOWN", "raw", jsonResult);
3330
}
3431

java-api/src/main/java/com/jpyrust/JPyRustBridge.java

Lines changed: 4 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public class JPyRustBridge {
2626
System.out.println("[JPyRustBridge] Native library loaded successfully via NativeLoader");
2727
} catch (Throwable e) {
2828
System.out.println("DEBUG: Failed to load native library!");
29-
e.printStackTrace(System.out); // Print to stdout to ensure visibility
29+
e.printStackTrace(System.out);
3030
throw new RuntimeException("Fatal: Native library load failed", e);
3131
}
3232
}
@@ -35,14 +35,12 @@ public class JPyRustBridge {
3535
private static Path pythonExe;
3636

3737
public synchronized static void initialize() {
38-
// Default to user home directory
3938
String userHome = System.getProperty("user.home");
4039
Path defaultWorkDir = Paths.get(userHome, ".jpyrust");
4140
initialize(defaultWorkDir.toString(), null);
4241
}
4342

4443
public synchronized static void initialize(String workDirectory, String ignoredSourceScript) {
45-
// Generate a unique session key for Shared Memory
4644
String memoryKey = "JPyRust_" + java.util.UUID.randomUUID().toString();
4745
System.out.println("[JPyRust] Generated Session Key (Default): " + memoryKey);
4846
initialize(workDirectory, ignoredSourceScript, memoryKey);
@@ -53,11 +51,7 @@ private static void setupEmbeddedPython(Path targetDir) throws Exception {
5351
Path markerFile = pythonDistDir.resolve(".installed");
5452

5553
if (!Files.exists(markerFile)) {
56-
// Robustness: Check if it's actually installed but marker is missing (e.g.
57-
// crash during last boot)
58-
// We check for a key package like 'ultralytics' or 'torch'
59-
Path sitePackages = pythonDistDir.resolve("Lib/site-packages"); // Standard for embedded layout usually, or
60-
// just Lib/site-packages
54+
Path sitePackages = pythonDistDir.resolve("Lib/site-packages");
6155
if (Files.exists(pythonDistDir.resolve("python.exe")) &&
6256
(Files.exists(sitePackages.resolve("ultralytics"))
6357
|| Files.exists(sitePackages.resolve("torch")))) {
@@ -69,48 +63,25 @@ private static void setupEmbeddedPython(Path targetDir) throws Exception {
6963
System.out.println("[Init] Extracting user embedded python to: " + pythonDistDir);
7064
NativeLoader.extractZip("/python_dist.zip", pythonDistDir);
7165

72-
// --- [Patched] Auto-fix for pip support ---
7366
Path pthFile = pythonDistDir.resolve("python311._pth");
7467
if (Files.exists(pthFile)) {
7568
System.out.println("[Init] Patching python311._pth to enable 'import site'...");
7669
Files.write(pthFile, "python311.zip\n.\nimport site".getBytes());
7770
}
7871

79-
// --- [Patched] Manual Dependency Installation ---
8072
System.out.println("[Init] Installing dependencies via pip...");
8173
Path pyExe = pythonDistDir.resolve("python.exe");
8274
Path requirements = targetDir.resolve("requirements.txt");
8375

84-
// Generate requirements.txt if missing (fallback)
85-
if (!Files.exists(requirements)) {
86-
// Copy from classpath or creating a minimal one if needed,
87-
// but for now we assume it exists or the user provided it.
88-
// Actually, let's copy the one from project root if we can or skip.
89-
// Better: JPyRustBridge is usually run where requirements.txt is available or
90-
// provided.
91-
}
92-
93-
// We need to assume requirements.txt is in the targetDir or provided.
94-
// The previous logic didn't explicitly move it, but our manual steps did.
95-
// Let's ensure requirements.txt is present.
96-
// Since we can't easily access the project root from here dynamically in all
97-
// cases,
98-
// we will rely on the fact that if it exists, we install.
99-
10076
if (Files.exists(requirements)) {
101-
Path wheelsDir = pythonDistDir.resolve("../wheels"); // Based on our manual copy structure
102-
// Adjust logic: The wheels were in build/python_staging/wheels.
103-
// We need to be careful. If wheels are not there, try online install or skip?
104-
// For now, let's just try to run pip.
77+
Path wheelsDir = pythonDistDir.resolve("../wheels");
10578

10679
ProcessBuilder pipPb = new ProcessBuilder(
10780
pyExe.toString(),
10881
"-m", "pip", "install",
10982
"--no-index",
110-
"--find-links=wheels", // Relative to working dir? No, let's use absolute if possible or
111-
// relative
83+
"--find-links=wheels",
11284
"-r", requirements.toString());
113-
// We assume wheels are in targetDir/wheels
11485
pipPb.directory(targetDir.toFile());
11586
pipPb.redirectErrorStream(true);
11687
Process pipProc = pipPb.start();
@@ -124,7 +95,6 @@ private static void setupEmbeddedPython(Path targetDir) throws Exception {
12495
pipProc.waitFor();
12596
}
12697

127-
// Create marker
12898
Files.createFile(markerFile);
12999

130100
} else {
@@ -135,40 +105,28 @@ private static void setupEmbeddedPython(Path targetDir) throws Exception {
135105
pythonExe = pythonDistDir.resolve("python.exe");
136106
}
137107

138-
/**
139-
* [Native Callback] Rust 프로세스에서 발생하는 로그를 Java로 전달받는 메서드입니다.
140-
* 주의: Native 코드(Rust)에서 이 메서드 시그니처를 참조하므로 절대 삭제하거나 변경하면 안 됩니다.
141-
*
142-
* @param level 로그 레벨 (INFO, ERROR, DEBUG 등)
143-
* @param msg 로그 메시지 내용
144-
*/
145108
public static void log(String level, String msg) {
146-
// 기본적으로 System.out으로 출력 (추후 SLF4J 등으로 확장 가능)
147109
System.out.println("[JPyRust-Native] [" + level + "] " + msg);
148110
}
149111

150112
private static native void initNative(String workDir, String sourceScriptDir, String modelPath, float confidence,
151113
String memoryKey);
152114

153-
// 4-param initialize overload for AIImageController compatibility
154115
public static void initialize(String workDirectory, String sourceScript, String modelPath, float confidence) {
155116
System.out.println("[JPyRust] Init with model: " + modelPath + ", confidence: " + confidence);
156117

157-
// Generate a unique session key for Shared Memory
158118
String memoryKey = "JPyRust_" + java.util.UUID.randomUUID().toString();
159119
System.out.println("[JPyRust] Generated Session Key: " + memoryKey);
160120

161121
initialize(workDirectory, sourceScript, memoryKey);
162122
}
163123

164-
// Internal initialize with key
165124
private synchronized static void initialize(String workDirectory, String ignoredSourceScript, String memoryKey) {
166125
if (initialized) {
167126
return;
168127
}
169128

170129
workDir = workDirectory;
171-
// sourceScriptDir is no longer needed as we use the embedded one
172130

173131
System.out.println("=== JPyRust IPC Initialization ===");
174132
System.out.println("[Init] Work Directory: " + workDir);
@@ -179,10 +137,8 @@ private synchronized static void initialize(String workDirectory, String ignored
179137
Files.createDirectories(workPath);
180138
}
181139

182-
// 1. Setup Embedded Python
183140
setupEmbeddedPython(workPath);
184141

185-
// 2. Initialize Native
186142
initNative(workDir, workDir, "yolov8n.pt", 0.5f, memoryKey);
187143

188144
System.out.println("=== Initialization Complete ===");
@@ -194,18 +150,15 @@ private synchronized static void initialize(String workDirectory, String ignored
194150
}
195151
}
196152

197-
// Native executeTask declaration matching Rust signature
198153
private native byte[] executeTask(String workDir, String taskType, String requestId, String metadata,
199154
ByteBuffer data, int length);
200155

201156
public byte[] processImage(String workDirectory, ByteBuffer data, int length, int width, int height, int channels) {
202157
String requestId = java.util.UUID.randomUUID().toString();
203-
// Construct metadata directly as simple string "width height channels"
204158
String metadata = width + " " + height + " " + channels;
205159
return executeTask(workDirectory, "YOLO", requestId, metadata, data, length);
206160
}
207161

208-
// 7-param processImage overload for AIImageController compatibility
209162
public byte[] processImage(String workDirectory, ByteBuffer data, int length, int width, int height, int channels,
210163
String requestId) {
211164
System.out.println("[JPyRust] Processing request: " + requestId);
@@ -217,7 +170,6 @@ public byte[] processImage(ByteBuffer data, int length, int width, int height, i
217170
return processImage(workDir, data, length, width, height, channels);
218171
}
219172

220-
// Edge detection implementation
221173
public byte[] processEdgeDetection(byte[] imageData, int width, int height, int channels) {
222174
System.out.println("[JPyRust] Edge detection called (Native)");
223175
try {
@@ -236,7 +188,6 @@ public byte[] processEdgeDetection(byte[] imageData, int width, int height, int
236188
}
237189
}
238190

239-
// NLP processing implementation
240191
public String processNlp(String text) {
241192
System.out.println("[JPyRust] NLP processing: " + text);
242193
try {
@@ -246,7 +197,6 @@ public String processNlp(String text) {
246197
directBuffer.flip();
247198

248199
String requestId = java.util.UUID.randomUUID().toString();
249-
// Metadata empty for NLP, or specialized if needed
250200
String metadata = "TEXT";
251201

252202
byte[] resultBytes = executeTask(workDir, "NLP_TEXTBLOB", requestId, metadata, directBuffer,
@@ -262,7 +212,6 @@ public String processNlp(String text) {
262212
}
263213
}
264214

265-
// Regression processing implementation
266215
public String processRegression(String jsonPoints) {
267216
System.out.println("[JPyRust] Regression processing: " + jsonPoints);
268217
try {
@@ -287,13 +236,6 @@ public String processRegression(String jsonPoints) {
287236
}
288237
}
289238

290-
// Legacy runPythonProcess declaration removed/replaced by executeTask usage
291-
/*
292-
* private native byte[] runPythonProcess(String workDir, ByteBuffer data, int
293-
* length, int width, int height,
294-
* int channels, String requestId);
295-
*/
296-
297239
public String runPythonRaw(ByteBuffer data, int length, int width, int height, int channels) {
298240
String inputFilePath = workDir + "/input_image.dat";
299241
String outputFilePath = workDir + "/output_image.dat";

java-api/src/main/java/com/jpyrust/NativeLoader.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ public static void load(String libName) {
2525

2626
String filename = libName + extension;
2727

28-
// Try multiple resource paths for Spring Boot compatibility
2928
String[] resourcePaths = {
3029
"/natives/" + filename,
3130
"natives/" + filename,
@@ -36,7 +35,6 @@ public static void load(String libName) {
3635
InputStream is = null;
3736
String foundPath = null;
3837

39-
// Try class classloader first
4038
for (String path : resourcePaths) {
4139
System.err.println("[NativeLoader] Checking path: " + path);
4240
is = NativeLoader.class.getResourceAsStream(path);
@@ -47,7 +45,6 @@ public static void load(String libName) {
4745
}
4846
}
4947

50-
// Fallback to thread context classloader
5148
if (is == null) {
5249
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
5350
if (contextCL != null) {

java-api/src/test/java/com/jpyrust/TestLoader.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ public class TestLoader {
77
public void testLoading() {
88
System.out.println("Testing JPyRustBridge Loading...");
99
try {
10-
// Force class loading to trigger static block
1110
Class.forName("com.jpyrust.JPyRustBridge");
1211
System.out.println("JPyRustBridge loaded successfully!");
1312

0 commit comments

Comments
 (0)