File size: 7,152 Bytes
2ef91ed
 
 
 
 
 
372f2f1
2ef91ed
 
372f2f1
2ef91ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372f2f1
2ef91ed
 
372f2f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef91ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372f2f1
2ef91ed
 
372f2f1
 
 
 
 
 
2ef91ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372f2f1
 
2ef91ed
372f2f1
2ef91ed
 
 
 
 
 
 
 
 
 
 
 
 
 
372f2f1
 
 
2ef91ed
 
 
 
 
 
 
 
 
 
372f2f1
 
2ef91ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372f2f1
2ef91ed
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess
import os
import shutil
import uuid
import json

app = Flask(__name__)
CORS(app)

# Base directory for OpenFOAM cases
CASES_DIR = "/app/cases"
os.makedirs(CASES_DIR, exist_ok=True)

@app.route('/', methods=['GET'])
def home():
    """Home endpoint with API information"""
    return jsonify({
        "name": "OpenFOAM blockMesh API",
        "version": "1.0",
        "endpoints": {
            "/health": "GET - Health check",
            "/blockmesh": "POST - Run blockMesh with provided blockMeshDict"
        },
        "status": "operational"
    })

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy",
        "openfoam": "ready",
        "version": "OpenFOAM-2312"
    })

def read_polymesh_files(case_dir):
    """Read polyMesh files and return as dictionary"""
    polymesh_dir = os.path.join(case_dir, "constant", "polyMesh")
    
    mesh_data = {}
    
    try:
        # Read points file
        points_file = os.path.join(polymesh_dir, "points")
        if os.path.exists(points_file):
            with open(points_file, 'r') as f:
                mesh_data['points'] = f.read()
        
        # Read faces file
        faces_file = os.path.join(polymesh_dir, "faces")
        if os.path.exists(faces_file):
            with open(faces_file, 'r') as f:
                mesh_data['faces'] = f.read()
        
        # Read owner file
        owner_file = os.path.join(polymesh_dir, "owner")
        if os.path.exists(owner_file):
            with open(owner_file, 'r') as f:
                mesh_data['owner'] = f.read()
        
        # Read neighbour file
        neighbour_file = os.path.join(polymesh_dir, "neighbour")
        if os.path.exists(neighbour_file):
            with open(neighbour_file, 'r') as f:
                mesh_data['neighbour'] = f.read()
        
        # Read boundary file
        boundary_file = os.path.join(polymesh_dir, "boundary")
        if os.path.exists(boundary_file):
            with open(boundary_file, 'r') as f:
                mesh_data['boundary'] = f.read()
                
    except Exception as e:
        mesh_data['error'] = f"Error reading polyMesh files: {str(e)}"
    
    return mesh_data

@app.route('/blockmesh', methods=['POST'])
def run_blockmesh():
    """Run blockMesh with provided blockMeshDict"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                "error": "No JSON data provided",
                "success": False
            }), 400
        
        block_mesh_dict = data.get('blockMeshDict')
        
        if not block_mesh_dict:
            return jsonify({
                "error": "blockMeshDict is required",
                "success": False
            }), 400
        
        # Create unique case directory
        case_id = str(uuid.uuid4())
        case_dir = os.path.join(CASES_DIR, case_id)
        system_dir = os.path.join(case_dir, "system")
        constant_dir = os.path.join(case_dir, "constant")
        
        # Create directory structure
        os.makedirs(system_dir, exist_ok=True)
        os.makedirs(constant_dir, exist_ok=True)
        
        # Write blockMeshDict
        block_mesh_path = os.path.join(system_dir, "blockMeshDict")
        with open(block_mesh_path, 'w') as f:
            f.write(block_mesh_dict)
        
        # Create minimal controlDict with CORRECT header format
        control_dict_path = os.path.join(system_dir, "controlDict")
        minimal_control_dict = """/*--------------------------------*- C++ -*----------------------------------*\\
| =========                 |                                                 |
| \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox           |
|  \\    /   O peration     | Version:  v2406                                 |
|   \\  /    A nd           | Website:  www.openfoam.com                      |
|    \\/     M anipulation  |                                                 |
\\*---------------------------------------------------------------------------*/
FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

application     simpleFoam;
startFrom       startTime;
startTime       0;
stopAt          endTime;
endTime         1;
deltaT          1;
writeControl    timeStep;
writeInterval   1;
purgeWrite      0;
writeFormat     ascii;
writePrecision  6;
writeCompression off;
timeFormat      general;
timePrecision   6;
runTimeModifiable true;

// ************************************************************************* //
"""
        with open(control_dict_path, 'w') as f:
            f.write(minimal_control_dict)
        
        # Run blockMesh
        result = subprocess.run(
            ['blockMesh', '-case', case_dir],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        output = result.stdout + result.stderr
        success = result.returncode == 0
        
        # Get mesh statistics if successful
        mesh_info = {}
        polymesh_data = {}
        
        if success:
            # Run checkMesh
            try:
                check_mesh_result = subprocess.run(
                    ['checkMesh', '-case', case_dir],
                    capture_output=True,
                    text=True,
                    timeout=10
                )
                mesh_info = {
                    "checkMesh": check_mesh_result.stdout
                }
            except Exception as e:
                mesh_info = {
                    "checkMesh_error": str(e)
                }
            
            # Read polyMesh files
            polymesh_data = read_polymesh_files(case_dir)
        
        # Cleanup case directory
        try:
            shutil.rmtree(case_dir)
        except Exception as e:
            print(f"Warning: Failed to cleanup case directory: {e}")
        
        return jsonify({
            "output": output,
            "success": success,
            "mesh_info": mesh_info,
            "polymesh": polymesh_data  # NEW: Return the actual mesh data
        })
        
    except subprocess.TimeoutExpired:
        return jsonify({
            "error": "blockMesh execution timed out",
            "success": False,
            "output": "Process exceeded 30 second timeout"
        }), 408
        
    except Exception as e:
        return jsonify({
            "error": str(e),
            "success": False,
            "output": f"Internal server error: {str(e)}"
        }), 500

if __name__ == '__main__':
    # Hugging Face Spaces sets PORT environment variable to 7860
    port = int(os.environ.get('PORT', 7860))
    
    print(f"Starting OpenFOAM blockMesh API on port {port}")
    print(f"OpenFOAM environment sourced")
    
    # Run with host 0.0.0.0 to accept external connections
    app.run(host='0.0.0.0', port=port, debug=False)