File size: 10,904 Bytes
6e4be07
a4ef927
 
 
 
 
009ec65
 
a4ef927
 
 
 
 
 
 
009ec65
6e4be07
009ec65
a4ef927
 
 
 
6e4be07
009ec65
a4ef927
 
009ec65
 
 
a4ef927
009ec65
a4ef927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
009ec65
a4ef927
 
009ec65
a4ef927
 
 
 
 
 
 
 
 
 
 
 
 
90b6e19
 
 
a4ef927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90b6e19
a4ef927
 
 
 
 
 
 
009ec65
a4ef927
 
 
 
009ec65
90b6e19
 
a4ef927
009ec65
90b6e19
 
 
 
 
a4ef927
 
944c441
 
 
 
 
a4ef927
90b6e19
 
 
 
 
944c441
90b6e19
a4ef927
90b6e19
009ec65
 
90b6e19
 
944c441
a4ef927
90b6e19
 
 
 
 
 
 
 
009ec65
90b6e19
009ec65
 
 
 
 
 
 
 
 
 
90b6e19
a4ef927
 
009ec65
a4ef927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
009ec65
 
 
 
 
 
 
 
 
 
 
 
616f92a
 
009ec65
616f92a
 
 
 
009ec65
616f92a
 
 
 
a4ef927
 
 
90b6e19
a4ef927
009ec65
a4ef927
 
009ec65
a4ef927
 
 
 
 
 
90b6e19
009ec65
90b6e19
a4ef927
 
 
 
 
90b6e19
 
944c441
 
009ec65
 
 
 
944c441
a4ef927
 
 
009ec65
a4ef927
 
90b6e19
 
 
a4ef927
 
009ec65
a4ef927
 
 
 
 
 
 
 
 
 
90b6e19
 
 
 
 
a4ef927
90b6e19
 
 
a4ef927
 
 
009ec65
a4ef927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616f92a
a4ef927
 
 
 
 
 
 
 
009ec65
90b6e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ef927
 
 
 
 
 
 
 
009ec65
 
 
 
a4ef927
009ec65
 
a4ef927
 
 
 
 
6e4be07
7284d62
 
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
import gradio as gr
import nltk
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
from typing import Tuple, Optional

from visuals.score_card import render_score_card
from visuals.layout import (
    render_page_header,
    render_core_reference,
    render_pipeline,
    render_pipeline_graph,
    render_pipeline_warning,
    render_strategy_alignment,
)

# Download tokenizer if not already available
try:
    nltk.download("punkt", quiet=True)
except Exception as e:
    print(f"Error downloading NLTK data: {e}")

# Load embedding model
model = SentenceTransformer("all-MiniLM-L6-v2")

# Global state to store uploaded DataFrame
uploaded_df = {}


# --- Core Metrics ---
def calculate_ttr(text: str) -> float:
    words = text.split()
    unique_words = set(words)
    return len(unique_words) / len(words) if words else 0.0


def calculate_similarity(text1: str, text2: str) -> float:
    embeddings = model.encode([text1, text2])
    return cosine_similarity([embeddings[0]], [embeddings[1]])[0][0]


def calculate_mad_score(ttr: float, similarity: float) -> float:
    return 0.3 * (1 - ttr) + 0.7 * similarity


def get_risk_level(mad_score: float) -> str:
    if mad_score > 0.7:
        return "High"
    elif 0.4 <= mad_score <= 0.7:
        return "Medium"
    return "Low"


# --- Data Processing ---
def process_data(file_obj, model_col: str, train_col: str, data_source: str) -> Tuple[
    Optional[str],
    Optional[bytes],
    Optional[str],
    Optional[str],
    Optional[float],
    Optional[float],
    Optional[float],
]:
    try:
        if not file_obj:
            return "Error: No file uploaded.", None, None, None, None, None, None

        df = uploaded_df.get("data")
        if df is None:
            return "Error: File not yet processed.", None, None, None, None, None, None

        if model_col not in df.columns or train_col not in df.columns:
            return (
                "Error: Selected columns not found in the file.",
                None,
                None,
                None,
                None,
                None,
                None,
            )

        output_text = " ".join(df[model_col].astype(str))
        train_text = " ".join(df[train_col].astype(str))

        ttr_output = calculate_ttr(output_text)
        ttr_train = calculate_ttr(train_text)
        similarity = calculate_similarity(output_text, train_text)
        mad_score = calculate_mad_score(ttr_output, similarity)
        risk_level = get_risk_level(mad_score)

        summary, details, explanation = render_score_card(
            ttr_output, ttr_train, similarity, mad_score, risk_level
        )
        evaluation_markdown = summary + details + explanation

        return (
            None,
            render_pipeline_graph(data_source),
            df.head().to_markdown(index=False, numalign="left", stralign="left"),
            evaluation_markdown,
            ttr_output,
            ttr_train,
            similarity,
        )

    except Exception as e:
        return f"An error occurred: {str(e)}", None, None, None, None, None, None


# --- Helpers ---
def update_dropdowns(file_obj) -> Tuple[gr.Dropdown, gr.Dropdown, str]:
    global uploaded_df
    if not file_obj:
        uploaded_df["data"] = None
        return (
            gr.update(choices=[], value=None),
            gr.update(choices=[], value=None),
            "No file uploaded.",
        )

    try:
        file_name = getattr(file_obj, "name", "")
        if file_name.endswith(".csv"):
            df = pd.read_csv(file_obj)
        elif file_name.endswith(".json"):
            df = pd.read_json(file_obj)
        else:
            return (
                gr.update(choices=[], value=None),
                gr.update(choices=[], value=None),
                "Invalid file type.",
            )

        uploaded_df["data"] = df
        preview = df.head().to_markdown(index=False, numalign="left", stralign="left")
        return (
            gr.update(choices=df.columns.tolist(), value=None),
            gr.update(choices=df.columns.tolist(), value=None),
            preview,
        )

    except Exception as e:
        return (
            gr.update(choices=[], value=None),
            gr.update(choices=[], value=None),
            f"Error reading file: {e}",
        )


def clear_all_fields():
    uploaded_df.clear()
    return (
        None,
        gr.update(choices=[], value=None),
        gr.update(choices=[], value=None),
        "",
        "",
        "",
        None,
        None,
        None,
        render_pipeline_graph("Synthetic Generated Data"),
    )


# --- Interface ---
def main_interface():
    css = """
    .gradio-container {
        background: linear-gradient(-45deg, #e0f7fa, #e1f5fe, #f1f8e9, #fff3e0);
        background-size: 400% 400%;
        animation: oceanWaves 20s ease infinite;
    }
    @keyframes oceanWaves {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    """

    with gr.Blocks(css=css, title="MADGuard AI Explorer") as interface:
        gr.HTML(render_page_header())

        gr.HTML(
            """
            <div style="text-align:center; margin-bottom: 20px;">
                <h3>πŸ“½οΈ How to Use MADGuard AI Explorer</h3>
                <iframe width="560" height="315" src="https://www.youtube.com/embed/qjMwvaBXQeY"
                        title="Tutorial Video" frameborder="0"
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowfullscreen></iframe>
            </div>
            """
        )

        gr.Markdown(
            """
            > 🧠 **MADGuard AI Explorer** helps simulate feedback loops in RAG pipelines and detect **Model Autophagy Disorder (MAD)**.

            - Compare **real vs. synthetic input effects**
            - Visualize the data flow
            - Upload your `.csv` or `.json` data
            - Get diagnostics based on lexical diversity and semantic similarity
            """
        )

        with gr.Accordion("πŸ“š Research Reference", open=False):
            gr.HTML(render_core_reference())

        gr.Markdown("## 1. Pipeline Simulation")
        data_source, description = render_pipeline(default="Synthetic Generated Data")
        gr.HTML(description)

        pipeline_output = gr.Image(type="filepath", label="Pipeline Graph")
        warning_output = gr.HTML()

        data_source.change(
            fn=render_pipeline_warning, inputs=data_source, outputs=warning_output
        )
        data_source.change(
            fn=render_pipeline_graph, inputs=data_source, outputs=pipeline_output
        )
        interface.load(
            fn=render_pipeline_graph, inputs=[data_source], outputs=[pipeline_output]
        )

        gr.Markdown("## 2. Upload CSV or JSON File")
        file_input = gr.File(
            file_types=[".csv", ".json"], label="Upload a CSV or JSON file"
        )
        clear_btn = gr.Button("🧹 Clear All")

        gr.Markdown(
            """
        πŸ“ **Note:**
        - **Model Output Column**: Model-generated responses/completions.
        - **Training Data Column**: Candidate future training input.
        """
        )

        with gr.Row():
            model_col_input = gr.Dropdown(
                choices=[], label="Select column for model output", interactive=True
            )
            train_col_input = gr.Dropdown(
                choices=[],
                label="Select column for future training data",
                interactive=True,
            )

        file_preview = gr.Markdown(label="πŸ“„ File Preview")
        output_markdown = gr.Markdown(label="πŸ” Evaluation Summary")

        with gr.Accordion("πŸ“‹ Research-Based Strategy Alignment", open=False):
            gr.HTML(render_strategy_alignment())

        with gr.Row():
            ttr_output_metric = gr.Number(label="Lexical Diversity (Output)")
            ttr_train_metric = gr.Number(label="Lexical Diversity (Training Set)")
            similarity_metric = gr.Number(label="Semantic Similarity (Cosine)")

        def handle_file_upload(file_obj, data_source_val):
            dropdowns = update_dropdowns(file_obj)
            graph = render_pipeline_graph(data_source_val)
            return *dropdowns, graph

        file_input.change(
            fn=handle_file_upload,
            inputs=[file_input, data_source],
            outputs=[model_col_input, train_col_input, file_preview, pipeline_output],
        )

        def process_and_generate(
            file_obj, model_col_val, train_col_val, data_source_val
        ):
            error, graph, preview, markdown, ttr_out, ttr_tr, sim = process_data(
                file_obj, model_col_val, train_col_val, data_source_val
            )
            if error:
                return error, graph, warning_output, preview, None, None, None, None
            return (
                "",
                graph,
                render_pipeline_warning(data_source_val),
                preview,
                markdown,
                ttr_out,
                ttr_tr,
                sim,
            )

        inputs = [file_input, model_col_input, train_col_input, data_source]
        outputs = [
            gr.Markdown(label="⚠️ Error Message"),
            pipeline_output,
            warning_output,
            file_preview,
            output_markdown,
            ttr_output_metric,
            ttr_train_metric,
            similarity_metric,
        ]

        clear_btn.click(
            fn=clear_all_fields,
            inputs=[],
            outputs=[
                file_input,
                model_col_input,
                train_col_input,
                file_preview,
                output_markdown,
                warning_output,
                ttr_output_metric,
                ttr_train_metric,
                similarity_metric,
                pipeline_output,
            ],
        )

        for input_component in inputs:
            input_component.change(
                fn=process_and_generate, inputs=inputs, outputs=outputs
            )

        gr.Markdown("---")
        gr.Markdown(
            """
            **Pro version coming soon:**
            - Bulk CSV uploads
            - Trend visualizations
            - One-click export of audit reports

            [πŸ“© Join the waitlist](https://docs.google.com/forms/d/e/1FAIpQLSfAPPC_Gm7DQElQSWGSnoB6T5hMxb_rXSu48OC8E6TNGZuKgQ/viewform?usp=sharing&ouid=118007615320536574300)
            """
        )

    return interface


if __name__ == "__main__":
    interface = main_interface()
    interface.launch(server_name="0.0.0.0", server_port=7860)