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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
"""
FastAPI application for skill classification service.

Provides REST API endpoints for classifying GitHub issues and pull requests
into skill categories using machine learning models.

Usage:
    Development: fastapi dev hopcroft_skill_classification_tool_competition/main.py
    Production:  fastapi run hopcroft_skill_classification_tool_competition/main.py

Endpoints:
    GET  /         - API information
    GET  /health   - Health check
    POST /predict  - Single issue classification
    POST /predict/batch - Batch classification
"""

from contextlib import asynccontextmanager
from datetime import datetime
import json
import os
import time
from typing import List

from fastapi import FastAPI, HTTPException, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse
import mlflow
from prometheus_client import (
    CONTENT_TYPE_LATEST,
    Counter,
    Gauge,
    Histogram,
    Summary,
    generate_latest,
)
from pydantic import ValidationError

from hopcroft_skill_classification_tool_competition.api_models import (
    BatchIssueInput,
    BatchPredictionResponse,
    ErrorResponse,
    HealthCheckResponse,
    IssueInput,
    PredictionRecord,
    PredictionResponse,
    SkillPrediction,
)
from hopcroft_skill_classification_tool_competition.config import MLFLOW_CONFIG
from hopcroft_skill_classification_tool_competition.modeling.predict import SkillPredictor

# Define Prometheus Metrics
# Counter: Total number of requests
REQUESTS_TOTAL = Counter(
    "hopcroft_requests_total",
    "Total number of requests",
    ["method", "endpoint", "http_status"],
)

# Histogram: Request duration
REQUEST_DURATION_SECONDS = Histogram(
    "hopcroft_request_duration_seconds",
    "Request duration in seconds",
    ["method", "endpoint"],
)

# Gauge: In-progress requests
IN_PROGRESS_REQUESTS = Gauge(
    "hopcroft_in_progress_requests",
    "Number of requests currently in progress",
    ["method", "endpoint"],
)

# Summary: Model prediction time
MODEL_PREDICTION_SECONDS = Summary(
    "hopcroft_prediction_processing_seconds",
    "Time spent processing model predictions",
)

predictor = None
model_version = "1.0.0"


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application startup and shutdown."""
    global predictor, model_version

    print("=" * 80)
    print("Starting Skill Classification API")
    print("=" * 80)

    # Configure MLflow
    mlflow.set_tracking_uri(MLFLOW_CONFIG["uri"])
    print(f"MLflow tracking URI set to: {MLFLOW_CONFIG['uri']}")

    try:
        model_name = os.getenv("MODEL_NAME", "random_forest_tfidf_gridsearch.pkl")
        print(f"Loading model: {model_name}")
        predictor = SkillPredictor(model_name=model_name)
        print("Model and artifacts loaded successfully")
    except Exception as e:
        print(f"Failed to load model: {e}")
        print("WARNING: API starting in degraded mode (prediction will fail)")

    print(f"Model version {model_version} initialized")
    print("API ready")
    print("=" * 80)

    yield

    print("Shutting down API")


app = FastAPI(
    title="Skill Classification API",
    description="API for classifying GitHub issues and pull requests into skill categories",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)


@app.middleware("http")
async def monitor_requests(request: Request, call_next):
    """Middleware to collect Prometheus metrics for each request."""
    method = request.method
    # Use a simplified path or template if possible to avoid high cardinality
    # For now, using request.url.path is acceptable for this scale
    endpoint = request.url.path

    IN_PROGRESS_REQUESTS.labels(method=method, endpoint=endpoint).inc()
    start_time = time.time()

    try:
        response = await call_next(request)
        status_code = response.status_code
        REQUESTS_TOTAL.labels(method=method, endpoint=endpoint, http_status=status_code).inc()
        return response
    except Exception as e:
        REQUESTS_TOTAL.labels(method=method, endpoint=endpoint, http_status=500).inc()
        raise e
    finally:
        duration = time.time() - start_time
        REQUEST_DURATION_SECONDS.labels(method=method, endpoint=endpoint).observe(duration)
        IN_PROGRESS_REQUESTS.labels(method=method, endpoint=endpoint).dec()


@app.get("/metrics", tags=["Observability"])
async def metrics():
    """Expose Prometheus metrics."""
    return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)


@app.get("/", tags=["Root"])
async def root():
    """Return basic API information."""
    return {
        "message": "Skill Classification API",
        "version": "1.0.0",
        "documentation": "/docs",
        "demo": "/demo",
        "health": "/health",
    }


@app.get("/health", response_model=HealthCheckResponse, tags=["Health"])
async def health_check():
    """Check API and model status."""
    return HealthCheckResponse(
        status="healthy",
        model_loaded=predictor is not None,
        version="1.0.0",
        timestamp=datetime.now(),
    )


@app.get("/demo")
async def redirect_to_demo():
    """Redirect to Streamlit demo."""
    return RedirectResponse(url="http://localhost:8501")


@app.post(
    "/predict",
    response_model=PredictionRecord,
    status_code=status.HTTP_201_CREATED,
    tags=["Prediction"],
    summary="Classify a single issue",
    response_description="Skill predictions with confidence scores",
)
async def predict_skills(issue: IssueInput) -> PredictionRecord:
    """
    Classify a single GitHub issue or pull request into skill categories.

    Args:
        issue: IssueInput containing issue text and optional metadata

    Returns:
        PredictionRecord with list of predicted skills, confidence scores, and run_id

    Raises:
        HTTPException: If prediction fails
    """
    start_time = time.time()

    try:
        if predictor is None:
            raise HTTPException(status_code=503, detail="Model not loaded")

        # Combine text fields if needed, or just use issue_text
        # The predictor expects a single string
        # The predictor expects a single string
        full_text = f"{issue.issue_text} {issue.issue_description or ''} {issue.repo_name or ''}"

        with MODEL_PREDICTION_SECONDS.time():
            predictions_data = predictor.predict(full_text)

        # Convert to Pydantic models
        predictions = [
            SkillPrediction(skill_name=p["skill_name"], confidence=p["confidence"])
            for p in predictions_data
        ]

        processing_time = (time.time() - start_time) * 1000

        # Log to MLflow
        run_id = "local"
        timestamp = datetime.now()

        try:
            experiment_name = MLFLOW_CONFIG["experiments"]["baseline"]
            mlflow.set_experiment(experiment_name)

            with mlflow.start_run() as run:
                run_id = run.info.run_id
                # Log inputs
                mlflow.log_param("issue_text", issue.issue_text)
                if issue.repo_name:
                    mlflow.log_param("repo_name", issue.repo_name)

                # Log outputs (as metrics or params/tags for retrieval)
                # For simple retrieval, we'll store the main prediction as a tag/param
                if predictions:
                    mlflow.log_param("top_skill", predictions[0].skill_name)
                    mlflow.log_metric("top_confidence", predictions[0].confidence)

                # Store full predictions as a JSON artifact or tag
                predictions_json = json.dumps([p.model_dump() for p in predictions])
                mlflow.set_tag("predictions_json", predictions_json)
                mlflow.set_tag("model_version", model_version)
        except Exception as e:
            print(f"MLflow logging failed: {e}")

        return PredictionRecord(
            predictions=predictions,
            num_predictions=len(predictions),
            model_version=model_version,
            processing_time_ms=round(processing_time, 2),
            run_id=run_id,
            timestamp=timestamp,
            input_text=issue.issue_text,
        )

    except Exception as e:
        import traceback

        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Prediction failed: {str(e)}",
        )


@app.post(
    "/predict/batch",
    response_model=BatchPredictionResponse,
    status_code=status.HTTP_200_OK,
    tags=["Prediction"],
    summary="Classify multiple issues",
    response_description="Batch skill predictions",
)
async def predict_skills_batch(batch: BatchIssueInput) -> BatchPredictionResponse:
    """
    Classify multiple GitHub issues or pull requests in batch.

    Args:
        batch: BatchIssueInput containing list of issues (max 100)

    Returns:
        BatchPredictionResponse with prediction results for each issue

    Raises:
        HTTPException: If batch prediction fails
    """
    start_time = time.time()

    try:
        results = []

        if predictor is None:
            raise HTTPException(status_code=503, detail="Model not loaded")

        for issue in batch.issues:
            full_text = (
                f"{issue.issue_text} {issue.issue_description or ''} {issue.repo_name or ''}"
            )
            predictions_data = predictor.predict(full_text)

            predictions = [
                SkillPrediction(skill_name=p["skill_name"], confidence=p["confidence"])
                for p in predictions_data
            ]

            results.append(
                PredictionResponse(
                    predictions=predictions,
                    num_predictions=len(predictions),
                    model_version=model_version,
                )
            )

        total_processing_time = (time.time() - start_time) * 1000

        return BatchPredictionResponse(
            results=results,
            total_issues=len(batch.issues),
            total_processing_time_ms=round(total_processing_time, 2),
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Batch prediction failed: {str(e)}",
        )


@app.get(
    "/predictions/{run_id}",
    response_model=PredictionRecord,
    status_code=status.HTTP_200_OK,
    tags=["Prediction"],
    summary="Get a prediction by ID",
    response_description="Prediction details",
)
async def get_prediction(run_id: str) -> PredictionRecord:
    """
    Retrieve a specific prediction by its MLflow Run ID.

    Args:
        run_id: The MLflow Run ID

    Returns:
        PredictionRecord containing the prediction details

    Raises:
        HTTPException: If run not found or error occurs
    """
    try:
        run = mlflow.get_run(run_id)
        data = run.data

        # Reconstruct predictions from tags
        predictions_json = data.tags.get("predictions_json", "[]")
        predictions_data = json.loads(predictions_json)
        predictions = [SkillPrediction(**p) for p in predictions_data]

        # Get timestamp (start_time is in ms)
        timestamp = datetime.fromtimestamp(run.info.start_time / 1000.0)

        return PredictionRecord(
            predictions=predictions,
            num_predictions=len(predictions),
            model_version=data.tags.get("model_version", "unknown"),
            processing_time_ms=None,  # Not stored in standard tags, could be added
            run_id=run.info.run_id,
            timestamp=timestamp,
            input_text=data.params.get("issue_text", ""),
        )

    except mlflow.exceptions.MlflowException:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=f"Prediction with ID {run_id} not found"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve prediction: {str(e)}",
        )


@app.get(
    "/predictions",
    response_model=List[PredictionRecord],
    status_code=status.HTTP_200_OK,
    tags=["Prediction"],
    summary="List predictions",
    response_description="List of recent predictions",
)
async def list_predictions(skip: int = 0, limit: int = 10) -> List[PredictionRecord]:
    """
    Retrieve a list of recent predictions.

    Args:
        skip: Number of records to skip (not fully supported by MLflow search, handled client-side)
        limit: Maximum number of records to return

    Returns:
        List of PredictionRecord
    """
    try:
        experiment_name = MLFLOW_CONFIG["experiments"]["baseline"]
        experiment = mlflow.get_experiment_by_name(experiment_name)

        if not experiment:
            return []

        # Search runs
        runs = mlflow.search_runs(
            experiment_ids=[experiment.experiment_id],
            max_results=limit + skip,
            order_by=["start_time DESC"],
        )

        results = []
        # Convert pandas DataFrame to list of dicts if needed, or iterate
        # mlflow.search_runs returns a pandas DataFrame

        # We need to iterate through the DataFrame
        if runs.empty:
            return []

        # Apply skip
        runs = runs.iloc[skip:]

        for _, row in runs.iterrows():
            run_id = row.run_id

            # Extract data from columns (flattened)
            # Tags are prefixed with 'tags.', Params with 'params.'

            # Helper to safely get value
            def get_val(row, prefix, key, default=None):
                col = f"{prefix}.{key}"
                return row[col] if col in row else default

            predictions_json = get_val(row, "tags", "predictions_json", "[]")
            try:
                predictions_data = json.loads(predictions_json)
                predictions = [SkillPrediction(**p) for p in predictions_data]
            except Exception:
                predictions = []

            timestamp = row.start_time  # This is usually a datetime object in the DF

            # Get model_version with fallback to "unknown" or inherited default
            model_version = get_val(row, "tags", "model_version")
            if model_version is None or model_version == "":
                model_version = "unknown"

            # Get input_text with fallback to empty string
            input_text = get_val(row, "params", "issue_text")
            if input_text is None:
                input_text = ""

            results.append(
                PredictionRecord(
                    predictions=predictions,
                    num_predictions=len(predictions),
                    model_version=model_version,
                    processing_time_ms=None,
                    run_id=run_id,
                    timestamp=timestamp,
                    input_text=input_text,
                )
            )

        return results

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to list predictions: {str(e)}",
        )


@app.exception_handler(ValidationError)
async def validation_exception_handler(request, exc: ValidationError):
    """Handle Pydantic validation errors."""
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=ErrorResponse(
            error="Validation Error", detail=str(exc), timestamp=datetime.now()
        ).model_dump(),
    )


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc: HTTPException):
    """Handle HTTP exceptions."""
    return JSONResponse(
        status_code=exc.status_code,
        content=ErrorResponse(
            error=exc.detail, detail=None, timestamp=datetime.now()
        ).model_dump(),
    )