MurderousCoder commited on
Commit
2ef91ed
·
verified ·
1 Parent(s): 9712770
Files changed (4) hide show
  1. Dockerfile +30 -0
  2. README.md +70 -7
  3. requirements.txt +3 -0
  4. server.py +168 -0
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM openfoam/openfoam11-paraview510
2
+
3
+ # Switch to root user for installations
4
+ USER root
5
+
6
+ # Install Python and dependencies
7
+ RUN apt-get update && apt-get install -y \
8
+ python3 \
9
+ python3-pip \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # Set working directory
13
+ WORKDIR /app
14
+
15
+ # Copy Python requirements
16
+ COPY requirements.txt .
17
+ RUN pip3 install --no-cache-dir -r requirements.txt
18
+
19
+ # Copy application code
20
+ COPY server.py .
21
+
22
+ # Create OpenFOAM case directory
23
+ RUN mkdir -p /app/cases
24
+
25
+ # Hugging Face Spaces uses port 7860 by default
26
+ EXPOSE 7860
27
+
28
+ # Source OpenFOAM environment and start server
29
+ # Note: Hugging Face sets PORT env variable to 7860
30
+ CMD ["/bin/bash", "-c", "source /opt/openfoam11/etc/bashrc && python3 server.py"]
README.md CHANGED
@@ -1,11 +1,74 @@
1
  ---
2
- title: Openfoam Blockmesh Api
3
- emoji: 💻
4
- colorFrom: indigo
5
- colorTo: pink
6
  sdk: docker
7
- pinned: false
8
- license: cc-by-4.0
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OpenFOAM blockMesh API
3
+ emoji: 🔧
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
+ app_port: 7860
 
8
  ---
9
 
10
+ # OpenFOAM blockMesh API
11
+
12
+ This Space provides an API endpoint for running OpenFOAM's blockMesh utility.
13
+
14
+ ## 🚀 API Endpoints
15
+
16
+ ### Health Check
17
+ ```bash
18
+ GET /health
19
+ ```
20
+
21
+ ### Run blockMesh
22
+ ```bash
23
+ POST /blockmesh
24
+ Content-Type: application/json
25
+
26
+ {
27
+ "blockMeshDict": "your blockMeshDict content here"
28
+ }
29
+ ```
30
+
31
+ ## 📝 Usage Example
32
+
33
+ ```bash
34
+ curl -X POST https://YOUR-USERNAME-openfoam-blockmesh-api.hf.space/blockmesh \
35
+ -H "Content-Type: application/json" \
36
+ -d '{
37
+ "blockMeshDict": "/*--------------------------------*- C++ -*----------------------------------*\\\nFoamFile\n{\n version 2.0;\n format ascii;\n class dictionary;\n object blockMeshDict;\n}\n..."
38
+ }'
39
+ ```
40
+
41
+ ## 🔧 Response Format
42
+
43
+ ```json
44
+ {
45
+ "output": "blockMesh output...",
46
+ "success": true,
47
+ "mesh_info": {
48
+ "checkMesh": "mesh statistics..."
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## ⚙️ Technical Details
54
+
55
+ - **OpenFOAM Version**: 11
56
+ - **Python**: 3.x
57
+ - **Framework**: Flask with CORS enabled
58
+ - **Port**: 7860 (Hugging Face default)
59
+
60
+ ## 📦 What's Included
61
+
62
+ - Full OpenFOAM 11 installation
63
+ - ParaView 5.10 (for potential future visualization)
64
+ - Python Flask API
65
+ - Automatic mesh validation with checkMesh
66
+
67
+ ## ⏱️ Execution
68
+
69
+ - Maximum execution time: 30 seconds per blockMesh run
70
+ - Cases are automatically cleaned up after execution
71
+
72
+ ## 🔒 Security
73
+
74
+ This is a public API. Do not use for sensitive or production workloads.
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Flask==3.0.0
2
+ flask-cors==4.0.0
3
+ gunicorn==21.2.0
server.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from flask_cors import CORS
3
+ import subprocess
4
+ import os
5
+ import shutil
6
+ import uuid
7
+
8
+ app = Flask(__name__)
9
+ CORS(app) # Enable CORS for all routes
10
+
11
+ # Base directory for OpenFOAM cases
12
+ CASES_DIR = "/app/cases"
13
+ os.makedirs(CASES_DIR, exist_ok=True)
14
+
15
+ @app.route('/', methods=['GET'])
16
+ def home():
17
+ """Home endpoint with API information"""
18
+ return jsonify({
19
+ "name": "OpenFOAM blockMesh API",
20
+ "version": "1.0",
21
+ "endpoints": {
22
+ "/health": "GET - Health check",
23
+ "/blockmesh": "POST - Run blockMesh with provided blockMeshDict"
24
+ },
25
+ "status": "operational"
26
+ })
27
+
28
+ @app.route('/health', methods=['GET'])
29
+ def health():
30
+ """Health check endpoint"""
31
+ return jsonify({
32
+ "status": "healthy",
33
+ "openfoam": "ready",
34
+ "version": "OpenFOAM-11"
35
+ })
36
+
37
+ @app.route('/blockmesh', methods=['POST'])
38
+ def run_blockmesh():
39
+ """Run blockMesh with provided blockMeshDict"""
40
+ try:
41
+ data = request.get_json()
42
+
43
+ if not data:
44
+ return jsonify({
45
+ "error": "No JSON data provided",
46
+ "success": False
47
+ }), 400
48
+
49
+ block_mesh_dict = data.get('blockMeshDict')
50
+
51
+ if not block_mesh_dict:
52
+ return jsonify({
53
+ "error": "blockMeshDict is required",
54
+ "success": False
55
+ }), 400
56
+
57
+ # Create unique case directory
58
+ case_id = str(uuid.uuid4())
59
+ case_dir = os.path.join(CASES_DIR, case_id)
60
+ system_dir = os.path.join(case_dir, "system")
61
+ constant_dir = os.path.join(case_dir, "constant")
62
+
63
+ # Create directory structure
64
+ os.makedirs(system_dir, exist_ok=True)
65
+ os.makedirs(constant_dir, exist_ok=True)
66
+
67
+ # Write blockMeshDict
68
+ block_mesh_path = os.path.join(system_dir, "blockMeshDict")
69
+ with open(block_mesh_path, 'w') as f:
70
+ f.write(block_mesh_dict)
71
+
72
+ # Create minimal controlDict (required by OpenFOAM)
73
+ control_dict_path = os.path.join(system_dir, "controlDict")
74
+ minimal_control_dict = """/*--------------------------------*- C++ -*----------------------------------*\\
75
+ FoamFile
76
+ {
77
+ version 2.0;
78
+ format ascii;
79
+ class dictionary;
80
+ object controlDict;
81
+ }
82
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
83
+
84
+ application simpleFoam;
85
+ startFrom startTime;
86
+ startTime 0;
87
+ stopAt endTime;
88
+ endTime 1;
89
+ deltaT 1;
90
+ writeControl timeStep;
91
+ writeInterval 1;
92
+ purgeWrite 0;
93
+ writeFormat ascii;
94
+ writePrecision 6;
95
+ writeCompression off;
96
+ timeFormat general;
97
+ timePrecision 6;
98
+ runTimeModifiable true;
99
+
100
+ // ************************************************************************* //
101
+ """
102
+ with open(control_dict_path, 'w') as f:
103
+ f.write(minimal_control_dict)
104
+
105
+ # Run blockMesh
106
+ result = subprocess.run(
107
+ ['blockMesh', '-case', case_dir],
108
+ capture_output=True,
109
+ text=True,
110
+ timeout=30
111
+ )
112
+
113
+ output = result.stdout + result.stderr
114
+ success = result.returncode == 0
115
+
116
+ # Get mesh statistics if successful
117
+ mesh_info = {}
118
+ if success:
119
+ try:
120
+ check_mesh_result = subprocess.run(
121
+ ['checkMesh', '-case', case_dir],
122
+ capture_output=True,
123
+ text=True,
124
+ timeout=10
125
+ )
126
+ mesh_info = {
127
+ "checkMesh": check_mesh_result.stdout
128
+ }
129
+ except Exception as e:
130
+ mesh_info = {
131
+ "checkMesh_error": str(e)
132
+ }
133
+
134
+ # Cleanup case directory
135
+ try:
136
+ shutil.rmtree(case_dir)
137
+ except Exception as e:
138
+ print(f"Warning: Failed to cleanup case directory: {e}")
139
+
140
+ return jsonify({
141
+ "output": output,
142
+ "success": success,
143
+ "mesh_info": mesh_info
144
+ })
145
+
146
+ except subprocess.TimeoutExpired:
147
+ return jsonify({
148
+ "error": "blockMesh execution timed out",
149
+ "success": False,
150
+ "output": "Process exceeded 30 second timeout"
151
+ }), 408
152
+
153
+ except Exception as e:
154
+ return jsonify({
155
+ "error": str(e),
156
+ "success": False,
157
+ "output": f"Internal server error: {str(e)}"
158
+ }), 500
159
+
160
+ if __name__ == '__main__':
161
+ # Hugging Face Spaces sets PORT environment variable to 7860
162
+ port = int(os.environ.get('PORT', 7860))
163
+
164
+ print(f"Starting OpenFOAM blockMesh API on port {port}")
165
+ print(f"OpenFOAM environment sourced from /opt/openfoam11/etc/bashrc")
166
+
167
+ # Run with host 0.0.0.0 to accept external connections
168
+ app.run(host='0.0.0.0', port=port, debug=False)