File size: 10,541 Bytes
fd99b61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CSV document generator for RAG system."""

import logging
from pathlib import Path
from typing import List, Dict, Any
import pandas as pd
from langchain_core.documents import Document

logger = logging.getLogger(__name__)


class CSVDocumentGenerator:
    """Generate documents from CSV data for RAG system."""

    def __init__(self, csv_path: Path, sample_size: int = 1050000) -> None:
        """Initialize CSV document generator.



        Args:

            csv_path: Path to the CSV file.

            sample_size: Number of rows to sample from CSV (to handle large files).

        """
        self.csv_path = Path(csv_path)
        self.sample_size = sample_size
        self.df: pd.DataFrame = None

    def load_data(self) -> None:
        """Load CSV data with sampling for efficiency."""
        if not self.csv_path.exists():
            raise FileNotFoundError(f"CSV file not found: {self.csv_path}")

        try:
            logger.info(f"Loading CSV data from {self.csv_path}")
            # Load with sampling to handle large file
            self.df = pd.read_csv(self.csv_path, nrows=self.sample_size)
            
            # Clean merchant names (remove 'fraud_' prefix common in synthetic datasets)
            if 'merchant' in self.df.columns:
                self.df['merchant'] = self.df['merchant'].str.replace('fraud_', '', regex=False)
                
            logger.info(f"Loaded {len(self.df)} rows from CSV (merchant names cleaned)")
        except Exception as e:
            logger.error(f"Error loading CSV: {str(e)}")
            raise

    def generate_fraud_pattern_documents(self) -> List[Document]:
        """Generate documents about fraud patterns by category.



        Returns:

            List of documents containing fraud pattern insights.

        """
        if self.df is None:
            self.load_data()

        documents = []

        # Fraud patterns by category
        category_fraud = self.df.groupby('category').agg({
            'is_fraud': ['sum', 'mean', 'count']
        }).round(4)

        for category in category_fraud.index:
            fraud_count = int(category_fraud.loc[category, ('is_fraud', 'sum')])
            fraud_rate = float(category_fraud.loc[category, ('is_fraud', 'mean')] * 100)
            total_txns = int(category_fraud.loc[category, ('is_fraud', 'count')])

            content = f"""Fraud Pattern Analysis - Category: {category}



Based on historical transaction data analysis:



- Total Transactions: {total_txns:,}

- Fraud Cases: {fraud_count:,}

- Fraud Rate: {fraud_rate:.2f}%

- Risk Level: {'HIGH' if fraud_rate > 5 else 'MEDIUM' if fraud_rate > 1 else 'LOW'}



This category shows {'significant' if fraud_rate > 5 else 'moderate' if fraud_rate > 1 else 'low'} fraud activity in the historical dataset.

"""
            documents.append(Document(
                page_content=content,
                metadata={
                    "source": "fraudTrain.csv",
                    "type": "fraud_pattern",
                    "category": category,
                    "fraud_rate": fraud_rate
                }
            ))

        logger.info(f"Generated {len(documents)} category fraud pattern documents")
        return documents

    def generate_statistical_summaries(self) -> List[Document]:
        """Generate statistical summary documents.



        Returns:

            List of documents containing statistical insights.

        """
        if self.df is None:
            self.load_data()

        documents = []

        # Overall statistics
        total_txns = len(self.df)
        fraud_txns = int(self.df['is_fraud'].sum())
        fraud_rate = float(self.df['is_fraud'].mean() * 100)
        avg_amount = float(self.df['amt'].mean())
        fraud_avg_amount = float(self.df[self.df['is_fraud'] == 1]['amt'].mean())
        legit_avg_amount = float(self.df[self.df['is_fraud'] == 0]['amt'].mean())

        overall_summary = f"""Overall Fraud Detection Statistics



Dataset Summary:

- Total Transactions Analyzed: {total_txns:,}

- Fraudulent Transactions: {fraud_txns:,}

- Overall Fraud Rate: {fraud_rate:.2f}%

- Average Transaction Amount: ${avg_amount:.2f}

- Average Fraud Amount: ${fraud_avg_amount:.2f}

- Average Legitimate Amount: ${legit_avg_amount:.2f}



Key Insight: Fraudulent transactions have an average amount of ${fraud_avg_amount:.2f} compared to ${legit_avg_amount:.2f} for legitimate transactions.

"""
        documents.append(Document(
            page_content=overall_summary,
            metadata={
                "source": "fraudTrain.csv",
                "type": "statistical_summary",
                "scope": "overall"
            }
        ))

        # Amount range analysis
        amount_bins = [0, 10, 50, 100, 500, 1000, float('inf')]
        amount_labels = ['$0-10', '$10-50', '$50-100', '$100-500', '$500-1000', '$1000+']
        self.df['amount_range'] = pd.cut(self.df['amt'], bins=amount_bins, labels=amount_labels)

        amount_fraud = self.df.groupby('amount_range', observed=True).agg({
            'is_fraud': ['sum', 'mean', 'count']
        }).round(4)

        amount_content = "Fraud Patterns by Transaction Amount\n\n"
        for amt_range in amount_labels:
            if amt_range in amount_fraud.index:
                fraud_count = int(amount_fraud.loc[amt_range, ('is_fraud', 'sum')])
                fraud_rate = float(amount_fraud.loc[amt_range, ('is_fraud', 'mean')] * 100)
                total = int(amount_fraud.loc[amt_range, ('is_fraud', 'count')])

                amount_content += f"""

Amount Range: {amt_range}

- Total Transactions: {total:,}

- Fraud Cases: {fraud_count:,}

- Fraud Rate: {fraud_rate:.2f}%

"""

        documents.append(Document(
            page_content=amount_content,
            metadata={
                "source": "fraudTrain.csv",
                "type": "statistical_summary",
                "scope": "amount_analysis"
            }
        ))

        logger.info(f"Generated {len(documents)} statistical summary documents")
        return documents

    def generate_merchant_profiles(self) -> List[Document]:
        """Generate merchant risk profile documents.



        Returns:

            List of documents containing merchant insights.

        """
        if self.df is None:
            self.load_data()

        documents = []

        # Top merchants by transaction volume
        merchant_stats = self.df.groupby('merchant').agg({
            'is_fraud': ['sum', 'mean', 'count'],
            'amt': 'mean'
        }).round(4)

        # Get top 20 merchants by volume
        top_merchants = merchant_stats.nlargest(20, ('is_fraud', 'count'))

        for merchant in top_merchants.index:
            fraud_count = int(top_merchants.loc[merchant, ('is_fraud', 'sum')])
            fraud_rate = float(top_merchants.loc[merchant, ('is_fraud', 'mean')] * 100)
            total_txns = int(top_merchants.loc[merchant, ('is_fraud', 'count')])
            avg_amt = float(top_merchants.loc[merchant, ('amt', 'mean')])

            content = f"""Merchant Risk Profile: {merchant}



Transaction Analysis:

- Total Transactions: {total_txns:,}

- Fraudulent Transactions: {fraud_count:,}

- Fraud Rate: {fraud_rate:.2f}%

- Average Transaction Amount: ${avg_amt:.2f}

- Risk Assessment: {'HIGH RISK' if fraud_rate > 10 else 'MEDIUM RISK' if fraud_rate > 5 else 'LOW RISK'}



This merchant profile is based on historical transaction patterns and can help identify similar fraud patterns.

"""
            documents.append(Document(
                page_content=content,
                metadata={
                    "source": "fraudTrain.csv",
                    "type": "merchant_profile",
                    "merchant": merchant,
                    "fraud_rate": fraud_rate
                }
            ))

        logger.info(f"Generated {len(documents)} merchant profile documents")
        return documents

    def generate_location_insights(self) -> List[Document]:
        """Generate location-based fraud insights.



        Returns:

            List of documents containing location insights.

        """
        if self.df is None:
            self.load_data()

        documents = []

        # State-level analysis
        state_fraud = self.df.groupby('state').agg({
            'is_fraud': ['sum', 'mean', 'count']
        }).round(4)

        # Get top 15 states by transaction volume
        top_states = state_fraud.nlargest(15, ('is_fraud', 'count'))

        for state in top_states.index:
            fraud_count = int(top_states.loc[state, ('is_fraud', 'sum')])
            fraud_rate = float(top_states.loc[state, ('is_fraud', 'mean')] * 100)
            total_txns = int(top_states.loc[state, ('is_fraud', 'count')])

            content = f"""Geographic Fraud Analysis - State: {state}



Location-based Fraud Patterns:

- Total Transactions: {total_txns:,}

- Fraud Cases: {fraud_count:,}

- Fraud Rate: {fraud_rate:.2f}%

- Geographic Risk Level: {'HIGH' if fraud_rate > 5 else 'MEDIUM' if fraud_rate > 2 else 'LOW'}



This geographic area shows {'elevated' if fraud_rate > 5 else 'moderate' if fraud_rate > 2 else 'normal'} fraud activity levels.

"""
            documents.append(Document(
                page_content=content,
                metadata={
                    "source": "fraudTrain.csv",
                    "type": "location_insight",
                    "state": state,
                    "fraud_rate": fraud_rate
                }
            ))

        logger.info(f"Generated {len(documents)} location insight documents")
        return documents

    def generate_all_documents(self) -> List[Document]:
        """Generate all types of documents from CSV data.



        Returns:

            List of all generated documents.

        """
        all_documents = []

        logger.info("Generating all document types from CSV data...")

        all_documents.extend(self.generate_fraud_pattern_documents())
        all_documents.extend(self.generate_statistical_summaries())
        all_documents.extend(self.generate_merchant_profiles())
        all_documents.extend(self.generate_location_insights())

        logger.info(f"Generated total of {len(all_documents)} documents from CSV data")
        return all_documents