File size: 7,433 Bytes
0fa8876
 
 
 
 
 
a687c6a
 
 
9acac5c
a687c6a
 
 
 
 
 
 
 
 
 
9acac5c
0fa8876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9acac5c
0fa8876
 
 
 
 
 
 
 
 
 
a687c6a
0fa8876
a687c6a
 
9acac5c
0fa8876
 
 
9acac5c
0fa8876
 
 
 
 
9acac5c
 
0fa8876
 
 
 
 
 
9acac5c
 
 
 
 
 
 
 
 
 
 
 
a687c6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9acac5c
 
 
 
a687c6a
 
 
9acac5c
 
 
 
0fa8876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9acac5c
 
 
 
 
 
 
 
 
0fa8876
9acac5c
 
0fa8876
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
import gradio as gr
import pandas as pd
import numpy as np
from typing import List, Dict
import os

# Create static directory if it doesn't exist
if not os.path.exists('static'):
    os.makedirs('static')

# Move thumbs directory into static if it exists
if os.path.exists('thumbs'):
    import shutil
    if not os.path.exists('static/thumbs'):
        shutil.move('thumbs', 'static/')
    else:
        # If static/thumbs already exists, merge the contents
        for file in os.listdir('thumbs'):
            shutil.move(os.path.join('thumbs', file), 'static/thumbs/')
        os.rmdir('thumbs')

class CSVViewer:
    def __init__(self, csv_path: str):
        self.df = pd.read_csv(csv_path)
        self.current_page = 0
        self.rows_per_page = 1
        self.total_pages = len(self.df)
        
    def get_page_data(self, page_num: int) -> Dict:
        if page_num < 0 or page_num >= self.total_pages:
            return None
            
        row = self.df.iloc[page_num]
        
        # Get product information
        product_info = {
            'Web link': str(row['Web link']),
            'Product Code': str(row['Product Code']),
            'Product Name': str(row['Product Name'])
        }
        
        # Separate original and AI-predicted columns
        original_data = {}
        ai_data = {}
        
        for col in self.df.columns:
            if 'Score' in col or 'Distance' in col or col  == '':
                continue  # Skip score and distance columns
                
            if col in ['Web link', 'Product Code', 'Product Name']:
                continue  # Skip these columns as they're shown at the top

            if col in ["Length", "Style", "Sleeve Length", "Neckline", "Pattern", "Fabric", "Features", "Closure", "Body Fit", "Occasion", "Season"]:
                original_data[col] = str(row[col])
            if col.endswith('_AI'):
                ai_data[col] = str(row[col])
                
        
        return {
            'product_info': product_info,
            'original_data': original_data,
            'ai_data': ai_data,
            'page_num': page_num + 1,
            'total_pages': self.total_pages
        }

def create_page_view(page_num: int):
    viewer = CSVViewer('attr.csv')
    page_data = viewer.get_page_data(page_num)
    
    if not page_data:
        return "Invalid page number"
    
    # Get product image
    product_code = page_data['product_info']['Product Code']
    
    # Find matching image file
    image_files = [f for f in os.listdir('static/thumbs') if f.startswith(product_code)]
    if image_files:
        # Use Gradio's static file serving
        image_path = f"/static/thumbs/{image_files[0]}"
        print(f"Found image: {image_path}")
    else:
        image_path = None
    
    # Create HTML content
    html = f"<h3>Page {page_data['page_num']} of {page_data['total_pages']}</h3>"
    html += "<div style='margin-bottom: 20px; display: flex; gap: 20px;'>"
    
    # Product info section
    html += "<div>"
    if image_path:
        html += f"<img src='{image_path}' alt='Product Image' style='max-width: 100%; border-radius: 5px;'>"
    for key, value in page_data['product_info'].items():
        html += f"<p><strong>{key}:</strong> {value}</p>"
    html += "</div></div>"
    
    html += "<div style='display: flex; gap: 20px;'>"
    
    # Comparison section
    html += "<div style='flex: 1; border: 1px solid #ddd; padding: 15px; border-radius: 5px;'>"
    html += "<h4>Comparison</h4>"
    html += "<table style='width: 100%;'>"
    html += "<tr style='background-color: #f5f5f5;'><th>Attribute</th><th>Original</th><th>AI Prediction</th><th>Status</th></tr>"
    
    # Add comparison rows
    for key, orig_value in page_data['original_data'].items():
        # Find matching AI prediction
        ai_key = key + '_AI'
        ai_value = page_data['ai_data'].get(ai_key, '')
        
        # Skip if AI value is empty
        if not ai_value.strip():
            continue
            
        # Clean up values by removing brackets and quotes
        orig_value = str(orig_value).strip('[]').strip('"').strip()
        ai_value = str(ai_value).strip('[]').strip('"').strip()
        
        # Handle array values
        try:
            # Try to parse as arrays
            orig_items = [item.strip() for item in orig_value.split(',') if item.strip()]
            ai_items = [item.strip() for item in ai_value.split(',') if item.strip()]
            
            # Check if all original items are in AI items
            if all(item.lower() in [x.lower() for x in ai_items] for item in orig_items):
                if len(ai_items) > len(orig_items):
                    status = "βœ“ All and more"
                    status_color = "#4CAF50"
                    row_color = "#e8f5e9"
                else:
                    status = "βœ“ Match"
                    status_color = "#4CAF50"
                    row_color = "#e8f5e9"
            else:
                status = "βœ— Mismatch"
                status_color = "#f44336"
                row_color = "#ffebee"
                
            # Format the values nicely
            orig_display = ', '.join(orig_items)
            ai_display = ', '.join(ai_items)
            
        except:
            # Handle non-array values
            if orig_value.lower() == ai_value.lower():
                status = "βœ“ Match"
                status_color = "#4CAF50"
                row_color = "#e8f5e9"
                orig_display = orig_value
                ai_display = ai_value
            else:
                status = "βœ— Mismatch"
                status_color = "#f44336"
                row_color = "#ffebee"
                orig_display = orig_value
                ai_display = ai_value
            
        # Add row with comparison
        html += f"<tr style='background-color: {row_color};'>"
        html += f"<td style='width: 150px;'>{key}</td>"
        html += f"<td>{orig_display}</td>"
        html += f"<td>{ai_display}</td>"
        html += f"<td style='color: {status_color}; font-weight: bold;'>{status}</td>"
        html += "</tr>"
    
    html += "</table></div>"
    
    # Original data section
    html += "<div style='flex: 1; border: 1px solid #ddd; padding: 15px; border-radius: 5px;'>"
    html += "<h4>Original Data</h4>"
    html += "<table style='width: 100%;'>"
    for key, value in page_data['original_data'].items():
        html += f"<tr><td style='width: 150px;'>{key}</td><td>{value}</td></tr>"
    html += "</table></div>"
    
    # AI data section
    html += "<div style='flex: 1; border: 1px solid #ddd; padding: 15px; border-radius: 5px;'>"
    html += "<h4>AI Predicted Data</h4>"
    html += "<table style='width: 100%;'>"
    for key, value in page_data['ai_data'].items():
        html += f"<tr><td style='width: 150px;'>{key}</td><td>{value}</td></tr>"
    html += "</table></div>"
    
    html += "</div>"
    return html

# Create Gradio interface
demo = gr.Blocks()
with demo:
    gr.Markdown("# CSV Data Viewer")
    gr.Markdown("Navigate through CSV data pages to compare original and AI-predicted values")
    
    page_num = gr.Slider(0, 100, step=1, label="Page Number")
    html_output = gr.HTML()
    
    page_num.change(create_page_view, [page_num], [html_output])

# Launch Gradio interface
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)