infinex commited on
Commit
16c5c77
Β·
verified Β·
1 Parent(s): e3c248b

Uploading dataset files from the local data folder.

Browse files
Files changed (1) hide show
  1. gepa.py +786 -0
gepa.py ADDED
@@ -0,0 +1,786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import dspy
3
+ import pandas as pd
4
+ import re
5
+ import httpx
6
+ import json
7
+ from openai import OpenAI
8
+ from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode
9
+ from typing import Optional, Dict, Any
10
+ import os
11
+
12
+ # --- Page Configuration ---
13
+ st. set_page_config(
14
+ layout="wide",
15
+ page_title="GEPA Regex Optimizer",
16
+ page_icon="🧬",
17
+ initial_sidebar_state="expanded"
18
+ )
19
+
20
+ # --- Session State Initialization ---
21
+ DEFAULT_STATE = {
22
+ 'dataset': None,
23
+ 'optimized_program': None,
24
+ 'optimization_history': [],
25
+ 'config': {
26
+ 'model_name': 'gpt-4o',
27
+ 'api_key': '',
28
+ 'base_url': 'https://api.openai.com/v1',
29
+ 'timeout': 30,
30
+ 'max_retries': 3,
31
+ 'temperature': 0.7,
32
+ 'max_tokens': 1024,
33
+ },
34
+ 'gepa_config': {
35
+ 'num_iterations': 5,
36
+ 'num_candidates': 3,
37
+ 'early_stopping_threshold': 0.95,
38
+ },
39
+ 'prompts': {
40
+ 'system_instruction': "You are a Regex Expert. Given the input text, provide a high-precision Python regex pattern to extract the target text.",
41
+ 'gepa_meta_prompt': "Focus on precision. If the feedback says the match was too broad, use more specific character classes or anchors. If it missed the target, suggest more flexible patterns.",
42
+ 'output_description': "A Python-compatible regular expression",
43
+ },
44
+ 'train_test_split': 0.8,
45
+ 'regex_flags': [],
46
+ }
47
+
48
+ for key, value in DEFAULT_STATE.items():
49
+ if key not in st.session_state:
50
+ st.session_state[key] = value
51
+
52
+
53
+ # --- Configuration Manager ---
54
+ class ConfigManager:
55
+ """Manages application configuration with persistence."""
56
+
57
+ CONFIG_FILE = "gepa_config.json"
58
+
59
+ @staticmethod
60
+ def save_config():
61
+ """Save current configuration to file."""
62
+ config_data = {
63
+ 'config': st.session_state. config,
64
+ 'gepa_config': st.session_state. gepa_config,
65
+ 'prompts': st.session_state.prompts,
66
+ 'train_test_split': st.session_state. train_test_split,
67
+ 'regex_flags': st. session_state.regex_flags,
68
+ }
69
+ try:
70
+ with open(ConfigManager.CONFIG_FILE, 'w') as f:
71
+ json.dump(config_data, f, indent=2)
72
+ return True
73
+ except Exception as e:
74
+ st.error(f"Failed to save config: {e}")
75
+ return False
76
+
77
+ @staticmethod
78
+ def load_config():
79
+ """Load configuration from file."""
80
+ try:
81
+ if os.path.exists(ConfigManager.CONFIG_FILE):
82
+ with open(ConfigManager.CONFIG_FILE, 'r') as f:
83
+ config_data = json.load(f)
84
+ for key, value in config_data. items():
85
+ if key in st.session_state:
86
+ if isinstance(value, dict):
87
+ st. session_state[key].update(value)
88
+ else:
89
+ st. session_state[key] = value
90
+ return True
91
+ except Exception as e:
92
+ st.warning(f"Failed to load config: {e}")
93
+ return False
94
+
95
+ @staticmethod
96
+ def reset_to_defaults():
97
+ """Reset all configuration to defaults."""
98
+ for key, value in DEFAULT_STATE.items():
99
+ if key not in ['dataset', 'optimized_program', 'optimization_history']:
100
+ st.session_state[key] = value. copy() if isinstance(value, (dict, list)) else value
101
+
102
+
103
+ # --- LLM Setup ---
104
+ def setup_dspy() -> bool:
105
+ """Configure DSPy with current settings."""
106
+ config = st.session_state. config
107
+ try:
108
+ http_client = httpx.Client(
109
+ timeout=config['timeout'],
110
+ limits=httpx.Limits(max_retries=config['max_retries'])
111
+ )
112
+
113
+ custom_openai_client = OpenAI(
114
+ api_key=config['api_key'] or os.getenv("OPENAI_API_KEY", "empty"),
115
+ base_url=config['base_url'] or None,
116
+ http_client=http_client
117
+ )
118
+
119
+ lm = dspy.LM(
120
+ model=config['model_name'],
121
+ client=custom_openai_client,
122
+ temperature=config['temperature'],
123
+ max_tokens=config['max_tokens']
124
+ )
125
+ dspy.configure(lm=lm)
126
+ return True
127
+ except Exception as e:
128
+ st. error(f"LLM Configuration Error: {e}")
129
+ return False
130
+
131
+
132
+ # --- Metric Function ---
133
+ def create_regex_metric(flags: list):
134
+ """Factory function to create metric with configurable regex flags."""
135
+
136
+ compiled_flags = 0
137
+ for flag in flags:
138
+ compiled_flags |= getattr(re, flag, 0)
139
+
140
+ def regex_metric_with_feedback(example, prediction, trace=None):
141
+ """GEPA Metric with rich feedback for regex optimization."""
142
+ target = example. ground_truth. strip()
143
+ raw_text = example. raw_text
144
+ pred_pattern = getattr(prediction, 'regex_pattern', '').strip()
145
+
146
+ # Handle missing output
147
+ if not pred_pattern:
148
+ feedback = (
149
+ f"No regex pattern provided. Target text: '{target}'. "
150
+ "Please output a valid Python regex string."
151
+ )
152
+ return dspy. Prediction(score=0.0, feedback=feedback)
153
+
154
+ # Syntax validation
155
+ try:
156
+ compiled = re.compile(pred_pattern, compiled_flags)
157
+ except re.error as e:
158
+ feedback = (
159
+ f"Invalid regex: '{pred_pattern}'. "
160
+ f"Error: {str(e)}. Check syntax and escape characters."
161
+ )
162
+ return dspy. Prediction(score=0.0, feedback=feedback)
163
+
164
+ # Match evaluation
165
+ match = compiled.search(raw_text)
166
+ extracted = match.group(0) if match else ""
167
+
168
+ if extracted == target:
169
+ return dspy.Prediction(
170
+ score=1.0,
171
+ feedback=f"Perfect match! Correctly extracted '{target}'."
172
+ )
173
+
174
+ # Failure analysis
175
+ score = 0.0
176
+ feedback = f"Pattern '{pred_pattern}' produced incorrect result.\n"
177
+
178
+ if not match:
179
+ feedback += f"NO MATCH found. Target: '{target}'."
180
+ elif target in extracted:
181
+ score = 0.3
182
+ feedback += (
183
+ f"TOO BROAD: Extracted '{extracted}' contains target '{target}' "
184
+ "plus extra characters. Use stricter boundaries or non-greedy quantifiers."
185
+ )
186
+ elif extracted in target:
187
+ score = 0.3
188
+ feedback += (
189
+ f"TOO NARROW: Extracted '{extracted}' but target is '{target}'. "
190
+ "Make pattern more inclusive."
191
+ )
192
+ else:
193
+ feedback += f"WRONG MATCH: Got '{extracted}' instead of '{target}'."
194
+
195
+ feedback += "\nAnalyze the target structure to isolate it uniquely."
196
+ return dspy.Prediction(score=score, feedback=feedback)
197
+
198
+ return regex_metric_with_feedback
199
+
200
+
201
+ # --- DSPy Program ---
202
+ class RegexSignature(dspy. Signature):
203
+ """Dynamic signature for regex generation."""
204
+ raw_text = dspy. InputField()
205
+ regex_pattern = dspy.OutputField()
206
+
207
+
208
+ class RegexGenerator(dspy.Module):
209
+ """Configurable regex generation module."""
210
+
211
+ def __init__(self, doc: str, output_desc: str):
212
+ super().__init__()
213
+ self.predictor = dspy.Predict(RegexSignature)
214
+ self.predictor.signature.__doc__ = doc
215
+ self.predictor.signature.regex_pattern. desc = output_desc
216
+
217
+ def forward(self, raw_text: str):
218
+ return self. predictor(raw_text=raw_text)
219
+
220
+
221
+ # --- Sidebar Configuration ---
222
+ def render_sidebar():
223
+ """Render the configuration sidebar."""
224
+ with st.sidebar:
225
+ st.title("βš™οΈ Configuration")
226
+
227
+ # Config management buttons
228
+ col1, col2, col3 = st.columns(3)
229
+ with col1:
230
+ if st.button("πŸ’Ύ Save", use_container_width=True):
231
+ if ConfigManager.save_config():
232
+ st.success("Saved!")
233
+ with col2:
234
+ if st.button("πŸ“‚ Load", use_container_width=True):
235
+ if ConfigManager.load_config():
236
+ st.success("Loaded!")
237
+ st.rerun()
238
+ with col3:
239
+ if st.button("πŸ”„ Reset", use_container_width=True):
240
+ ConfigManager.reset_to_defaults()
241
+ st.rerun()
242
+
243
+ st.divider()
244
+
245
+ # LLM Configuration
246
+ with st.expander("πŸ€– LLM Settings", expanded=True):
247
+ st.session_state.config['model_name'] = st.text_input(
248
+ "Model Name",
249
+ value=st.session_state.config['model_name'],
250
+ help="e.g., gpt-4o, gpt-3.5-turbo, claude-3-opus"
251
+ )
252
+
253
+ st.session_state.config['api_key'] = st.text_input(
254
+ "API Key",
255
+ value=st.session_state.config['api_key'],
256
+ type="password",
257
+ help="Leave empty to use OPENAI_API_KEY env var"
258
+ )
259
+
260
+ st.session_state.config['base_url'] = st.text_input(
261
+ "Base URL",
262
+ value=st.session_state.config['base_url'],
263
+ help="Custom API endpoint (e.g., for Azure, local models)"
264
+ )
265
+
266
+ col1, col2 = st.columns(2)
267
+ with col1:
268
+ st.session_state.config['timeout'] = st.number_input(
269
+ "Timeout (s)",
270
+ min_value=5,
271
+ max_value=300,
272
+ value=st.session_state.config['timeout']
273
+ )
274
+ with col2:
275
+ st.session_state.config['max_retries'] = st.number_input(
276
+ "Max Retries",
277
+ min_value=0,
278
+ max_value=10,
279
+ value=st.session_state.config['max_retries']
280
+ )
281
+
282
+ col1, col2 = st.columns(2)
283
+ with col1:
284
+ st.session_state.config['temperature'] = st.slider(
285
+ "Temperature",
286
+ min_value=0.0,
287
+ max_value=2.0,
288
+ value=st. session_state.config['temperature'],
289
+ step=0.1
290
+ )
291
+ with col2:
292
+ st.session_state.config['max_tokens'] = st.number_input(
293
+ "Max Tokens",
294
+ min_value=64,
295
+ max_value=8192,
296
+ value=st.session_state.config['max_tokens']
297
+ )
298
+
299
+ # GEPA Optimizer Settings
300
+ with st. expander("🧬 GEPA Optimizer", expanded=False):
301
+ st.session_state.gepa_config['num_iterations'] = st.slider(
302
+ "Iterations",
303
+ min_value=1,
304
+ max_value=20,
305
+ value=st. session_state.gepa_config['num_iterations'],
306
+ help="Number of optimization iterations"
307
+ )
308
+
309
+ st.session_state. gepa_config['num_candidates'] = st.slider(
310
+ "Candidates per Iteration",
311
+ min_value=1,
312
+ max_value=10,
313
+ value=st.session_state.gepa_config['num_candidates'],
314
+ help="Number of candidate patterns to evaluate"
315
+ )
316
+
317
+ st. session_state.gepa_config['early_stopping_threshold'] = st.slider(
318
+ "Early Stopping Threshold",
319
+ min_value=0.5,
320
+ max_value=1.0,
321
+ value=st.session_state.gepa_config['early_stopping_threshold'],
322
+ step=0.05,
323
+ help="Stop if this score is reached"
324
+ )
325
+
326
+ # Prompt Configuration
327
+ with st.expander("πŸ“ Prompts", expanded=False):
328
+ st.session_state.prompts['system_instruction'] = st.text_area(
329
+ "System Instruction",
330
+ value=st.session_state.prompts['system_instruction'],
331
+ height=100,
332
+ help="Initial instruction for regex generation"
333
+ )
334
+
335
+ st.session_state. prompts['gepa_meta_prompt'] = st.text_area(
336
+ "GEPA Evolution Prompt",
337
+ value=st.session_state.prompts['gepa_meta_prompt'],
338
+ height=100,
339
+ help="Instructions for GEPA's prompt evolution"
340
+ )
341
+
342
+ st.session_state. prompts['output_description'] = st. text_input(
343
+ "Output Field Description",
344
+ value=st.session_state.prompts['output_description'],
345
+ help="Description for the regex output field"
346
+ )
347
+
348
+ # Regex Configuration
349
+ with st. expander("πŸ”§ Regex Options", expanded=False):
350
+ flag_options = ['IGNORECASE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'ASCII']
351
+ st.session_state. regex_flags = st.multiselect(
352
+ "Regex Flags",
353
+ options=flag_options,
354
+ default=st.session_state. regex_flags,
355
+ help="Python regex flags to apply"
356
+ )
357
+
358
+ # Data Split Configuration
359
+ with st.expander("πŸ“Š Data Settings", expanded=False):
360
+ st.session_state.train_test_split = st.slider(
361
+ "Train/Validation Split",
362
+ min_value=0.5,
363
+ max_value=0.95,
364
+ value=st.session_state.train_test_split,
365
+ step=0.05,
366
+ help="Proportion of data for training"
367
+ )
368
+
369
+
370
+ # --- Main Application Tabs ---
371
+ def render_data_ingestion_tab():
372
+ """Render the data ingestion tab."""
373
+ st.header("πŸ“₯ Data Ingestion & Annotation")
374
+
375
+ col1, col2 = st.columns([2, 1])
376
+
377
+ with col1:
378
+ uploaded = st.file_uploader(
379
+ "Upload Dataset",
380
+ type=["csv", "json", "xlsx"],
381
+ help="CSV/JSON/Excel with 'text' column (ground_truth optional)"
382
+ )
383
+
384
+ with col2:
385
+ st.markdown("**Expected Format:**")
386
+ st.code("text,ground_truth\n'Sample text','expected'", language="csv")
387
+
388
+ if uploaded:
389
+ # Load based on file type
390
+ try:
391
+ if uploaded.name.endswith('.csv'):
392
+ df = pd.read_csv(uploaded)
393
+ elif uploaded.name. endswith('.json'):
394
+ df = pd.read_json(uploaded)
395
+ else:
396
+ df = pd.read_excel(uploaded)
397
+
398
+ # Ensure required columns
399
+ if 'text' not in df.columns:
400
+ st.error("Dataset must have a 'text' column.")
401
+ return
402
+
403
+ if 'ground_truth' not in df. columns:
404
+ df['ground_truth'] = ''
405
+
406
+ st.session_state. dataset = df
407
+
408
+ except Exception as e:
409
+ st.error(f"Failed to load file: {e}")
410
+ return
411
+
412
+ if st.session_state.dataset is not None:
413
+ df = st.session_state. dataset
414
+
415
+ st.subheader("πŸ“ Annotate Ground Truth")
416
+ st.caption("Edit the 'ground_truth' column to specify expected extractions.")
417
+
418
+ # Configure AgGrid
419
+ gb = GridOptionsBuilder.from_dataframe(df)
420
+ gb.configure_default_column(
421
+ resizable=True,
422
+ filterable=True,
423
+ sortable=True
424
+ )
425
+ gb.configure_column(
426
+ "text",
427
+ width=500,
428
+ wrapText=True,
429
+ autoHeight=True,
430
+ editable=False
431
+ )
432
+ gb.configure_column(
433
+ "ground_truth",
434
+ editable=True,
435
+ width=300,
436
+ cellStyle={'backgroundColor': '#fffde7'}
437
+ )
438
+ gb.configure_selection(
439
+ selection_mode='multiple',
440
+ use_checkbox=True
441
+ )
442
+ gb.configure_pagination(paginationAutoPageSize=False, paginationPageSize=10)
443
+
444
+ grid_response = AgGrid(
445
+ df,
446
+ gridOptions=gb.build(),
447
+ update_mode=GridUpdateMode.VALUE_CHANGED,
448
+ data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
449
+ fit_columns_on_grid_load=False,
450
+ theme='streamlit',
451
+ height=400
452
+ )
453
+
454
+ # Update session state with edited data
455
+ st.session_state. dataset = pd.DataFrame(grid_response['data'])
456
+
457
+ # Data statistics
458
+ col1, col2, col3 = st.columns(3)
459
+ annotated = (st.session_state. dataset['ground_truth'] != '').sum()
460
+ total = len(st. session_state.dataset)
461
+ train_size = int(total * st.session_state.train_test_split)
462
+
463
+ with col1:
464
+ st. metric("Total Samples", total)
465
+ with col2:
466
+ st.metric("Annotated", f"{annotated}/{total}")
467
+ with col3:
468
+ st.metric("Train/Val Split", f"{train_size}/{total - train_size}")
469
+
470
+ # Sample data preview
471
+ with st.expander("πŸ“‹ Sample Preview"):
472
+ st.dataframe(
473
+ st.session_state.dataset.head(5),
474
+ use_container_width=True
475
+ )
476
+
477
+
478
+ def render_optimization_tab():
479
+ """Render the optimization tab."""
480
+ st.header("🧬 GEPA Optimization")
481
+
482
+ if st.session_state. dataset is None:
483
+ st.warning("⚠️ Please upload and annotate data first.")
484
+ return
485
+
486
+ df = st.session_state.dataset
487
+ annotated_df = df[df['ground_truth'] != '']
488
+
489
+ if len(annotated_df) < 2:
490
+ st.warning("⚠️ Please annotate at least 2 samples.")
491
+ return
492
+
493
+ # Split configuration display
494
+ split_idx = int(len(annotated_df) * st.session_state.train_test_split)
495
+ train_df = annotated_df. iloc[:split_idx]
496
+ val_df = annotated_df.iloc[split_idx:]
497
+
498
+ col1, col2 = st.columns(2)
499
+ with col1:
500
+ st.info(f"πŸ“š Training samples: {len(train_df)}")
501
+ with col2:
502
+ st.info(f"πŸ§ͺ Validation samples: {len(val_df)}")
503
+
504
+ # Optimization controls
505
+ col1, col2, col3 = st.columns([1, 1, 2])
506
+
507
+ with col1:
508
+ run_button = st.button(
509
+ "πŸš€ Run Optimization",
510
+ type="primary",
511
+ use_container_width=True
512
+ )
513
+
514
+ with col2:
515
+ if st.button("πŸ”„ Reset Results", use_container_width=True):
516
+ st.session_state.optimized_program = None
517
+ st.session_state.optimization_history = []
518
+ st.rerun()
519
+
520
+ if run_button:
521
+ if not setup_dspy():
522
+ return
523
+
524
+ # Prepare training set
525
+ trainset = [
526
+ dspy.Example(
527
+ raw_text=row['text'],
528
+ ground_truth=row['ground_truth']
529
+ ).with_inputs('raw_text')
530
+ for _, row in train_df.iterrows()
531
+ ]
532
+
533
+ valset = [
534
+ dspy.Example(
535
+ raw_text=row['text'],
536
+ ground_truth=row['ground_truth']
537
+ ).with_inputs('raw_text')
538
+ for _, row in val_df.iterrows()
539
+ ]
540
+
541
+ # Progress tracking
542
+ progress_bar = st.progress(0)
543
+ status_text = st. empty()
544
+
545
+ try:
546
+ with st.spinner("🧬 GEPA is evolving regex patterns..."):
547
+ status_text.text("Initializing optimizer...")
548
+
549
+ optimizer = GEPA(
550
+ metric=create_regex_metric(st.session_state.regex_flags),
551
+ num_iterations=st. session_state.gepa_config['num_iterations'],
552
+ num_candidates=st.session_state.gepa_config['num_candidates'],
553
+ )
554
+
555
+ progress_bar.progress(20)
556
+ status_text.text("Creating initial program...")
557
+
558
+ program = RegexGenerator(
559
+ doc=st.session_state.prompts['system_instruction'],
560
+ output_desc=st. session_state.prompts['output_description']
561
+ )
562
+
563
+ progress_bar.progress(40)
564
+ status_text.text("Running optimization...")
565
+
566
+ optimized = optimizer.compile(
567
+ program,
568
+ trainset=trainset,
569
+ )
570
+
571
+ progress_bar.progress(80)
572
+ status_text.text("Evaluating on validation set...")
573
+
574
+ # Evaluate on validation set
575
+ metric_fn = create_regex_metric(st.session_state.regex_flags)
576
+ val_scores = []
577
+ for example in valset:
578
+ pred = optimized(raw_text=example. raw_text)
579
+ result = metric_fn(example, pred)
580
+ val_scores.append(result. score)
581
+
582
+ avg_score = sum(val_scores) / len(val_scores) if val_scores else 0
583
+
584
+ progress_bar. progress(100)
585
+ status_text.text("Complete!")
586
+
587
+ st.session_state. optimized_program = optimized
588
+ st.session_state.optimization_history.append({
589
+ 'score': avg_score,
590
+ 'prompt': optimized.predictor.signature.__doc__,
591
+ 'timestamp': pd.Timestamp.now()
592
+ })
593
+
594
+ st. success(f"βœ… Optimization Complete! Validation Score: {avg_score:.2%}")
595
+
596
+ except Exception as e:
597
+ st.error(f"Optimization failed: {e}")
598
+ return
599
+
600
+ # Display results
601
+ if st. session_state.optimized_program:
602
+ st.subheader("πŸ“Š Results")
603
+
604
+ with st.expander("πŸ” Evolved Prompt", expanded=True):
605
+ st.code(
606
+ st.session_state.optimized_program.predictor. signature.__doc__,
607
+ language="text"
608
+ )
609
+
610
+ # Optimization history
611
+ if st.session_state.optimization_history:
612
+ with st.expander("πŸ“ˆ Optimization History"):
613
+ history_df = pd. DataFrame(st.session_state. optimization_history)
614
+ st.dataframe(history_df, use_container_width=True)
615
+
616
+
617
+ def render_testing_tab():
618
+ """Render the testing tab."""
619
+ st.header("πŸ” Test & Validate")
620
+
621
+ if st.session_state.optimized_program is None:
622
+ st. warning("⚠️ Please run optimization first.")
623
+ return
624
+
625
+ # Single test
626
+ st.subheader("πŸ§ͺ Single Test")
627
+
628
+ test_input = st.text_area(
629
+ "Enter test text",
630
+ height=100,
631
+ placeholder="Paste text here to extract regex pattern..."
632
+ )
633
+
634
+ col1, col2 = st.columns([1, 3])
635
+ with col1:
636
+ test_button = st.button("▢️ Generate & Run", type="primary")
637
+
638
+ if test_button and test_input:
639
+ if not setup_dspy():
640
+ return
641
+
642
+ with st.spinner("Generating regex... "):
643
+ try:
644
+ result = st.session_state.optimized_program(raw_text=test_input)
645
+ pattern = result.regex_pattern
646
+
647
+ st.code(f"Generated Regex: {pattern}", language="regex")
648
+
649
+ # Compile and test
650
+ flags = 0
651
+ for flag in st.session_state.regex_flags:
652
+ flags |= getattr(re, flag, 0)
653
+
654
+ compiled = re.compile(pattern, flags)
655
+ matches = compiled.findall(test_input)
656
+
657
+ if matches:
658
+ st.success(f"βœ… Found {len(matches)} match(es):")
659
+ for i, match in enumerate(matches, 1):
660
+ st.markdown(f"**Match {i}:** `{match}`")
661
+
662
+ # Highlight matches in text
663
+ highlighted = test_input
664
+ for match in matches:
665
+ highlighted = highlighted.replace(
666
+ match,
667
+ f"**: green[{match}]**"
668
+ )
669
+ st.markdown("**Highlighted text:**")
670
+ st.markdown(highlighted)
671
+ else:
672
+ st. warning("No matches found.")
673
+
674
+ except re.error as e:
675
+ st.error(f"Invalid regex generated: {e}")
676
+ except Exception as e:
677
+ st.error(f"Error: {e}")
678
+
679
+ st.divider()
680
+
681
+ # Batch testing
682
+ st. subheader("πŸ“‹ Batch Testing")
683
+
684
+ batch_file = st.file_uploader(
685
+ "Upload test data (CSV with 'text' column)",
686
+ type=["csv"],
687
+ key="batch_test"
688
+ )
689
+
690
+ if batch_file:
691
+ test_df = pd. read_csv(batch_file)
692
+
693
+ if 'text' not in test_df. columns:
694
+ st.error("CSV must have 'text' column.")
695
+ return
696
+
697
+ if st.button("πŸš€ Run Batch Test"):
698
+ if not setup_dspy():
699
+ return
700
+
701
+ results = []
702
+ progress = st.progress(0)
703
+
704
+ for i, row in test_df.iterrows():
705
+ try:
706
+ result = st.session_state.optimized_program(raw_text=row['text'])
707
+ pattern = result.regex_pattern
708
+
709
+ flags = 0
710
+ for flag in st.session_state. regex_flags:
711
+ flags |= getattr(re, flag, 0)
712
+
713
+ match = re.search(pattern, row['text'], flags)
714
+ extracted = match.group(0) if match else ""
715
+
716
+ results.append({
717
+ 'text': row['text'][: 100] + '...' if len(row['text']) > 100 else row['text'],
718
+ 'pattern': pattern,
719
+ 'extracted': extracted,
720
+ 'success': bool(match)
721
+ })
722
+ except Exception as e:
723
+ results.append({
724
+ 'text': row['text'][:100] + '...',
725
+ 'pattern': 'ERROR',
726
+ 'extracted': str(e),
727
+ 'success': False
728
+ })
729
+
730
+ progress. progress((i + 1) / len(test_df))
731
+
732
+ results_df = pd. DataFrame(results)
733
+
734
+ # Summary metrics
735
+ success_rate = results_df['success']. mean()
736
+ col1, col2 = st.columns(2)
737
+ with col1:
738
+ st.metric("Success Rate", f"{success_rate:.1%}")
739
+ with col2:
740
+ st.metric("Total Tests", len(results_df))
741
+
742
+ # Results table
743
+ st.dataframe(results_df, use_container_width=True)
744
+
745
+ # Download results
746
+ csv = results_df. to_csv(index=False)
747
+ st.download_button(
748
+ "πŸ“₯ Download Results",
749
+ csv,
750
+ "batch_test_results. csv",
751
+ "text/csv"
752
+ )
753
+
754
+
755
+ # --- Main Application ---
756
+ def main():
757
+ render_sidebar()
758
+
759
+ st.title("🧬 GEPA Regex Optimizer")
760
+ st.caption("Automated regex generation with DSPy and evolutionary optimization")
761
+
762
+ tab1, tab2, tab3 = st.tabs([
763
+ "πŸ“₯ Data Ingestion",
764
+ "🧬 Optimization",
765
+ "πŸ” Testing"
766
+ ])
767
+
768
+ with tab1:
769
+ render_data_ingestion_tab()
770
+
771
+ with tab2:
772
+ render_optimization_tab()
773
+
774
+ with tab3:
775
+ render_testing_tab()
776
+
777
+ # Footer
778
+ st.divider()
779
+ st.caption(
780
+ "Built with Streamlit, DSPy, and GEPA | "
781
+ "Configuration is auto-saved in the sidebar"
782
+ )
783
+
784
+
785
+ if __name__ == "__main__":
786
+ main()