File size: 5,363 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
"""Example usage of the fraud detection system."""

import sys
from pathlib import Path

# Add parent directory to path to allow importing src modules
sys.path.insert(0, str(Path(__file__).parent.parent))

import logging
import warnings
import os

# Suppress warnings for cleaner output
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=UserWarning)
warnings.filterwarnings('ignore', message='.*LangChain.*')

from src.data.processor import FraudDataProcessor
from src.llm.groq_client import GroqClient
from src.rag.document_loader import DocumentLoader
from src.rag.vector_store import VectorStore
from src.services.fraud_analyzer import FraudAnalyzer
from src.config.config import settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def example_basic_llm():
    """Example: Basic LLM usage."""
    logger.info("=== Example: Basic LLM Usage ===")
    
    client = GroqClient()
    
    response = client.invoke(
        prompt="What are common indicators of credit card fraud?",
        system_message="You are an expert fraud detection analyst.",
    )
    
    print("\nResponse:")
    print(response)
    print("\n")


def example_rag_system():
    """Example: RAG system setup."""
    logger.info("=== Example: RAG System Setup ===")
    
    # Load documents
    document_loader = DocumentLoader(
        chunk_size=settings.chunk_size,
        chunk_overlap=settings.chunk_overlap,
    )
    
    pdf_documents = document_loader.load_pdfs_from_directory(settings.pdf_dir)
    
    if pdf_documents:
        # Create vector store
        vector_store = VectorStore()
        vector_store.add_documents(pdf_documents)
        
        # Search for relevant documents
        query = "What are the main types of payment fraud?"
        results = vector_store.similarity_search(query, k=3)
        
        print(f"\nFound {len(results)} relevant documents for query: {query}")
        for i, doc in enumerate(results, 1):
            print(f"\n--- Document {i} ---")
            print(doc.page_content[:200] + "...")
    else:
        logger.warning("No PDF documents found")
    
    print("\n")


def example_fraud_analysis():
    """Example: Fraud analysis."""
    logger.info("=== Example: Fraud Analysis ===")
    
    # Initialize components
    groq_client = GroqClient()
    
    # Setup RAG (optional)
    vector_store = None
    try:
        document_loader = DocumentLoader()
        pdf_documents = document_loader.load_pdfs_from_directory(settings.pdf_dir)
        if pdf_documents:
            vector_store = VectorStore()
            vector_store.add_documents(pdf_documents)
    except Exception as e:
        logger.warning(f"RAG setup failed: {e}")
    
    # Create analyzer
    analyzer = FraudAnalyzer(
        groq_client=groq_client,
        vector_store=vector_store,
    )
    
    # Analyze a transaction
    try:
        result = analyzer.analyze_transaction(
            transaction_id=0,
            use_rag=vector_store is not None,
        )
        
        print("\n=== Analysis Result ===")
        print(f"Transaction: {result['transaction'].get('merchant', 'N/A')}")
        print(f"\nAnalysis:\n{result['analysis']}")
    except Exception as e:
        logger.error(f"Analysis failed: {e}")
    
    print("\n")


def example_data_processing():
    """Example: Data processing."""
    logger.info("=== Example: Data Processing ===")
    
    processor = FraudDataProcessor()
    
    try:
        # Load data
        train_df = processor.load_train_data()
        print(f"\nLoaded {len(train_df)} training samples")
        
        # Get summary
        summary = processor.get_transaction_summary()
        print(f"\n=== Dataset Summary ===")
        print(f"Total transactions: {summary['total_transactions']}")
        print(f"Fraud count: {summary['fraud_count']}")
        print(f"Fraud percentage: {summary['fraud_percentage']:.2f}%")
        print(f"Average amount: ${summary['average_amount']:.2f}")
        
        # Format a transaction
        if len(train_df) > 0:
            transaction = train_df.iloc[0].to_dict()
            formatted = processor.format_transaction_for_llm(transaction)
            print(f"\n=== Formatted Transaction ===")
            print(formatted)
    except Exception as e:
        logger.error(f"Data processing failed: {e}")
    
    print("\n")


if __name__ == "__main__":
    print("Fraud Detection System - Example Usage\n")
    print("=" * 50)
    
    # Run examples
    try:
        example_basic_llm()
    except Exception as e:
        logger.error(f"Basic LLM example failed: {e}")
    
    try:
        example_data_processing()
    except Exception as e:
        logger.error(f"Data processing example failed: {e}")
    
    try:
        example_rag_system()
    except Exception as e:
        logger.error(f"RAG system example failed: {e}")
    
    try:
        example_fraud_analysis()
    except Exception as e:
        logger.error(f"Fraud analysis example failed: {e}")
    
    print("=" * 50)
    print("\nExamples completed!")