File size: 6,321 Bytes
6d08d46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI main application for XRD Analysis Tool.
Serves both the API endpoints and the static React frontend.
"""
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
from typing import Dict, List
import re

from .model_inference import XRDModelInference

# Initialize FastAPI app
app = FastAPI(
    title="OpenAlphaDiffract",
    description="Automated crystallographic analysis of powder X-ray diffraction data",
    version="1.0.0",
)

# CORS — allow all origins (same-origin on HF Spaces, open for embeds)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize model inference
model_inference = XRDModelInference()


@app.on_event("startup")
async def startup_event():
    """Load model on startup"""
    model_inference.load_model()


@app.get("/api/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "model_loaded": model_inference.is_loaded()}


@app.post("/api/predict")
async def predict(data: dict):
    """
    Predict XRD analysis from preprocessed data.

    Expects JSON payload: {"x": [2theta values], "y": [intensity values], "metadata": {...}}
    """
    import time

    request_start = time.time()

    try:
        metadata = data.get("metadata", {})
        request_id = metadata.get("timestamp", "unknown")
        filename = metadata.get("filename", "unknown")
        analysis_count = metadata.get("analysisCount", "unknown")

        x = data.get("x", [])
        y = data.get("y", [])

        if not x or not y:
            return JSONResponse(status_code=400, content={"error": "Missing x or y data"})

        if len(x) != len(y):
            return JSONResponse(
                status_code=400,
                content={"error": "x and y arrays must have the same length"},
            )

        results = model_inference.predict(x, y)

        request_time = (time.time() - request_start) * 1000

        if isinstance(results, dict):
            results["request_metadata"] = {
                "request_id": request_id,
                "filename": filename,
                "analysis_count": analysis_count,
                "processing_time_ms": request_time,
            }

        return JSONResponse(
            content=results,
            headers={
                "Cache-Control": "no-cache, no-store, must-revalidate, private",
                "Pragma": "no-cache",
                "Expires": "0",
                "X-Request-ID": str(request_id),
            },
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"error": f"Prediction failed: {str(e)}"},
        )


# ---------------------------------------------------------------------------
# Example data endpoints
# ---------------------------------------------------------------------------
EXAMPLE_DATA_DIR = Path(__file__).parent.parent / "example_data"

CRYSTAL_SYSTEM_NAMES = {
    "1": "Triclinic",
    "2": "Monoclinic",
    "3": "Orthorhombic",
    "4": "Tetragonal",
    "5": "Trigonal",
    "6": "Hexagonal",
    "7": "Cubic",
}


def _parse_example_metadata(filepath: Path) -> dict:
    """Extract metadata from the header lines of a .dif file."""
    meta = {
        "filename": filepath.name,
        "material_id": None,
        "crystal_system": None,
        "crystal_system_name": None,
        "space_group": None,
        "wavelength": None,
    }
    with open(filepath, "r") as f:
        for line in f:
            line = line.strip()
            if (
                line
                and not line.startswith("#")
                and not line.startswith("CELL")
                and not line.startswith("SPACE")
                and not line.lower().startswith("wavelength")
            ):
                break

            if m := re.search(r"Material ID:\s*(\S+)", line):
                meta["material_id"] = m.group(1)
            if m := re.search(r"Crystal System:\s*(\d+)", line):
                num = m.group(1)
                meta["crystal_system"] = num
                meta["crystal_system_name"] = CRYSTAL_SYSTEM_NAMES.get(
                    num, f"Unknown ({num})"
                )
            if m := re.search(r"SPACE GROUP:\s*(\d+)", line):
                meta["space_group"] = m.group(1)
            if m := re.search(r"wavelength:\s*([\d.]+)", line, re.IGNORECASE):
                meta["wavelength"] = m.group(1)
    return meta


@app.get("/api/examples")
async def list_examples():
    """List available example data files with metadata."""
    if not EXAMPLE_DATA_DIR.exists():
        return []

    examples = []
    for fp in sorted(EXAMPLE_DATA_DIR.glob("*.dif")):
        examples.append(_parse_example_metadata(fp))
    return examples


@app.get("/api/examples/{filename}")
async def get_example(filename: str):
    """Return the raw text content of an example data file."""
    if "/" in filename or "\\" in filename or ".." in filename:
        raise HTTPException(status_code=400, detail="Invalid filename")

    filepath = EXAMPLE_DATA_DIR / filename
    if not filepath.exists() or not filepath.is_file():
        raise HTTPException(status_code=404, detail="Example file not found")

    return PlainTextResponse(filepath.read_text())


# ---------------------------------------------------------------------------
# Static files and SPA support
# ---------------------------------------------------------------------------
frontend_dist = Path(__file__).parent.parent / "frontend" / "dist"

if frontend_dist.exists():
    app.mount(
        "/assets",
        StaticFiles(directory=str(frontend_dist / "assets")),
        name="assets",
    )

    @app.get("/{path:path}")
    async def serve_spa(path: str):
        """Serve React SPA"""
        file_path = frontend_dist / path
        if file_path.is_file():
            return FileResponse(file_path)
        return FileResponse(frontend_dist / "index.html")

else:

    @app.get("/")
    async def root():
        return {"message": "Frontend not built. Run 'npm run build' in frontend/"}