File size: 10,204 Bytes
7a920b1
 
 
 
 
 
 
 
5515ef5
 
7a920b1
5515ef5
7a920b1
5515ef5
7a920b1
5515ef5
7a920b1
5515ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a920b1
 
 
 
5515ef5
7a920b1
 
5515ef5
7a920b1
 
 
 
 
 
5515ef5
7a920b1
 
 
 
5515ef5
7a920b1
5515ef5
7a920b1
 
5515ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a920b1
5515ef5
 
 
7a920b1
5515ef5
 
 
 
7a920b1
5515ef5
 
 
 
7a920b1
5515ef5
 
7a920b1
 
5515ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a920b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5515ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
from typing import Optional
from sklearn.metrics import (
    precision_score,
    recall_score,
    accuracy_score,
    classification_report,
)
from tqdm.asyncio import tqdm as async_tqdm
import asyncio

from src.modules.vlm_inference import analyze_product_image_async
from src.modules.data_processing import image_to_base64
from pathlib import Path

DATA_PATH = Path(__file__).parents[2] / "data"


async def _process_single_row(
    row_data: dict,
    model: str,
    api_key: str,
    provider: str,
    semaphore: asyncio.Semaphore,
) -> dict:
    """
    Process a single row with semaphore control

    Args:
        row_data: Dictionary with 'image' and 'id' keys
        model: Model to use for inference
        api_key: API key for the provider
        provider: Provider to use
        semaphore: Asyncio semaphore for rate limiting

    Returns:
        dict: Prediction result
    """
    async with semaphore:
        try:
            img_b64 = image_to_base64(row_data["image"])
            prediction = await analyze_product_image_async(
                image_url=img_b64,
                model=model,
                api_key=api_key,
                provider=provider,
            )
            return {
                "id": row_data["id"],
                "pred_masterCategory": prediction.master_category,
                "pred_gender": prediction.gender,
                "pred_subCategory": prediction.sub_category,
                "pred_description": prediction.description,
            }
        except Exception as e:
            return {
                "id": row_data["id"],
                "pred_masterCategory": None,
                "pred_gender": None,
                "pred_subCategory": None,
                "pred_description": f"Error: {str(e)}",
            }


async def run_inference_on_dataframe_async(
    df: pd.DataFrame,
    model: str = "accounts/fireworks/models/qwen2p5-vl-72b-instruct",
    api_key: Optional[str] = None,
    provider: str = "Fireworks",
    max_concurrent_requests: int = 10,
) -> pd.DataFrame:
    """
    Run VLM inference on entire dataframe of images with concurrent requests

    Args:
        df: DataFrame containing images
        model: Model to use for inference
        api_key: API key for the provider
        provider: Provider to use (Fireworks or OpenAI)
        max_concurrent_requests: Maximum number of concurrent API requests (default: 10)

    Returns:
        pd.DataFrame: Results with columns:
            - id: Image ID
            - pred_masterCategory: Predicted master category
            - pred_gender: Predicted gender
            - pred_subCategory: Predicted sub-category
            - pred_description: Predicted description
    """
    # Create semaphore for rate limiting
    semaphore = asyncio.Semaphore(max_concurrent_requests)

    # Prepare all rows as dictionaries
    rows_data = [
        {"image": row.image, "id": row.id}
        for row in df.itertuples(index=False, name="columns")
    ]

    # Create all tasks (coroutines, not awaited yet)
    tasks = [
        _process_single_row(row_data, model, api_key, provider, semaphore)
        for row_data in rows_data
    ]

    _model = model.split("/")[-1]
    # Run all tasks concurrently with progress bar
    results = []
    for task in async_tqdm.as_completed(tasks, total=len(tasks)):
        result = await task
        results.append(result)

        if len(results) % 10 == 0:
            df_pred = pd.DataFrame(results)
            file_name = DATA_PATH / f"df_pred_{provider}_{_model}.csv"
            df_pred.to_csv(file_name, index=False)

    # Final save
    df_pred = pd.DataFrame(results)
    file_name = DATA_PATH / f"df_pred_{provider}_{_model}.csv"
    df_pred.to_csv(file_name, index=False)

    print(f"\nPrediction successful, dataset saved to {file_name}")
    return df_pred


def run_inference_on_dataframe(
    df: pd.DataFrame,
    model: str = "accounts/fireworks/models/qwen2p5-vl-72b-instruct",
    api_key: Optional[str] = None,
    provider: str = "Fireworks",
    max_concurrent_requests: int = 10,
) -> pd.DataFrame:
    """
    Run VLM inference on entire dataframe of images (sync wrapper for async function)

    Args:
        df: DataFrame containing images
        model: Model to use for inference
        api_key: API key for the provider
        provider: Provider to use (Fireworks or OpenAI)
        max_concurrent_requests: Maximum number of concurrent API requests (default: 10)

    Returns:
        pd.DataFrame: Results with columns:
            - id: Image ID
            - pred_masterCategory: Predicted master category
            - pred_gender: Predicted gender
            - pred_subCategory: Predicted sub-category
            - pred_description: Predicted description
    """
    return asyncio.run(
        run_inference_on_dataframe_async(df, model, api_key, provider, max_concurrent_requests)
    )


def calculate_metrics(
    df_ground_truth: pd.DataFrame,
    df_predictions: pd.DataFrame,
    column: str,
    id_col: str = "id",
    average: str = "weighted",
) -> dict:
    """
    Calculate precision, recall, and accuracy for a specific column

    Args:
        df_ground_truth: DataFrame with ground truth labels
        df_predictions: DataFrame with predictions
        column: Column name to evaluate (e.g., 'master_category', 'gender', 'sub_category')
        id_col: Column name for joining the dataframes
        average: Averaging method for multi-class metrics ('weighted', 'macro', 'micro')

    Returns:
        dict: Dictionary containing:
            - accuracy: Overall accuracy
            - precision: Precision score
            - recall: Recall score
            - classification_report: Detailed classification report
    """
    # Merge ground truth and predictions on ID
    merged = df_ground_truth[[id_col, column]].merge(
        df_predictions[[id_col, f"pred_{column}"]], on=id_col, how="inner"
    )

    # Remove any rows with None predictions (failed inferences)
    merged = merged.dropna(subset=[f"pred_{column}"])

    if len(merged) == 0:
        raise ValueError("No valid predictions found after merging and removing nulls")

    # Get ground truth and predictions
    y_true = merged[column]
    y_pred = merged[f"pred_{column}"]

    # Calculate metrics
    accuracy = accuracy_score(y_true, y_pred)
    precision = precision_score(y_true, y_pred, average=average, zero_division=0)
    recall = recall_score(y_true, y_pred, average=average, zero_division=0)

    # Get detailed classification report
    report = classification_report(y_true, y_pred, zero_division=0)

    return {
        "accuracy": accuracy,
        "precision": precision,
        "recall": recall,
        "classification_report": report,
        "num_samples": len(merged),
    }


def evaluate_all_categories(
    df_ground_truth: pd.DataFrame,
    df_predictions: pd.DataFrame,
    id_col: str = "id",
    categories: list[str] = None,
) -> dict:
    """
    Evaluate predictions for all category types

    Args:
        df_ground_truth: DataFrame with ground truth labels
        df_predictions: DataFrame with predictions
        id_col: Column name for joining
        categories: List of category columns to evaluate

    Returns:
        dict: Dictionary with metrics for each category
    """
    if categories is None:
        categories = ["masterCategory", "gender", "subCategory"]

    results = {}

    for category in categories:
        print(f"\n{'='*60}")
        print(f"Evaluating: {category}")
        print(f"{'='*60}")

        try:
            metrics = calculate_metrics(
                df_ground_truth=df_ground_truth,
                df_predictions=df_predictions,
                column=category,
                id_col=id_col,
            )

            results[category] = metrics

            # Print summary
            print(f"Accuracy:  {metrics['accuracy']:.4f}")
            print(f"Precision: {metrics['precision']:.4f}")
            print(f"Recall:    {metrics['recall']:.4f}")
            print(f"Samples:   {metrics['num_samples']}")
            print(f"\nClassification Report:\n{metrics['classification_report']}")

        except Exception as e:
            print(f"Error evaluating {category}: {e}")
            results[category] = {"error": str(e)}

    return results


def create_evaluation_summary(results: dict) -> pd.DataFrame:
    """
    Create a summary DataFrame from evaluation results

    Args:
        results: Dictionary of evaluation results from evaluate_all_categories

    Returns:
        pd.DataFrame: Summary table with metrics for each category
    """
    summary_data = []

    for category, metrics in results.items():
        if "error" not in metrics:
            summary_data.append(
                {
                    "Category": category,
                    "Accuracy": f"{metrics['accuracy']:.4f}",
                    "Precision": f"{metrics['precision']:.4f}",
                    "Recall": f"{metrics['recall']:.4f}",
                    "Samples": metrics["num_samples"],
                }
            )
        else:
            summary_data.append(
                {
                    "Category": category,
                    "Accuracy": "Error",
                    "Precision": "Error",
                    "Recall": "Error",
                    "Samples": 0,
                }
            )

    return pd.DataFrame(summary_data)


def extract_metrics(results_dict, model_name):
    """
    Extract accuracy, precision, and recall for each category.

    Args:
        results_dict: Dictionary containing evaluation metrics
        model_name: Name of the model for identification

    Returns:
        List of dictionaries with metrics per category
    """
    metrics_list = []

    for category, metrics in results_dict.items():
        metrics_list.append({
            'model': model_name,
            'category': category,
            'accuracy': metrics['accuracy'],
            'precision': metrics['precision'],
            'recall': metrics['recall'],
            'num_samples': metrics['num_samples']
        })

    return metrics_list