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

Write a doc example on multi-language Mill projects #4476

Merged
merged 16 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from 13 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
3 changes: 3 additions & 0 deletions docs/modules/ROOT/pages/large/multi-file-builds.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ include::partial$example/large/multi/11-helper-files.adoc[]

include::partial$example/large/multi/12-helper-files-sc.adoc[]

== Multi Language Project

include::partial$example/large/multi/14-multi-language.adoc[]
monyedavid marked this conversation as resolved.
Show resolved Hide resolved

50 changes: 50 additions & 0 deletions example/large/multi/14-multi-language/build.mill
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package build
import mill._, javascriptlib._, pythonlib._, javalib.{TestModule => JTestModule, _}

object client extends ReactScriptsModule

object `sentiment-analysis` extends PythonModule {
def mainScript = Task.Source { millSourcePath / "src" / "foo.py" }

def pythonDeps = Seq("Jinja2==3.1.4", "textblob==0.19.0")
}

object server extends JavaModule {
def ivyDeps = Agg(
ivy"org.springframework.boot:spring-boot-starter-web:2.5.6",
ivy"org.springframework.boot:spring-boot-starter-actuator:2.5.6"
)

/** Bundle client & sentiment-analysis as resource */
def resources = Task.Sources {
os.copy(client.bundle().path, Task.dest / "static")
os.makeDir.all(Task.dest / "analysis")
os.copy(`sentiment-analysis`.bundle().path, Task.dest / "analysis" / "analysis.pex")
super.resources() ++ Seq(PathRef(Task.dest))
}

object test extends JavaTests with JTestModule.Junit5 {
monyedavid marked this conversation as resolved.
Show resolved Hide resolved
def ivyDeps = super.ivyDeps() ++ Agg(
ivy"org.springframework.boot:spring-boot-starter-test:2.5.6"
)
}
}

// This example demonstrates a simple multi-langauge project,
// running a `spring boot webserver` serving a `react client` and interacting with a `python binary`
// through the web-server api.

/** Usage

> mill server.test
...com.example.ServerTest#shouldReturnStaticPage() finished...
...com.example.ServerTest#shouldReturnPositiveAnalysis() finished...
...com.example.ServerTest#shouldReturnNegativeAnalysis() finished...

> mill server.runBackground

> curl http://localhost:8086
...<title>Sentiment Analysis Tool</title>...

monyedavid marked this conversation as resolved.
Show resolved Hide resolved
> mill clean server.runBackground
*/
43 changes: 43 additions & 0 deletions example/large/multi/14-multi-language/client/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Sentiment Analysis Tool</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
90 changes: 90 additions & 0 deletions example/large/multi/14-multi-language/client/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}

body {
background: #f4f4f4;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}

.app-container {
background: #fff;
border-radius: 12px;
padding: 40px;
width: 400px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
}

h1 {
margin-bottom: 20px;
font-size: 1.8rem;
color: #333;
}

.analysis-form {
display: flex;
flex-direction: column;
gap: 10px;
}

textarea {
width: 100%;
height: 120px;
padding: 10px;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 8px;
resize: none;
outline: none;
}

textarea:focus {
border-color: #007bff;
}

button {
padding: 10px;
background: #007bff;
color: #fff;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
}

button:hover {
background: #0056b3;
}

button:disabled {
background: #b0c4de;
cursor: not-allowed;
}

.result-container {
margin-top: 20px;
padding: 15px;
border-radius: 8px;
color: #fff;
font-weight: bold;
}

/* Sentiment-based styles */
.result-container.positive {
background-color: #28a745; /* Green for positive */
}

.result-container.negative {
background-color: #dc3545; /* Red for negative */
}

.result-container.neutral {
background-color: #007bff; /* Blue for neutral */
}
76 changes: 76 additions & 0 deletions example/large/multi/14-multi-language/client/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React, {useState} from 'react';
import 'src/App.css';

const App = () => {
const [inputText, setInputText] = useState('');
const [result, setResult] = useState('');
const [loading, setLoading] = useState(false);
const [sentiment, setSentiment] = useState('neutral');

const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setResult('');
setSentiment('neutral');

try {
const response = await fetch('http://localhost:8086/api/analysis', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: inputText,
});

if (response.ok) {
const responseData = await response.text();
setResult(responseData);

// Determine sentiment from the response
const polarityMatch = responseData.match(/polarity: ([+-]?[0-9]*\.?[0-9]+)/);
if (polarityMatch) {
const polarity = parseFloat(polarityMatch[1]);

if (polarity > 0) {
setSentiment('positive');
} else if (polarity < 0) {
setSentiment('negative');
} else {
setSentiment('neutral');
}
}
} else {
setResult('Error occurred during analysis.');
}
} catch (error) {
setResult('Network error: Could not connect to the server.');
} finally {
setLoading(false);
}
};

return (
<div className="app-container">
<h1>Text Analysis Tool</h1>
<form onSubmit={handleSubmit} className="analysis-form">
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Enter your text here..."
required
/>
<button type="submit" disabled={loading}>
{loading ? 'Analyzing...' : 'Analyze'}
</button>
</form>
{result && (
<div className={`result-container ${sentiment}`}>
<h2>Analysis Result:</h2>
<p>{result}</p>
</div>
)}
</div>
);
};

export default App;
12 changes: 12 additions & 0 deletions example/large/multi/14-multi-language/client/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app/App';

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import sys
from textblob import TextBlob

def analyze_sentiment(text):
blob = TextBlob(text)
polarity = blob.sentiment.polarity

if polarity > 0:
return f"Positive sentiment (polarity: {polarity})"
elif polarity < 0:
return f"Negative sentiment (polarity: {polarity})"
else:
return "Neutral sentiment (polarity: 0)"

if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python sentiment.py <text>")
sys.exit(1)

input_text = " ".join(sys.argv[1:])
result = analyze_sentiment(input_text)
print(result)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
server.port=8086
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.example;

import java.io.*;
import java.nio.file.Files;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class AnalysisController {

@PostMapping("/analysis")
public ResponseEntity<String> analyzeText(@RequestBody String text) {
try {
// Read the binary from resources
byte[] analysisBinary = readResourceAsBytes("analysis/analysis.pex");
if (analysisBinary == null) {
return ResponseEntity.status(500).body("Analysis binary not found");
}

// Write binary to a temporary file
File tempBinary = File.createTempFile("analysis", ".pex");
tempBinary.deleteOnExit(); // Auto-delete on app exit
Files.write(tempBinary.toPath(), analysisBinary);
tempBinary.setExecutable(true); // Ensure it's executable

// Run the Python binary with the input text
ProcessBuilder processBuilder = new ProcessBuilder(tempBinary.getAbsolutePath(), text);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();

// Read output from the Python process
StringBuilder output = new StringBuilder();
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}

// Check the exit code
int exitCode = process.waitFor();
if (exitCode != 0) {
return ResponseEntity.status(500).body("Error running analysis");
}

return ResponseEntity.ok(output.toString());

} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(500).body("Server error");
}
}

private static byte[] readResourceAsBytes(String resourceName) {
try (InputStream resourceStream =
AnalysisController.class.getClassLoader().getResourceAsStream(resourceName)) {
if (resourceStream == null) {
return null;
}
return resourceStream.readAllBytes();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Server {

public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}
Loading
Loading