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

Uploading dataset files from the local data folder.

Browse files
gepa_app.py ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import dspy
3
+ import pandas as pd
4
+ import numpy as np
5
+ import re
6
+ import httpx
7
+ import json
8
+ from openai import OpenAI
9
+ from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode
10
+ from typing import Optional, Dict, Any, List
11
+ import os
12
+
13
+ # --- Page Configuration ---
14
+ st. set_page_config(
15
+ layout="wide",
16
+ page_title="GEPA Regex Optimizer",
17
+ page_icon="🧬",
18
+ initial_sidebar_state="expanded"
19
+ )
20
+
21
+ # --- Session State Initialization ---
22
+ DEFAULT_STATE = {
23
+ 'dataset': None,
24
+ 'selected_indices': [], # Track selected row indices for training
25
+ 'optimized_program': None,
26
+ 'optimization_history': [],
27
+ 'config': {
28
+ 'model_name': 'gpt-4o',
29
+ 'api_key': '',
30
+ 'base_url': 'https://api.openai.com/v1',
31
+ 'timeout': 30,
32
+ 'max_retries': 3,
33
+ 'temperature': 0.7,
34
+ 'max_tokens': 1024,
35
+ },
36
+ 'gepa_config': {
37
+ 'num_iterations': 5,
38
+ 'num_candidates': 3,
39
+ 'early_stopping_threshold': 0.95,
40
+ },
41
+ 'prompts': {
42
+ 'system_instruction': "You are a Regex Expert. Given the input text, provide a high-precision Python regex pattern to extract the target text.",
43
+ '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.",
44
+ 'output_description': "A Python-compatible regular expression",
45
+ },
46
+ 'train_test_split': 0.8,
47
+ 'regex_flags': [],
48
+ }
49
+
50
+ for key, value in DEFAULT_STATE.items():
51
+ if key not in st.session_state:
52
+ st.session_state[key] = value
53
+
54
+
55
+ # --- Configuration Manager ---
56
+ class ConfigManager:
57
+ """Manages application configuration with persistence."""
58
+
59
+ CONFIG_FILE = "gepa_config.json"
60
+
61
+ @staticmethod
62
+ def save_config():
63
+ """Save current configuration to file."""
64
+ config_data = {
65
+ 'config': st.session_state. config,
66
+ 'gepa_config': st.session_state. gepa_config,
67
+ 'prompts': st.session_state.prompts,
68
+ 'train_test_split': st.session_state. train_test_split,
69
+ 'regex_flags': st. session_state.regex_flags,
70
+ }
71
+ try:
72
+ with open(ConfigManager.CONFIG_FILE, 'w') as f:
73
+ json.dump(config_data, f, indent=2)
74
+ return True
75
+ except Exception as e:
76
+ st.error(f"Failed to save config: {e}")
77
+ return False
78
+
79
+ @staticmethod
80
+ def load_config():
81
+ """Load configuration from file."""
82
+ try:
83
+ if os.path.exists(ConfigManager.CONFIG_FILE):
84
+ with open(ConfigManager.CONFIG_FILE, 'r') as f:
85
+ config_data = json.load(f)
86
+ for key, value in config_data. items():
87
+ if key in st.session_state:
88
+ if isinstance(value, dict):
89
+ st. session_state[key].update(value)
90
+ else:
91
+ st. session_state[key] = value
92
+ return True
93
+ except Exception as e:
94
+ st.warning(f"Failed to load config: {e}")
95
+ return False
96
+
97
+ @staticmethod
98
+ def reset_to_defaults():
99
+ """Reset all configuration to defaults."""
100
+ for key, value in DEFAULT_STATE.items():
101
+ if key not in ['dataset', 'optimized_program', 'optimization_history']:
102
+ st.session_state[key] = value. copy() if isinstance(value, (dict, list)) else value
103
+
104
+
105
+ # --- LLM Setup ---
106
+ def setup_dspy() -> bool:
107
+ """Configure DSPy with current settings."""
108
+ config = st.session_state. config
109
+ try:
110
+ http_client = httpx.Client(
111
+ timeout=config['timeout'],
112
+ limits=httpx.Limits(max_retries=config['max_retries'])
113
+ )
114
+
115
+ custom_openai_client = OpenAI(
116
+ api_key=config['api_key'] or os.getenv("OPENAI_API_KEY", "empty"),
117
+ base_url=config['base_url'] or None,
118
+ http_client=http_client
119
+ )
120
+
121
+ lm = dspy.LM(
122
+ model=config['model_name'],
123
+ client=custom_openai_client,
124
+ temperature=config['temperature'],
125
+ max_tokens=config['max_tokens']
126
+ )
127
+ dspy.configure(lm=lm)
128
+ return True
129
+ except Exception as e:
130
+ st. error(f"LLM Configuration Error: {e}")
131
+ return False
132
+
133
+
134
+ # --- Metric Function ---
135
+ def create_regex_metric(flags: list):
136
+ """Factory function to create metric with configurable regex flags."""
137
+
138
+ compiled_flags = 0
139
+ for flag in flags:
140
+ compiled_flags |= getattr(re, flag, 0)
141
+
142
+ def regex_metric_with_feedback(example, prediction, trace=None):
143
+ """GEPA Metric with rich feedback for regex optimization."""
144
+ target = example. ground_truth. strip()
145
+ raw_text = example. raw_text
146
+ pred_pattern = getattr(prediction, 'regex_pattern', '').strip()
147
+
148
+ # Handle missing output
149
+ if not pred_pattern:
150
+ feedback = (
151
+ f"No regex pattern provided. Target text: '{target}'. "
152
+ "Please output a valid Python regex string."
153
+ )
154
+ return dspy. Prediction(score=0.0, feedback=feedback)
155
+
156
+ # Syntax validation
157
+ try:
158
+ compiled = re.compile(pred_pattern, compiled_flags)
159
+ except re.error as e:
160
+ feedback = (
161
+ f"Invalid regex: '{pred_pattern}'. "
162
+ f"Error: {str(e)}. Check syntax and escape characters."
163
+ )
164
+ return dspy. Prediction(score=0.0, feedback=feedback)
165
+
166
+ # Match evaluation
167
+ match = compiled.search(raw_text)
168
+ extracted = match.group(0) if match else ""
169
+
170
+ if extracted == target:
171
+ return dspy.Prediction(
172
+ score=1.0,
173
+ feedback=f"Perfect match! Correctly extracted '{target}'."
174
+ )
175
+
176
+ # Failure analysis
177
+ score = 0.0
178
+ feedback = f"Pattern '{pred_pattern}' produced incorrect result.\n"
179
+
180
+ if not match:
181
+ feedback += f"NO MATCH found. Target: '{target}'."
182
+ elif target in extracted:
183
+ score = 0.3
184
+ feedback += (
185
+ f"TOO BROAD: Extracted '{extracted}' contains target '{target}' "
186
+ "plus extra characters. Use stricter boundaries or non-greedy quantifiers."
187
+ )
188
+ elif extracted in target:
189
+ score = 0.3
190
+ feedback += (
191
+ f"TOO NARROW: Extracted '{extracted}' but target is '{target}'. "
192
+ "Make pattern more inclusive."
193
+ )
194
+ else:
195
+ feedback += f"WRONG MATCH: Got '{extracted}' instead of '{target}'."
196
+
197
+ feedback += "\nAnalyze the target structure to isolate it uniquely."
198
+ return dspy.Prediction(score=score, feedback=feedback)
199
+
200
+ return regex_metric_with_feedback
201
+
202
+
203
+ # --- DSPy Program ---
204
+ class RegexSignature(dspy. Signature):
205
+ """Dynamic signature for regex generation."""
206
+ raw_text = dspy. InputField()
207
+ regex_pattern = dspy.OutputField()
208
+
209
+
210
+ class RegexGenerator(dspy.Module):
211
+ """Configurable regex generation module."""
212
+
213
+ def __init__(self, doc: str, output_desc: str):
214
+ super().__init__()
215
+ self.predictor = dspy.Predict(RegexSignature)
216
+ self.predictor.signature.__doc__ = doc
217
+ self.predictor.signature.regex_pattern. desc = output_desc
218
+
219
+ def forward(self, raw_text: str):
220
+ return self. predictor(raw_text=raw_text)
221
+
222
+
223
+ # --- Sidebar Configuration ---
224
+ def render_sidebar():
225
+ """Render the configuration sidebar."""
226
+ with st.sidebar:
227
+ st.title("βš™οΈ Configuration")
228
+
229
+ # Config management buttons
230
+ col1, col2, col3 = st.columns(3)
231
+ with col1:
232
+ if st.button("πŸ’Ύ Save", use_container_width=True):
233
+ if ConfigManager.save_config():
234
+ st.success("Saved!")
235
+ with col2:
236
+ if st.button("πŸ“‚ Load", use_container_width=True):
237
+ if ConfigManager.load_config():
238
+ st.success("Loaded!")
239
+ st.rerun()
240
+ with col3:
241
+ if st.button("πŸ”„ Reset", use_container_width=True):
242
+ ConfigManager.reset_to_defaults()
243
+ st.rerun()
244
+
245
+ st.divider()
246
+
247
+ # LLM Configuration
248
+ with st.expander("πŸ€– LLM Settings", expanded=True):
249
+ st.session_state.config['model_name'] = st.text_input(
250
+ "Model Name",
251
+ value=st.session_state.config['model_name'],
252
+ help="e.g., gpt-4o, gpt-3.5-turbo, claude-3-opus"
253
+ )
254
+
255
+ st.session_state.config['api_key'] = st.text_input(
256
+ "API Key",
257
+ value=st.session_state.config['api_key'],
258
+ type="password",
259
+ help="Leave empty to use OPENAI_API_KEY env var"
260
+ )
261
+
262
+ st.session_state.config['base_url'] = st.text_input(
263
+ "Base URL",
264
+ value=st.session_state.config['base_url'],
265
+ help="Custom API endpoint (e.g., for Azure, local models)"
266
+ )
267
+
268
+ col1, col2 = st.columns(2)
269
+ with col1:
270
+ st.session_state.config['timeout'] = st.number_input(
271
+ "Timeout (s)",
272
+ min_value=5,
273
+ max_value=300,
274
+ value=st.session_state.config['timeout']
275
+ )
276
+ with col2:
277
+ st.session_state.config['max_retries'] = st.number_input(
278
+ "Max Retries",
279
+ min_value=0,
280
+ max_value=10,
281
+ value=st.session_state.config['max_retries']
282
+ )
283
+
284
+ col1, col2 = st.columns(2)
285
+ with col1:
286
+ st.session_state.config['temperature'] = st.slider(
287
+ "Temperature",
288
+ min_value=0.0,
289
+ max_value=2.0,
290
+ value=st. session_state.config['temperature'],
291
+ step=0.1
292
+ )
293
+ with col2:
294
+ st.session_state.config['max_tokens'] = st.number_input(
295
+ "Max Tokens",
296
+ min_value=64,
297
+ max_value=8192,
298
+ value=st.session_state.config['max_tokens']
299
+ )
300
+
301
+ # GEPA Optimizer Settings
302
+ with st. expander("🧬 GEPA Optimizer", expanded=False):
303
+ st.session_state.gepa_config['num_iterations'] = st.slider(
304
+ "Iterations",
305
+ min_value=1,
306
+ max_value=20,
307
+ value=st. session_state.gepa_config['num_iterations'],
308
+ help="Number of optimization iterations"
309
+ )
310
+
311
+ st.session_state. gepa_config['num_candidates'] = st.slider(
312
+ "Candidates per Iteration",
313
+ min_value=1,
314
+ max_value=10,
315
+ value=st.session_state.gepa_config['num_candidates'],
316
+ help="Number of candidate patterns to evaluate"
317
+ )
318
+
319
+ st. session_state.gepa_config['early_stopping_threshold'] = st.slider(
320
+ "Early Stopping Threshold",
321
+ min_value=0.5,
322
+ max_value=1.0,
323
+ value=st.session_state.gepa_config['early_stopping_threshold'],
324
+ step=0.05,
325
+ help="Stop if this score is reached"
326
+ )
327
+
328
+ # Prompt Configuration
329
+ with st.expander("πŸ“ Prompts", expanded=False):
330
+ st.session_state.prompts['system_instruction'] = st.text_area(
331
+ "System Instruction",
332
+ value=st.session_state.prompts['system_instruction'],
333
+ height=100,
334
+ help="Initial instruction for regex generation"
335
+ )
336
+
337
+ st.session_state. prompts['gepa_meta_prompt'] = st.text_area(
338
+ "GEPA Evolution Prompt",
339
+ value=st.session_state.prompts['gepa_meta_prompt'],
340
+ height=100,
341
+ help="Instructions for GEPA's prompt evolution"
342
+ )
343
+
344
+ st.session_state. prompts['output_description'] = st. text_input(
345
+ "Output Field Description",
346
+ value=st.session_state.prompts['output_description'],
347
+ help="Description for the regex output field"
348
+ )
349
+
350
+ # Regex Configuration
351
+ with st. expander("πŸ”§ Regex Options", expanded=False):
352
+ flag_options = ['IGNORECASE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'ASCII']
353
+ st.session_state. regex_flags = st.multiselect(
354
+ "Regex Flags",
355
+ options=flag_options,
356
+ default=st.session_state. regex_flags,
357
+ help="Python regex flags to apply"
358
+ )
359
+
360
+ # Data Split Configuration
361
+ with st.expander("πŸ“Š Data Settings", expanded=False):
362
+ st.session_state.train_test_split = st.slider(
363
+ "Train/Validation Split",
364
+ min_value=0.5,
365
+ max_value=0.95,
366
+ value=st.session_state.train_test_split,
367
+ step=0.05,
368
+ help="Proportion of data for training"
369
+ )
370
+
371
+
372
+ # --- Stratified Sampling Utility ---
373
+ def stratified_train_val_split(
374
+ df: pd.DataFrame,
375
+ train_ratio: float = 0.8,
376
+ stratify_column: str = 'ground_truth',
377
+ random_state: int = 42
378
+ ) -> tuple:
379
+ """
380
+ Perform stratified train/validation split.
381
+ Groups samples by ground_truth pattern and splits proportionally.
382
+ """
383
+ np.random.seed(random_state)
384
+
385
+ # Create stratification groups based on ground_truth patterns
386
+ # Use first 50 chars of ground_truth as group key to handle similar patterns
387
+ df = df.copy()
388
+ df['_strat_key'] = df[stratify_column].apply(
389
+ lambda x: str(x)[:50] if pd.notna(x) and x != '' else '_empty_'
390
+ )
391
+
392
+ train_indices = []
393
+ val_indices = []
394
+
395
+ # Split each stratum
396
+ for _, group in df.groupby('_strat_key'):
397
+ indices = group.index.tolist()
398
+ np.random.shuffle(indices)
399
+
400
+ split_idx = max(1, int(len(indices) * train_ratio))
401
+
402
+ # Ensure at least one sample in validation if group has multiple samples
403
+ if len(indices) > 1 and split_idx == len(indices):
404
+ split_idx = len(indices) - 1
405
+
406
+ train_indices.extend(indices[:split_idx])
407
+ val_indices.extend(indices[split_idx:])
408
+
409
+ train_df = df.loc[train_indices].drop(columns=['_strat_key'])
410
+ val_df = df.loc[val_indices].drop(columns=['_strat_key']) if val_indices else pd.DataFrame()
411
+
412
+ return train_df, val_df
413
+
414
+
415
+ # --- Data Persistence ---
416
+ def save_annotated_data(df: pd.DataFrame, selected_indices: List[int], filepath: str) -> bool:
417
+ """Save annotated data with selection state."""
418
+ try:
419
+ # Add selection column
420
+ save_df = df.copy()
421
+ save_df['_selected'] = save_df.index.isin(selected_indices)
422
+
423
+ if filepath.endswith('.json'):
424
+ save_df.to_json(filepath, orient='records', indent=2)
425
+ else:
426
+ save_df.to_csv(filepath, index=False)
427
+ return True
428
+ except Exception as e:
429
+ st.error(f"Failed to save data: {e}")
430
+ return False
431
+
432
+
433
+ def load_annotated_data(filepath: str) -> tuple:
434
+ """Load annotated data with selection state."""
435
+ try:
436
+
437
+ df = pd.read_csv(filepath)
438
+
439
+ # Extract selection state if present
440
+ selected_indices = []
441
+ if '_selected' in df.columns:
442
+ selected_indices = df[df['_selected'] == True].index.tolist()
443
+ df = df.drop(columns=['_selected'])
444
+
445
+ # Ensure required columns
446
+ if 'text' not in df.columns:
447
+ raise ValueError("Dataset must have a 'text' column.")
448
+
449
+ if 'ground_truth' not in df.columns:
450
+ df['ground_truth'] = ''
451
+
452
+ return df, selected_indices
453
+ except Exception as e:
454
+ st.error(f"Failed to load data: {e}")
455
+ return None, []
456
+
457
+
458
+ # --- Main Application Tabs ---
459
+ def render_data_ingestion_tab():
460
+ """Render the data ingestion tab."""
461
+ st.header("πŸ“₯ Data Ingestion & Annotation")
462
+
463
+ # File upload section
464
+ col1, col2 = st.columns([2, 1])
465
+
466
+ with col1:
467
+ uploaded = st.file_uploader(
468
+ "Upload Dataset",
469
+ type=["csv", "json", "xlsx"],
470
+ help="CSV/JSON/Excel with 'text' column (ground_truth optional, _selected for pre-selected rows)"
471
+ )
472
+
473
+ with col2:
474
+ st.markdown("**Expected Format:**")
475
+ st.code("text,ground_truth,_selected\n'Sample text','expected',true", language="csv")
476
+
477
+ if uploaded:
478
+ # Load based on file type
479
+ try:
480
+ df, selected_indices = load_annotated_data(uploaded)
481
+ if df is not None:
482
+ st.session_state.dataset = df.reset_index(drop=True)
483
+ st.session_state.selected_indices = selected_indices
484
+ st.success(f"βœ… Loaded {len(df)} samples ({len(selected_indices)} pre-selected)")
485
+ except Exception as e:
486
+ st.error(f"Failed to load file: {e}")
487
+ return
488
+
489
+ if st.session_state.dataset is not None:
490
+ df = st.session_state.dataset.copy()
491
+
492
+ st.subheader("πŸ“ Annotate Ground Truth")
493
+ st.caption("Edit 'ground_truth' column and select rows (checkbox) to include in training/validation.")
494
+
495
+ # Prepare pre-selected rows for AgGrid
496
+ pre_selected_rows = st.session_state.get('selected_indices', [])
497
+
498
+ # Configure AgGrid
499
+ gb = GridOptionsBuilder.from_dataframe(df)
500
+ gb.configure_default_column(
501
+ resizable=True,
502
+ filterable=True,
503
+ sortable=True
504
+ )
505
+ gb.configure_column(
506
+ "text",
507
+ width=500,
508
+ wrapText=True,
509
+ autoHeight=True,
510
+ editable=False
511
+ )
512
+ gb.configure_column(
513
+ "ground_truth",
514
+ editable=True,
515
+ width=300,
516
+ cellStyle={'backgroundColor': '#fffde7'}
517
+ )
518
+ gb.configure_selection(
519
+ selection_mode='multiple',
520
+ use_checkbox=True,
521
+ pre_selected_rows=pre_selected_rows
522
+ )
523
+ gb.configure_pagination(paginationAutoPageSize=False, paginationPageSize=10)
524
+
525
+ grid_response = AgGrid(
526
+ df,
527
+ gridOptions=gb.build(),
528
+ update_mode=GridUpdateMode.MODEL_CHANGED | GridUpdateMode.SELECTION_CHANGED,
529
+ data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
530
+ fit_columns_on_grid_load=False,
531
+ theme='streamlit',
532
+ height=400,
533
+ key='annotation_grid'
534
+ )
535
+
536
+ # Update session state with edited data
537
+ st.session_state.dataset = pd.DataFrame(grid_response['data'])
538
+
539
+ # Update selected indices from grid selection
540
+ selected_rows = grid_response.get('selected_rows', [])
541
+ if selected_rows is not None and len(selected_rows) > 0:
542
+ # Get indices of selected rows
543
+ selected_df = pd.DataFrame(selected_rows)
544
+ if not selected_df.empty:
545
+ # Match selected rows back to original indices
546
+ st.session_state.selected_indices = selected_df.index.tolist()
547
+ else:
548
+ st.session_state.selected_indices = []
549
+
550
+ st.divider()
551
+
552
+ # Save/Export section
553
+ st.subheader("πŸ’Ύ Save Annotated Data")
554
+ col1, col2, col3 = st.columns([2, 1, 1])
555
+
556
+ with col1:
557
+ save_filename = st.text_input(
558
+ "Filename",
559
+ value="annotated_data.csv",
560
+ help="Enter filename (.csv or .json)"
561
+ )
562
+
563
+ with col2:
564
+ if st.button("πŸ’Ύ Save to File", use_container_width=True):
565
+ if save_annotated_data(
566
+ st.session_state.dataset,
567
+ st.session_state.selected_indices,
568
+ save_filename
569
+ ):
570
+ st.success(f"βœ… Saved to {save_filename}")
571
+
572
+ with col3:
573
+ # Download button
574
+ save_df = st.session_state.dataset.copy()
575
+ save_df['_selected'] = save_df.index.isin(st.session_state.selected_indices)
576
+
577
+ csv_data = save_df.to_csv(index=False)
578
+ st.download_button(
579
+ "πŸ“₯ Download CSV",
580
+ csv_data,
581
+ file_name="annotated_data.csv",
582
+ mime="text/csv",
583
+ use_container_width=True
584
+ )
585
+
586
+ st.divider()
587
+
588
+ # Data statistics
589
+ st.subheader("πŸ“Š Data Statistics")
590
+
591
+ total = len(st.session_state.dataset)
592
+ annotated = (st.session_state.dataset['ground_truth'].astype(str) != '').sum()
593
+ selected_count = len(st.session_state.selected_indices)
594
+
595
+ # Calculate train/val split preview
596
+ selected_df = st.session_state.dataset.iloc[st.session_state.selected_indices] if st.session_state.selected_indices else pd.DataFrame()
597
+ selected_annotated = selected_df[selected_df['ground_truth'].astype(str) != ''] if not selected_df.empty else pd.DataFrame()
598
+
599
+ if len(selected_annotated) >= 2:
600
+ train_df, val_df = stratified_train_val_split(
601
+ selected_annotated,
602
+ train_ratio=st.session_state.train_test_split
603
+ )
604
+ train_size = len(train_df)
605
+ val_size = len(val_df)
606
+ else:
607
+ train_size = 0
608
+ val_size = 0
609
+
610
+ col1, col2, col3, col4 = st.columns(4)
611
+
612
+ with col1:
613
+ st.metric("Total Samples", total)
614
+ with col2:
615
+ st.metric("Annotated", f"{annotated}/{total}")
616
+ with col3:
617
+ st.metric("Selected", selected_count, help="Rows selected for training/validation")
618
+ with col4:
619
+ st.metric("Train/Val", f"{train_size}/{val_size}", help="Stratified split of selected & annotated rows")
620
+
621
+ # Selection guidance
622
+ if selected_count == 0:
623
+ st.info("πŸ’‘ Select rows using checkboxes to include them in training/validation.")
624
+ elif len(selected_annotated) < 2:
625
+ st.warning("⚠️ Please select at least 2 annotated rows for training.")
626
+
627
+ # Stratification preview
628
+ if len(selected_annotated) >= 2:
629
+ with st.expander("πŸ“ˆ Stratification Preview"):
630
+ # Show distribution of ground_truth patterns
631
+ pattern_counts = selected_annotated['ground_truth'].apply(
632
+ lambda x: str(x)[:30] + '...' if len(str(x)) > 30 else str(x)
633
+ ).value_counts()
634
+
635
+ st.markdown("**Ground Truth Pattern Distribution:**")
636
+ st.bar_chart(pattern_counts)
637
+
638
+ st.caption(f"Training: {train_size} samples, Validation: {val_size} samples")
639
+
640
+ # Sample data preview
641
+ with st.expander("πŸ“‹ Sample Preview"):
642
+ st.dataframe(
643
+ st.session_state.dataset.head(5),
644
+ use_container_width=True
645
+ )
646
+
647
+
648
+ def render_optimization_tab():
649
+ """Render the optimization tab."""
650
+ st.header("🧬 GEPA Optimization")
651
+
652
+ if st.session_state.dataset is None:
653
+ st.warning("⚠️ Please upload and annotate data first.")
654
+ return
655
+
656
+ df = st.session_state.dataset
657
+ selected_indices = st.session_state.get('selected_indices', [])
658
+
659
+ # Use selected rows if available, otherwise fall back to all annotated rows
660
+ if selected_indices:
661
+ selected_df = df.iloc[selected_indices]
662
+ annotated_df = selected_df[selected_df['ground_truth'].astype(str) != '']
663
+ use_selection = True
664
+ else:
665
+ annotated_df = df[df['ground_truth'].astype(str) != '']
666
+ use_selection = False
667
+
668
+ if len(annotated_df) < 2:
669
+ if use_selection:
670
+ st.warning("⚠️ Please select and annotate at least 2 samples in the Data Ingestion tab.")
671
+ else:
672
+ st.warning("⚠️ Please annotate at least 2 samples or select rows for training.")
673
+ return
674
+
675
+ # Stratified split
676
+ train_df, val_df = stratified_train_val_split(
677
+ annotated_df,
678
+ train_ratio=st.session_state.train_test_split
679
+ )
680
+
681
+ col1, col2, col3 = st.columns(3)
682
+ with col1:
683
+ st.info(f"πŸ“š Training samples: {len(train_df)}")
684
+ with col2:
685
+ st.info(f"πŸ§ͺ Validation samples: {len(val_df)}")
686
+ with col3:
687
+ if use_selection:
688
+ st.success("βœ… Using selected rows")
689
+ else:
690
+ st.warning("⚠️ Using all annotated rows")
691
+
692
+ # Optimization controls
693
+ col1, col2, col3 = st.columns([1, 1, 2])
694
+
695
+ with col1:
696
+ run_button = st.button(
697
+ "πŸš€ Run Optimization",
698
+ type="primary",
699
+ use_container_width=True
700
+ )
701
+
702
+ with col2:
703
+ if st.button("πŸ”„ Reset Results", use_container_width=True):
704
+ st.session_state.optimized_program = None
705
+ st.session_state.optimization_history = []
706
+ st.rerun()
707
+
708
+ if run_button:
709
+ if not setup_dspy():
710
+ return
711
+
712
+ # Prepare training set
713
+ trainset = [
714
+ dspy.Example(
715
+ raw_text=row['text'],
716
+ ground_truth=row['ground_truth']
717
+ ).with_inputs('raw_text')
718
+ for _, row in train_df.iterrows()
719
+ ]
720
+
721
+ valset = [
722
+ dspy.Example(
723
+ raw_text=row['text'],
724
+ ground_truth=row['ground_truth']
725
+ ).with_inputs('raw_text')
726
+ for _, row in val_df.iterrows()
727
+ ]
728
+
729
+ # Progress tracking
730
+ progress_bar = st.progress(0)
731
+ status_text = st. empty()
732
+
733
+ try:
734
+ with st.spinner("🧬 GEPA is evolving regex patterns..."):
735
+ status_text.text("Initializing optimizer...")
736
+
737
+ optimizer = GEPA(
738
+ metric=create_regex_metric(st.session_state.regex_flags),
739
+ num_iterations=st. session_state.gepa_config['num_iterations'],
740
+ num_candidates=st.session_state.gepa_config['num_candidates'],
741
+ )
742
+
743
+ progress_bar.progress(20)
744
+ status_text.text("Creating initial program...")
745
+
746
+ program = RegexGenerator(
747
+ doc=st.session_state.prompts['system_instruction'],
748
+ output_desc=st. session_state.prompts['output_description']
749
+ )
750
+
751
+ progress_bar.progress(40)
752
+ status_text.text("Running optimization...")
753
+
754
+ optimized = optimizer.compile(
755
+ program,
756
+ trainset=trainset,
757
+ )
758
+
759
+ progress_bar.progress(80)
760
+ status_text.text("Evaluating on validation set...")
761
+
762
+ # Evaluate on validation set
763
+ metric_fn = create_regex_metric(st.session_state.regex_flags)
764
+ val_scores = []
765
+ for example in valset:
766
+ pred = optimized(raw_text=example. raw_text)
767
+ result = metric_fn(example, pred)
768
+ val_scores.append(result. score)
769
+
770
+ avg_score = sum(val_scores) / len(val_scores) if val_scores else 0
771
+
772
+ progress_bar. progress(100)
773
+ status_text.text("Complete!")
774
+
775
+ st.session_state. optimized_program = optimized
776
+ st.session_state.optimization_history.append({
777
+ 'score': avg_score,
778
+ 'prompt': optimized.predictor.signature.__doc__,
779
+ 'timestamp': pd.Timestamp.now()
780
+ })
781
+
782
+ st. success(f"βœ… Optimization Complete! Validation Score: {avg_score:.2%}")
783
+
784
+ except Exception as e:
785
+ st.error(f"Optimization failed: {e}")
786
+ return
787
+
788
+ # Display results
789
+ if st. session_state.optimized_program:
790
+ st.subheader("πŸ“Š Results")
791
+
792
+ with st.expander("πŸ” Evolved Prompt", expanded=True):
793
+ st.code(
794
+ st.session_state.optimized_program.predictor. signature.__doc__,
795
+ language="text"
796
+ )
797
+
798
+ # Optimization history
799
+ if st.session_state.optimization_history:
800
+ with st.expander("πŸ“ˆ Optimization History"):
801
+ history_df = pd. DataFrame(st.session_state. optimization_history)
802
+ st.dataframe(history_df, use_container_width=True)
803
+
804
+
805
+ def render_testing_tab():
806
+ """Render the testing tab."""
807
+ st.header("πŸ” Test & Validate")
808
+
809
+ if st.session_state.optimized_program is None:
810
+ st. warning("⚠️ Please run optimization first.")
811
+ return
812
+
813
+ # Single test
814
+ st.subheader("πŸ§ͺ Single Test")
815
+
816
+ test_input = st.text_area(
817
+ "Enter test text",
818
+ height=100,
819
+ placeholder="Paste text here to extract regex pattern..."
820
+ )
821
+
822
+ col1, col2 = st.columns([1, 3])
823
+ with col1:
824
+ test_button = st.button("▢️ Generate & Run", type="primary")
825
+
826
+ if test_button and test_input:
827
+ if not setup_dspy():
828
+ return
829
+
830
+ with st.spinner("Generating regex... "):
831
+ try:
832
+ result = st.session_state.optimized_program(raw_text=test_input)
833
+ pattern = result.regex_pattern
834
+
835
+ st.code(f"Generated Regex: {pattern}", language="regex")
836
+
837
+ # Compile and test
838
+ flags = 0
839
+ for flag in st.session_state.regex_flags:
840
+ flags |= getattr(re, flag, 0)
841
+
842
+ compiled = re.compile(pattern, flags)
843
+ matches = compiled.findall(test_input)
844
+
845
+ if matches:
846
+ st.success(f"βœ… Found {len(matches)} match(es):")
847
+ for i, match in enumerate(matches, 1):
848
+ st.markdown(f"**Match {i}:** `{match}`")
849
+
850
+ # Highlight matches in text
851
+ highlighted = test_input
852
+ for match in matches:
853
+ highlighted = highlighted.replace(
854
+ match,
855
+ f"**: green[{match}]**"
856
+ )
857
+ st.markdown("**Highlighted text:**")
858
+ st.markdown(highlighted)
859
+ else:
860
+ st. warning("No matches found.")
861
+
862
+ except re.error as e:
863
+ st.error(f"Invalid regex generated: {e}")
864
+ except Exception as e:
865
+ st.error(f"Error: {e}")
866
+
867
+ st.divider()
868
+
869
+ # Batch testing
870
+ st. subheader("πŸ“‹ Batch Testing")
871
+
872
+ batch_file = st.file_uploader(
873
+ "Upload test data (CSV with 'text' column)",
874
+ type=["csv"],
875
+ key="batch_test"
876
+ )
877
+
878
+ if batch_file:
879
+ test_df = pd. read_csv(batch_file)
880
+
881
+ if 'text' not in test_df. columns:
882
+ st.error("CSV must have 'text' column.")
883
+ return
884
+
885
+ if st.button("πŸš€ Run Batch Test"):
886
+ if not setup_dspy():
887
+ return
888
+
889
+ results = []
890
+ progress = st.progress(0)
891
+
892
+ for i, row in test_df.iterrows():
893
+ try:
894
+ result = st.session_state.optimized_program(raw_text=row['text'])
895
+ pattern = result.regex_pattern
896
+
897
+ flags = 0
898
+ for flag in st.session_state. regex_flags:
899
+ flags |= getattr(re, flag, 0)
900
+
901
+ match = re.search(pattern, row['text'], flags)
902
+ extracted = match.group(0) if match else ""
903
+
904
+ results.append({
905
+ 'text': row['text'][: 100] + '...' if len(row['text']) > 100 else row['text'],
906
+ 'pattern': pattern,
907
+ 'extracted': extracted,
908
+ 'success': bool(match)
909
+ })
910
+ except Exception as e:
911
+ results.append({
912
+ 'text': row['text'][:100] + '...',
913
+ 'pattern': 'ERROR',
914
+ 'extracted': str(e),
915
+ 'success': False
916
+ })
917
+
918
+ progress. progress((i + 1) / len(test_df))
919
+
920
+ results_df = pd. DataFrame(results)
921
+
922
+ # Summary metrics
923
+ success_rate = results_df['success']. mean()
924
+ col1, col2 = st.columns(2)
925
+ with col1:
926
+ st.metric("Success Rate", f"{success_rate:.1%}")
927
+ with col2:
928
+ st.metric("Total Tests", len(results_df))
929
+
930
+ # Results table
931
+ st.dataframe(results_df, use_container_width=True)
932
+
933
+ # Download results
934
+ csv = results_df. to_csv(index=False)
935
+ st.download_button(
936
+ "πŸ“₯ Download Results",
937
+ csv,
938
+ "batch_test_results. csv",
939
+ "text/csv"
940
+ )
941
+
942
+
943
+ # --- Main Application ---
944
+ def main():
945
+ render_sidebar()
946
+
947
+ st.title("🧬 GEPA Regex Optimizer")
948
+ st.caption("Automated regex generation with DSPy and evolutionary optimization")
949
+
950
+ tab1, tab2, tab3 = st.tabs([
951
+ "πŸ“₯ Data Ingestion",
952
+ "🧬 Optimization",
953
+ "πŸ” Testing"
954
+ ])
955
+
956
+ with tab1:
957
+ render_data_ingestion_tab()
958
+
959
+ with tab2:
960
+ render_optimization_tab()
961
+
962
+ with tab3:
963
+ render_testing_tab()
964
+
965
+ # Footer
966
+ st.divider()
967
+ st.caption(
968
+ "Built with Streamlit, DSPy, and GEPA | "
969
+ "Configuration is auto-saved in the sidebar"
970
+ )
971
+
972
+
973
+ if __name__ == "__main__":
974
+ main()
gepa_app.py:Zone.Identifier ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [ZoneTransfer]
2
+ ZoneId=3
3
+ ReferrerUrl=https://web.telegram.org/k/
4
+ HostUrl=https://web.telegram.org/k/d/61795611
textgrad_app.py ADDED
@@ -0,0 +1,1138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import re
5
+ import httpx
6
+ import json
7
+ import os
8
+ import time
9
+ import logging
10
+ from typing import Optional, List
11
+ from openai import OpenAI
12
+
13
+ import textgrad as tg
14
+ from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode
15
+
16
+ # Configure logging
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # --- Page Configuration ---
21
+ st.set_page_config(
22
+ layout="wide",
23
+ page_title="TextGrad Regex Optimizer",
24
+ page_icon="πŸ“",
25
+ initial_sidebar_state="expanded"
26
+ )
27
+
28
+ # --- Session State Initialization ---
29
+ DEFAULT_STATE = {
30
+ 'dataset': None,
31
+ 'selected_indices': [], # Track selected row indices for training
32
+ 'optimized_prompt': None,
33
+ 'optimization_history': [],
34
+ 'config': {
35
+ 'model_name': 'gpt-4o-mini',
36
+ 'critic_model': 'gpt-4o',
37
+ 'api_key': '',
38
+ 'base_url': 'https://api.openai.com/v1',
39
+ 'timeout': 30,
40
+ 'max_retries': 3,
41
+ 'temperature': 0.7,
42
+ 'max_tokens': 1024,
43
+ },
44
+ 'textgrad_config': {
45
+ 'num_iterations': 5,
46
+ 'batch_size': 3,
47
+ 'early_stopping_threshold': 0.95,
48
+ },
49
+ 'prompts': {
50
+ 'system_instruction': "You are a Regex Expert. Given the input text, provide a high-precision Python regex pattern to extract the target text. Output only the regex pattern, nothing else.",
51
+ 'output_description': "A Python-compatible regular expression",
52
+ },
53
+ 'train_test_split': 0.8,
54
+ 'regex_flags': [],
55
+ }
56
+
57
+ for key, value in DEFAULT_STATE.items():
58
+ if key not in st.session_state:
59
+ st.session_state[key] = value
60
+
61
+
62
+ # --- Configuration Manager ---
63
+ class ConfigManager:
64
+ """Manages application configuration with persistence."""
65
+
66
+ CONFIG_FILE = "textgrad_config.json"
67
+
68
+ @staticmethod
69
+ def save_config():
70
+ """Save current configuration to file."""
71
+ config_data = {
72
+ 'config': st.session_state.config,
73
+ 'textgrad_config': st.session_state.textgrad_config,
74
+ 'prompts': st.session_state.prompts,
75
+ 'train_test_split': st.session_state.train_test_split,
76
+ 'regex_flags': st.session_state.regex_flags,
77
+ }
78
+ try:
79
+ with open(ConfigManager.CONFIG_FILE, 'w') as f:
80
+ json.dump(config_data, f, indent=2)
81
+ return True
82
+ except Exception as e:
83
+ st.error(f"Failed to save config: {e}")
84
+ return False
85
+
86
+ @staticmethod
87
+ def load_config():
88
+ """Load configuration from file."""
89
+ try:
90
+ if os.path.exists(ConfigManager.CONFIG_FILE):
91
+ with open(ConfigManager.CONFIG_FILE, 'r') as f:
92
+ config_data = json.load(f)
93
+ for key, value in config_data.items():
94
+ if key in st.session_state:
95
+ if isinstance(value, dict):
96
+ st.session_state[key].update(value)
97
+ else:
98
+ st.session_state[key] = value
99
+ return True
100
+ except Exception as e:
101
+ st.warning(f"Failed to load config: {e}")
102
+ return False
103
+
104
+ @staticmethod
105
+ def reset_to_defaults():
106
+ """Reset all configuration to defaults."""
107
+ for key, value in DEFAULT_STATE.items():
108
+ if key not in ['dataset', 'optimized_prompt', 'optimization_history']:
109
+ st.session_state[key] = value.copy() if isinstance(value, (dict, list)) else value
110
+
111
+
112
+ # --- TextGrad Setup ---
113
+ def setup_textgrad() -> bool:
114
+ """Configure TextGrad with current settings."""
115
+ config = st.session_state.config
116
+ try:
117
+ api_key = config['api_key'] or os.getenv("OPENAI_API_KEY", "")
118
+ if not api_key:
119
+ st.error("Please provide an OpenAI API key.")
120
+ return False
121
+
122
+ os.environ["OPENAI_API_KEY"] = api_key
123
+
124
+ # Get engines
125
+ target_engine = tg.get_engine(config['model_name'])
126
+ critic_engine = tg.get_engine(config['critic_model'])
127
+ tg.set_backward_engine(critic_engine)
128
+
129
+ st.session_state['target_engine'] = target_engine
130
+ st.session_state['critic_engine'] = critic_engine
131
+
132
+ return True
133
+ except Exception as e:
134
+ st.error(f"TextGrad Configuration Error: {e}")
135
+ return False
136
+
137
+
138
+ # --- TextGrad Model Wrapper ---
139
+ class RegexGeneratorModel:
140
+ """TextGrad model wrapper for regex generation task."""
141
+
142
+ def __init__(self, system_prompt: tg.Variable, engine):
143
+ self.system_prompt = system_prompt
144
+ self.llm_engine = engine
145
+ self.model = tg.BlackboxLLM(engine=engine, system_prompt=system_prompt)
146
+
147
+ def __call__(self, user_message: tg.Variable) -> tg.Variable:
148
+ """Forward pass through the LLM with current system prompt."""
149
+ return self.model(user_message)
150
+
151
+ def parameters(self):
152
+ """Return parameters for the optimizer."""
153
+ return [self.system_prompt]
154
+
155
+
156
+ # --- Loss Function ---
157
+ def create_regex_loss_fn(raw_text: str, target: str, regex_flags: list) -> tg.TextLoss:
158
+ """
159
+ Create a TextGrad loss function that evaluates regex quality.
160
+ Returns textual feedback that guides optimization.
161
+ """
162
+ flags_str = ", ".join(regex_flags) if regex_flags else "None"
163
+
164
+ evaluation_instruction = f"""Evaluate the quality of this regex pattern for extracting specific text.
165
+
166
+ Input Text: {raw_text[:500]}{'...' if len(raw_text) > 500 else ''}
167
+ Target Text to Extract: {target}
168
+ Regex Flags Applied: {flags_str}
169
+
170
+ Evaluation Criteria:
171
+ 1. Does the regex pattern correctly extract the target text from the input?
172
+ 2. Is the pattern precise (not too broad, capturing extra text)?
173
+ 3. Is the pattern syntax valid for Python's re module?
174
+ 4. Is the pattern robust (handles edge cases appropriately)?
175
+
176
+ Provide specific, actionable feedback on how to improve the system prompt to generate better regex patterns.
177
+ Focus on:
178
+ - What instructions would help generate more precise patterns
179
+ - How to avoid common regex mistakes
180
+ - Ways to improve pattern matching accuracy
181
+ Be constructive and specific about what changes would improve performance."""
182
+
183
+ return tg.TextLoss(evaluation_instruction)
184
+
185
+
186
+ # --- Simple Metric ---
187
+ def evaluate_regex_simple(pattern: str, raw_text: str, target: str, flags: list) -> float:
188
+ """
189
+ Simple scoring function for regex evaluation.
190
+ Returns a score between 0 and 1.
191
+ """
192
+ if not pattern:
193
+ return 0.0
194
+
195
+ # Compile flags
196
+ compiled_flags = 0
197
+ for flag in flags:
198
+ compiled_flags |= getattr(re, flag, 0)
199
+
200
+ try:
201
+ compiled = re.compile(pattern.strip(), compiled_flags)
202
+ except re.error:
203
+ return 0.0
204
+
205
+ match = compiled.search(raw_text)
206
+ if not match:
207
+ return 0.0
208
+
209
+ extracted = match.group(0)
210
+
211
+ if extracted == target:
212
+ return 1.0
213
+ elif target in extracted:
214
+ # Too broad - partial credit
215
+ return 0.3
216
+ elif extracted in target:
217
+ # Too narrow - partial credit
218
+ return 0.3
219
+ else:
220
+ return 0.1
221
+
222
+
223
+ # --- Sidebar Configuration ---
224
+ def render_sidebar():
225
+ """Render the configuration sidebar."""
226
+ with st.sidebar:
227
+ st.title("βš™οΈ Configuration")
228
+
229
+ # Config management buttons
230
+ col1, col2, col3 = st.columns(3)
231
+ with col1:
232
+ if st.button("πŸ’Ύ Save", use_container_width=True):
233
+ if ConfigManager.save_config():
234
+ st.success("Saved!")
235
+ with col2:
236
+ if st.button("πŸ“‚ Load", use_container_width=True):
237
+ if ConfigManager.load_config():
238
+ st.success("Loaded!")
239
+ st.rerun()
240
+ with col3:
241
+ if st.button("πŸ”„ Reset", use_container_width=True):
242
+ ConfigManager.reset_to_defaults()
243
+ st.rerun()
244
+
245
+ st.divider()
246
+
247
+ # LLM Configuration
248
+ with st.expander("πŸ€– LLM Settings", expanded=True):
249
+ st.session_state.config['model_name'] = st.text_input(
250
+ "Target Model",
251
+ value=st.session_state.config['model_name'],
252
+ help="Model to optimize (e.g., gpt-4o-mini)"
253
+ )
254
+
255
+ st.session_state.config['critic_model'] = st.text_input(
256
+ "Critic Model",
257
+ value=st.session_state.config['critic_model'],
258
+ help="Model for generating gradients (e.g., gpt-4o)"
259
+ )
260
+
261
+ st.session_state.config['api_key'] = st.text_input(
262
+ "API Key",
263
+ value=st.session_state.config['api_key'],
264
+ type="password",
265
+ help="Leave empty to use OPENAI_API_KEY env var"
266
+ )
267
+
268
+ st.session_state.config['base_url'] = st.text_input(
269
+ "Base URL",
270
+ value=st.session_state.config['base_url'],
271
+ help="Custom API endpoint"
272
+ )
273
+
274
+ col1, col2 = st.columns(2)
275
+ with col1:
276
+ st.session_state.config['timeout'] = st.number_input(
277
+ "Timeout (s)",
278
+ min_value=5,
279
+ max_value=300,
280
+ value=st.session_state.config['timeout']
281
+ )
282
+ with col2:
283
+ st.session_state.config['max_retries'] = st.number_input(
284
+ "Max Retries",
285
+ min_value=0,
286
+ max_value=10,
287
+ value=st.session_state.config['max_retries']
288
+ )
289
+
290
+ col1, col2 = st.columns(2)
291
+ with col1:
292
+ st.session_state.config['temperature'] = st.slider(
293
+ "Temperature",
294
+ min_value=0.0,
295
+ max_value=2.0,
296
+ value=st.session_state.config['temperature'],
297
+ step=0.1
298
+ )
299
+ with col2:
300
+ st.session_state.config['max_tokens'] = st.number_input(
301
+ "Max Tokens",
302
+ min_value=64,
303
+ max_value=8192,
304
+ value=st.session_state.config['max_tokens']
305
+ )
306
+
307
+ # TextGrad Optimizer Settings
308
+ with st.expander("πŸ“ TextGrad Optimizer", expanded=False):
309
+ st.session_state.textgrad_config['num_iterations'] = st.slider(
310
+ "Iterations",
311
+ min_value=1,
312
+ max_value=20,
313
+ value=st.session_state.textgrad_config['num_iterations'],
314
+ help="Number of optimization iterations"
315
+ )
316
+
317
+ st.session_state.textgrad_config['batch_size'] = st.slider(
318
+ "Batch Size",
319
+ min_value=1,
320
+ max_value=10,
321
+ value=st.session_state.textgrad_config['batch_size'],
322
+ help="Number of examples per batch"
323
+ )
324
+
325
+ st.session_state.textgrad_config['early_stopping_threshold'] = st.slider(
326
+ "Early Stopping Threshold",
327
+ min_value=0.5,
328
+ max_value=1.0,
329
+ value=st.session_state.textgrad_config['early_stopping_threshold'],
330
+ step=0.05,
331
+ help="Stop if this score is reached"
332
+ )
333
+
334
+ # Prompt Configuration
335
+ with st.expander("πŸ“ Prompts", expanded=False):
336
+ st.session_state.prompts['system_instruction'] = st.text_area(
337
+ "System Instruction",
338
+ value=st.session_state.prompts['system_instruction'],
339
+ height=150,
340
+ help="Initial system prompt for regex generation"
341
+ )
342
+
343
+ st.session_state.prompts['output_description'] = st.text_input(
344
+ "Output Field Description",
345
+ value=st.session_state.prompts['output_description'],
346
+ help="Description for the regex output field"
347
+ )
348
+
349
+ # Regex Configuration
350
+ with st.expander("πŸ”§ Regex Options", expanded=False):
351
+ flag_options = ['IGNORECASE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'ASCII']
352
+ st.session_state.regex_flags = st.multiselect(
353
+ "Regex Flags",
354
+ options=flag_options,
355
+ default=st.session_state.regex_flags,
356
+ help="Python regex flags to apply"
357
+ )
358
+
359
+ # Data Split Configuration
360
+ with st.expander("πŸ“Š Data Settings", expanded=False):
361
+ st.session_state.train_test_split = st.slider(
362
+ "Train/Validation Split",
363
+ min_value=0.5,
364
+ max_value=0.95,
365
+ value=st.session_state.train_test_split,
366
+ step=0.05,
367
+ help="Proportion of data for training"
368
+ )
369
+
370
+
371
+ # --- Stratified Sampling Utility ---
372
+ def stratified_train_val_split(
373
+ df: pd.DataFrame,
374
+ train_ratio: float = 0.8,
375
+ stratify_column: str = 'ground_truth',
376
+ random_state: int = 42
377
+ ) -> tuple:
378
+ """
379
+ Perform stratified train/validation split.
380
+ Groups samples by ground_truth pattern and splits proportionally.
381
+ """
382
+ np.random.seed(random_state)
383
+
384
+ df = df.copy()
385
+ df['_strat_key'] = df[stratify_column].apply(
386
+ lambda x: str(x)[:50] if pd.notna(x) and x != '' else '_empty_'
387
+ )
388
+
389
+ train_indices = []
390
+ val_indices = []
391
+
392
+ for _, group in df.groupby('_strat_key'):
393
+ indices = group.index.tolist()
394
+ np.random.shuffle(indices)
395
+
396
+ split_idx = max(1, int(len(indices) * train_ratio))
397
+
398
+ if len(indices) > 1 and split_idx == len(indices):
399
+ split_idx = len(indices) - 1
400
+
401
+ train_indices.extend(indices[:split_idx])
402
+ val_indices.extend(indices[split_idx:])
403
+
404
+ train_df = df.loc[train_indices].drop(columns=['_strat_key'])
405
+ val_df = df.loc[val_indices].drop(columns=['_strat_key']) if val_indices else pd.DataFrame()
406
+
407
+ return train_df, val_df
408
+
409
+
410
+ # --- Data Persistence ---
411
+ def save_annotated_data(df: pd.DataFrame, selected_indices: List[int], filepath: str) -> bool:
412
+ """Save annotated data with selection state."""
413
+ try:
414
+ save_df = df.copy()
415
+ save_df['_selected'] = save_df.index.isin(selected_indices)
416
+
417
+ if filepath.endswith('.json'):
418
+ save_df.to_json(filepath, orient='records', indent=2)
419
+ else:
420
+ save_df.to_csv(filepath, index=False)
421
+ return True
422
+ except Exception as e:
423
+ st.error(f"Failed to save data: {e}")
424
+ return False
425
+
426
+
427
+ def load_annotated_data(filepath: str) -> tuple:
428
+ """Load annotated data with selection state."""
429
+ try:
430
+ df = pd.read_csv(filepath)
431
+
432
+ selected_indices = []
433
+ if '_selected' in df.columns:
434
+ selected_indices = df[df['_selected'] == True].index.tolist()
435
+ df = df.drop(columns=['_selected'])
436
+
437
+ if 'text' not in df.columns:
438
+ raise ValueError("Dataset must have a 'text' column.")
439
+
440
+ if 'ground_truth' not in df.columns:
441
+ df['ground_truth'] = ''
442
+
443
+ return df, selected_indices
444
+ except Exception as e:
445
+ st.error(f"Failed to load data: {e}")
446
+ return None, []
447
+
448
+
449
+ # --- Main Application Tabs ---
450
+ def render_data_ingestion_tab():
451
+ """Render the data ingestion tab."""
452
+ st.header("πŸ“₯ Data Ingestion & Annotation")
453
+
454
+ col1, col2 = st.columns([2, 1])
455
+
456
+ with col1:
457
+ uploaded = st.file_uploader(
458
+ "Upload Dataset",
459
+ type=["csv", "json", "xlsx"],
460
+ help="CSV/JSON/Excel with 'text' column (ground_truth optional, _selected for pre-selected rows)"
461
+ )
462
+
463
+ with col2:
464
+ st.markdown("**Expected Format:**")
465
+ st.code("text,ground_truth,_selected\n'Sample text','expected',true", language="csv")
466
+
467
+ if uploaded:
468
+ try:
469
+ df, selected_indices = load_annotated_data(uploaded)
470
+ if df is not None:
471
+ st.session_state.dataset = df.reset_index(drop=True)
472
+ st.session_state.selected_indices = selected_indices
473
+ st.success(f"βœ… Loaded {len(df)} samples ({len(selected_indices)} pre-selected)")
474
+ except Exception as e:
475
+ st.error(f"Failed to load file: {e}")
476
+ return
477
+
478
+ if st.session_state.dataset is not None:
479
+ df = st.session_state.dataset.copy()
480
+
481
+ st.subheader("πŸ“ Annotate Ground Truth")
482
+ st.caption("Edit 'ground_truth' column and select rows (checkbox) to include in training/validation.")
483
+
484
+ pre_selected_rows = st.session_state.get('selected_indices', [])
485
+
486
+ # Configure AgGrid
487
+ gb = GridOptionsBuilder.from_dataframe(df)
488
+ gb.configure_default_column(
489
+ resizable=True,
490
+ filterable=True,
491
+ sortable=True
492
+ )
493
+ gb.configure_column(
494
+ "text",
495
+ width=500,
496
+ wrapText=True,
497
+ autoHeight=True,
498
+ editable=False
499
+ )
500
+ gb.configure_column(
501
+ "ground_truth",
502
+ editable=True,
503
+ width=300,
504
+ cellStyle={'backgroundColor': '#fffde7'}
505
+ )
506
+ gb.configure_selection(
507
+ selection_mode='multiple',
508
+ use_checkbox=True,
509
+ pre_selected_rows=pre_selected_rows
510
+ )
511
+ gb.configure_pagination(paginationAutoPageSize=False, paginationPageSize=10)
512
+
513
+ grid_response = AgGrid(
514
+ df,
515
+ gridOptions=gb.build(),
516
+ update_mode=GridUpdateMode.MODEL_CHANGED | GridUpdateMode.SELECTION_CHANGED,
517
+ data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
518
+ fit_columns_on_grid_load=False,
519
+ theme='streamlit',
520
+ height=400,
521
+ key='annotation_grid'
522
+ )
523
+
524
+ st.session_state.dataset = pd.DataFrame(grid_response['data'])
525
+
526
+ selected_rows = grid_response.get('selected_rows', [])
527
+ if selected_rows is not None and len(selected_rows) > 0:
528
+ selected_df = pd.DataFrame(selected_rows)
529
+ if not selected_df.empty:
530
+ st.session_state.selected_indices = selected_df.index.tolist()
531
+ else:
532
+ st.session_state.selected_indices = []
533
+
534
+ st.divider()
535
+
536
+ # Save/Export section
537
+ st.subheader("πŸ’Ύ Save Annotated Data")
538
+ col1, col2, col3 = st.columns([2, 1, 1])
539
+
540
+ with col1:
541
+ save_filename = st.text_input(
542
+ "Filename",
543
+ value="annotated_data.csv",
544
+ help="Enter filename (.csv or .json)"
545
+ )
546
+
547
+ with col2:
548
+ if st.button("πŸ’Ύ Save to File", use_container_width=True):
549
+ if save_annotated_data(
550
+ st.session_state.dataset,
551
+ st.session_state.selected_indices,
552
+ save_filename
553
+ ):
554
+ st.success(f"βœ… Saved to {save_filename}")
555
+
556
+ with col3:
557
+ save_df = st.session_state.dataset.copy()
558
+ save_df['_selected'] = save_df.index.isin(st.session_state.selected_indices)
559
+
560
+ csv_data = save_df.to_csv(index=False)
561
+ st.download_button(
562
+ "πŸ“₯ Download CSV",
563
+ csv_data,
564
+ file_name="annotated_data.csv",
565
+ mime="text/csv",
566
+ use_container_width=True
567
+ )
568
+
569
+ st.divider()
570
+
571
+ # Data statistics
572
+ st.subheader("πŸ“Š Data Statistics")
573
+
574
+ total = len(st.session_state.dataset)
575
+ annotated = (st.session_state.dataset['ground_truth'].astype(str) != '').sum()
576
+ selected_count = len(st.session_state.selected_indices)
577
+
578
+ selected_df = st.session_state.dataset.iloc[st.session_state.selected_indices] if st.session_state.selected_indices else pd.DataFrame()
579
+ selected_annotated = selected_df[selected_df['ground_truth'].astype(str) != ''] if not selected_df.empty else pd.DataFrame()
580
+
581
+ if len(selected_annotated) >= 2:
582
+ train_df, val_df = stratified_train_val_split(
583
+ selected_annotated,
584
+ train_ratio=st.session_state.train_test_split
585
+ )
586
+ train_size = len(train_df)
587
+ val_size = len(val_df)
588
+ else:
589
+ train_size = 0
590
+ val_size = 0
591
+
592
+ col1, col2, col3, col4 = st.columns(4)
593
+
594
+ with col1:
595
+ st.metric("Total Samples", total)
596
+ with col2:
597
+ st.metric("Annotated", f"{annotated}/{total}")
598
+ with col3:
599
+ st.metric("Selected", selected_count, help="Rows selected for training/validation")
600
+ with col4:
601
+ st.metric("Train/Val", f"{train_size}/{val_size}", help="Stratified split of selected & annotated rows")
602
+
603
+ if selected_count == 0:
604
+ st.info("πŸ’‘ Select rows using checkboxes to include them in training/validation.")
605
+ elif len(selected_annotated) < 2:
606
+ st.warning("⚠️ Please select at least 2 annotated rows for training.")
607
+
608
+ if len(selected_annotated) >= 2:
609
+ with st.expander("πŸ“ˆ Stratification Preview"):
610
+ pattern_counts = selected_annotated['ground_truth'].apply(
611
+ lambda x: str(x)[:30] + '...' if len(str(x)) > 30 else str(x)
612
+ ).value_counts()
613
+
614
+ st.markdown("**Ground Truth Pattern Distribution:**")
615
+ st.bar_chart(pattern_counts)
616
+
617
+ st.caption(f"Training: {train_size} samples, Validation: {val_size} samples")
618
+
619
+ with st.expander("πŸ“‹ Sample Preview"):
620
+ st.dataframe(
621
+ st.session_state.dataset.head(5),
622
+ use_container_width=True
623
+ )
624
+
625
+
626
+ def render_optimization_tab():
627
+ """Render the optimization tab."""
628
+ st.header("πŸ“ TextGrad Optimization")
629
+
630
+ if st.session_state.dataset is None:
631
+ st.warning("⚠️ Please upload and annotate data first.")
632
+ return
633
+
634
+ df = st.session_state.dataset
635
+ selected_indices = st.session_state.get('selected_indices', [])
636
+
637
+ if selected_indices:
638
+ selected_df = df.iloc[selected_indices]
639
+ annotated_df = selected_df[selected_df['ground_truth'].astype(str) != '']
640
+ use_selection = True
641
+ else:
642
+ annotated_df = df[df['ground_truth'].astype(str) != '']
643
+ use_selection = False
644
+
645
+ if len(annotated_df) < 2:
646
+ if use_selection:
647
+ st.warning("⚠️ Please select and annotate at least 2 samples in the Data Ingestion tab.")
648
+ else:
649
+ st.warning("⚠️ Please annotate at least 2 samples or select rows for training.")
650
+ return
651
+
652
+ # Stratified split
653
+ train_df, val_df = stratified_train_val_split(
654
+ annotated_df,
655
+ train_ratio=st.session_state.train_test_split
656
+ )
657
+
658
+ col1, col2, col3 = st.columns(3)
659
+ with col1:
660
+ st.info(f"πŸ“š Training samples: {len(train_df)}")
661
+ with col2:
662
+ st.info(f"πŸ§ͺ Validation samples: {len(val_df)}")
663
+ with col3:
664
+ if use_selection:
665
+ st.success("βœ… Using selected rows")
666
+ else:
667
+ st.warning("⚠️ Using all annotated rows")
668
+
669
+ # Optimization controls
670
+ col1, col2, col3 = st.columns([1, 1, 2])
671
+
672
+ with col1:
673
+ run_button = st.button(
674
+ "πŸš€ Run Optimization",
675
+ type="primary",
676
+ use_container_width=True
677
+ )
678
+
679
+ with col2:
680
+ if st.button("πŸ”„ Reset Results", use_container_width=True):
681
+ st.session_state.optimized_prompt = None
682
+ st.session_state.optimization_history = []
683
+ st.rerun()
684
+
685
+ if run_button:
686
+ if not setup_textgrad():
687
+ return
688
+
689
+ # Prepare training examples
690
+ train_examples = [
691
+ {'raw_text': row['text'], 'ground_truth': row['ground_truth']}
692
+ for _, row in train_df.iterrows()
693
+ ]
694
+
695
+ val_examples = [
696
+ {'raw_text': row['text'], 'ground_truth': row['ground_truth']}
697
+ for _, row in val_df.iterrows()
698
+ ]
699
+
700
+ # Progress tracking
701
+ progress_bar = st.progress(0)
702
+ status_text = st.empty()
703
+ iteration_log = st.empty()
704
+
705
+ try:
706
+ with st.spinner("πŸ“ TextGrad is optimizing the prompt..."):
707
+ status_text.text("Initializing TextGrad...")
708
+
709
+ # Initialize system prompt as a TextGrad Variable (trainable)
710
+ system_prompt = tg.Variable(
711
+ st.session_state.prompts['system_instruction'],
712
+ requires_grad=True,
713
+ role_description="system prompt for regex generation that guides the LLM to extract target text using precise Python regex patterns"
714
+ )
715
+
716
+ # Initialize model
717
+ model = RegexGeneratorModel(
718
+ system_prompt,
719
+ st.session_state['target_engine']
720
+ )
721
+
722
+ # Initialize TextGrad optimizer (TGD - Textual Gradient Descent)
723
+ optimizer = tg.TGD(parameters=[system_prompt])
724
+
725
+ progress_bar.progress(10)
726
+ status_text.text("Evaluating initial performance...")
727
+
728
+ # Evaluate initial performance
729
+ initial_scores = []
730
+ for example in val_examples[:5]:
731
+ try:
732
+ user_msg = tg.Variable(
733
+ f"Extract the target text from the following input:\n\n{example['raw_text']}",
734
+ requires_grad=False,
735
+ role_description="user input for regex extraction"
736
+ )
737
+ prediction = model(user_msg)
738
+ score = evaluate_regex_simple(
739
+ prediction.value.strip(),
740
+ example['raw_text'],
741
+ example['ground_truth'],
742
+ st.session_state.regex_flags
743
+ )
744
+ initial_scores.append(score)
745
+ except Exception as e:
746
+ logger.warning(f"Error in initial eval: {e}")
747
+ initial_scores.append(0.0)
748
+
749
+ initial_avg = np.mean(initial_scores) if initial_scores else 0.0
750
+
751
+ best_score = initial_avg
752
+ best_prompt = system_prompt.value
753
+ history = []
754
+
755
+ num_iterations = st.session_state.textgrad_config['num_iterations']
756
+ batch_size = st.session_state.textgrad_config['batch_size']
757
+
758
+ progress_bar.progress(20)
759
+ status_text.text(f"Starting optimization (Initial score: {initial_avg:.2%})...")
760
+
761
+ # TextGrad optimization loop
762
+ for iteration in range(num_iterations):
763
+ status_text.text(f"Iteration {iteration + 1}/{num_iterations}")
764
+
765
+ # Sample training examples for this iteration
766
+ batch_indices = np.random.choice(
767
+ len(train_examples),
768
+ min(batch_size, len(train_examples)),
769
+ replace=False
770
+ )
771
+
772
+ iteration_losses = []
773
+
774
+ for idx in batch_indices:
775
+ example = train_examples[idx]
776
+
777
+ try:
778
+ # Clear gradients
779
+ optimizer.zero_grad()
780
+
781
+ # Create user message variable
782
+ user_msg = tg.Variable(
783
+ f"Extract the target text from the following input:\n\n{example['raw_text']}",
784
+ requires_grad=False,
785
+ role_description="user input for regex extraction"
786
+ )
787
+
788
+ # Forward pass
789
+ prediction = model(user_msg)
790
+
791
+ # Create loss function for this example
792
+ loss_fn = create_regex_loss_fn(
793
+ example['raw_text'],
794
+ example['ground_truth'],
795
+ st.session_state.regex_flags
796
+ )
797
+
798
+ # Calculate loss
799
+ loss = loss_fn(prediction)
800
+ iteration_losses.append(loss)
801
+
802
+ # Backward pass to compute textual gradients
803
+ loss.backward()
804
+
805
+ except Exception as e:
806
+ logger.warning(f"Error in iteration {iteration + 1}, example {idx}: {e}")
807
+ continue
808
+
809
+ if iteration_losses:
810
+ # Apply optimization step (updates the system prompt)
811
+ optimizer.step()
812
+
813
+ # Evaluate on validation set
814
+ val_scores = []
815
+ for example in val_examples[:5]:
816
+ try:
817
+ user_msg = tg.Variable(
818
+ f"Extract the target text from the following input:\n\n{example['raw_text']}",
819
+ requires_grad=False,
820
+ role_description="user input for regex extraction"
821
+ )
822
+ prediction = model(user_msg)
823
+ score = evaluate_regex_simple(
824
+ prediction.value.strip(),
825
+ example['raw_text'],
826
+ example['ground_truth'],
827
+ st.session_state.regex_flags
828
+ )
829
+ val_scores.append(score)
830
+ except Exception as e:
831
+ val_scores.append(0.0)
832
+
833
+ current_score = np.mean(val_scores) if val_scores else 0.0
834
+
835
+ # Track results
836
+ history.append({
837
+ 'iteration': iteration + 1,
838
+ 'score': current_score,
839
+ 'prompt': system_prompt.value[:200] + '...' if len(system_prompt.value) > 200 else system_prompt.value
840
+ })
841
+
842
+ iteration_log.text(f"Iteration {iteration + 1}: Score = {current_score:.2%} (Best: {best_score:.2%})")
843
+
844
+ # Update best if improved
845
+ if current_score > best_score:
846
+ best_score = current_score
847
+ best_prompt = system_prompt.value
848
+
849
+ # Early stopping
850
+ if best_score >= st.session_state.textgrad_config['early_stopping_threshold']:
851
+ status_text.text(f"Early stopping - reached threshold {best_score:.2%}")
852
+ break
853
+
854
+ # Update progress
855
+ progress_bar.progress(20 + int(70 * (iteration + 1) / num_iterations))
856
+
857
+ # Small delay to avoid rate limits
858
+ time.sleep(1)
859
+
860
+ # Final evaluation
861
+ progress_bar.progress(95)
862
+ status_text.text("Final evaluation...")
863
+
864
+ final_scores = []
865
+ for example in val_examples:
866
+ try:
867
+ user_msg = tg.Variable(
868
+ f"Extract the target text from the following input:\n\n{example['raw_text']}",
869
+ requires_grad=False,
870
+ role_description="user input for regex extraction"
871
+ )
872
+ prediction = model(user_msg)
873
+ score = evaluate_regex_simple(
874
+ prediction.value.strip(),
875
+ example['raw_text'],
876
+ example['ground_truth'],
877
+ st.session_state.regex_flags
878
+ )
879
+ final_scores.append(score)
880
+ except Exception as e:
881
+ final_scores.append(0.0)
882
+
883
+ final_avg = np.mean(final_scores) if final_scores else 0.0
884
+
885
+ progress_bar.progress(100)
886
+ status_text.text("Complete!")
887
+
888
+ st.session_state.optimized_prompt = best_prompt
889
+ st.session_state.optimization_history.append({
890
+ 'initial_score': initial_avg,
891
+ 'final_score': final_avg,
892
+ 'best_score': best_score,
893
+ 'prompt': best_prompt,
894
+ 'timestamp': pd.Timestamp.now(),
895
+ 'history': history
896
+ })
897
+
898
+ st.success(f"βœ… Optimization Complete! Initial: {initial_avg:.2%} β†’ Best: {best_score:.2%}")
899
+
900
+ except Exception as e:
901
+ st.error(f"Optimization failed: {e}")
902
+ import traceback
903
+ st.error(traceback.format_exc())
904
+ return
905
+
906
+ # Display results
907
+ if st.session_state.optimized_prompt:
908
+ st.subheader("πŸ“Š Results")
909
+
910
+ with st.expander("πŸ” Optimized Prompt", expanded=True):
911
+ st.code(st.session_state.optimized_prompt, language="text")
912
+
913
+ # Optimization history
914
+ if st.session_state.optimization_history:
915
+ with st.expander("πŸ“ˆ Optimization History"):
916
+ latest = st.session_state.optimization_history[-1]
917
+
918
+ col1, col2, col3 = st.columns(3)
919
+ with col1:
920
+ st.metric("Initial Score", f"{latest['initial_score']:.2%}")
921
+ with col2:
922
+ st.metric("Final Score", f"{latest['final_score']:.2%}")
923
+ with col3:
924
+ improvement = latest['best_score'] - latest['initial_score']
925
+ st.metric("Best Score", f"{latest['best_score']:.2%}", delta=f"{improvement:+.2%}")
926
+
927
+ if 'history' in latest and latest['history']:
928
+ history_df = pd.DataFrame(latest['history'])
929
+ st.line_chart(history_df.set_index('iteration')['score'])
930
+
931
+
932
+ def render_testing_tab():
933
+ """Render the testing tab."""
934
+ st.header("πŸ” Test & Validate")
935
+
936
+ if st.session_state.optimized_prompt is None:
937
+ st.warning("⚠️ Please run optimization first.")
938
+ return
939
+
940
+ # Single test
941
+ st.subheader("πŸ§ͺ Single Test")
942
+
943
+ test_input = st.text_area(
944
+ "Enter test text",
945
+ height=100,
946
+ placeholder="Paste text here to extract regex pattern..."
947
+ )
948
+
949
+ col1, col2 = st.columns([1, 3])
950
+ with col1:
951
+ test_button = st.button("▢️ Generate & Run", type="primary")
952
+
953
+ if test_button and test_input:
954
+ if not setup_textgrad():
955
+ return
956
+
957
+ with st.spinner("Generating regex..."):
958
+ try:
959
+ # Create model with optimized prompt
960
+ system_prompt = tg.Variable(
961
+ st.session_state.optimized_prompt,
962
+ requires_grad=False,
963
+ role_description="optimized system prompt for regex generation"
964
+ )
965
+
966
+ model = RegexGeneratorModel(
967
+ system_prompt,
968
+ st.session_state['target_engine']
969
+ )
970
+
971
+ user_msg = tg.Variable(
972
+ f"Extract the target text from the following input:\n\n{test_input}",
973
+ requires_grad=False,
974
+ role_description="user input for regex extraction"
975
+ )
976
+
977
+ result = model(user_msg)
978
+ pattern = result.value.strip()
979
+
980
+ st.code(f"Generated Regex: {pattern}", language="regex")
981
+
982
+ # Compile and test
983
+ flags = 0
984
+ for flag in st.session_state.regex_flags:
985
+ flags |= getattr(re, flag, 0)
986
+
987
+ compiled = re.compile(pattern, flags)
988
+ matches = compiled.findall(test_input)
989
+
990
+ if matches:
991
+ st.success(f"βœ… Found {len(matches)} match(es):")
992
+ for i, match in enumerate(matches, 1):
993
+ st.markdown(f"**Match {i}:** `{match}`")
994
+
995
+ # Highlight matches in text
996
+ highlighted = test_input
997
+ for match in matches:
998
+ if isinstance(match, str):
999
+ highlighted = highlighted.replace(
1000
+ match,
1001
+ f"**:green[{match}]**"
1002
+ )
1003
+ st.markdown("**Highlighted text:**")
1004
+ st.markdown(highlighted)
1005
+ else:
1006
+ st.warning("No matches found.")
1007
+
1008
+ except re.error as e:
1009
+ st.error(f"Invalid regex generated: {e}")
1010
+ except Exception as e:
1011
+ st.error(f"Error: {e}")
1012
+
1013
+ st.divider()
1014
+
1015
+ # Batch testing
1016
+ st.subheader("πŸ“‹ Batch Testing")
1017
+
1018
+ batch_file = st.file_uploader(
1019
+ "Upload test data (CSV with 'text' column)",
1020
+ type=["csv"],
1021
+ key="batch_test"
1022
+ )
1023
+
1024
+ if batch_file:
1025
+ test_df = pd.read_csv(batch_file)
1026
+
1027
+ if 'text' not in test_df.columns:
1028
+ st.error("CSV must have 'text' column.")
1029
+ return
1030
+
1031
+ if st.button("πŸš€ Run Batch Test"):
1032
+ if not setup_textgrad():
1033
+ return
1034
+
1035
+ results = []
1036
+ progress = st.progress(0)
1037
+
1038
+ # Create model with optimized prompt
1039
+ system_prompt = tg.Variable(
1040
+ st.session_state.optimized_prompt,
1041
+ requires_grad=False,
1042
+ role_description="optimized system prompt for regex generation"
1043
+ )
1044
+
1045
+ model = RegexGeneratorModel(
1046
+ system_prompt,
1047
+ st.session_state['target_engine']
1048
+ )
1049
+
1050
+ for i, row in test_df.iterrows():
1051
+ try:
1052
+ user_msg = tg.Variable(
1053
+ f"Extract the target text from the following input:\n\n{row['text']}",
1054
+ requires_grad=False,
1055
+ role_description="user input for regex extraction"
1056
+ )
1057
+
1058
+ result = model(user_msg)
1059
+ pattern = result.value.strip()
1060
+
1061
+ flags = 0
1062
+ for flag in st.session_state.regex_flags:
1063
+ flags |= getattr(re, flag, 0)
1064
+
1065
+ match = re.search(pattern, row['text'], flags)
1066
+ extracted = match.group(0) if match else ""
1067
+
1068
+ results.append({
1069
+ 'text': row['text'][:100] + '...' if len(row['text']) > 100 else row['text'],
1070
+ 'pattern': pattern,
1071
+ 'extracted': extracted,
1072
+ 'success': bool(match)
1073
+ })
1074
+ except Exception as e:
1075
+ results.append({
1076
+ 'text': row['text'][:100] + '...',
1077
+ 'pattern': 'ERROR',
1078
+ 'extracted': str(e),
1079
+ 'success': False
1080
+ })
1081
+
1082
+ progress.progress((i + 1) / len(test_df))
1083
+
1084
+ results_df = pd.DataFrame(results)
1085
+
1086
+ # Summary metrics
1087
+ success_rate = results_df['success'].mean()
1088
+ col1, col2 = st.columns(2)
1089
+ with col1:
1090
+ st.metric("Success Rate", f"{success_rate:.1%}")
1091
+ with col2:
1092
+ st.metric("Total Tests", len(results_df))
1093
+
1094
+ # Results table
1095
+ st.dataframe(results_df, use_container_width=True)
1096
+
1097
+ # Download results
1098
+ csv = results_df.to_csv(index=False)
1099
+ st.download_button(
1100
+ "πŸ“₯ Download Results",
1101
+ csv,
1102
+ "batch_test_results.csv",
1103
+ "text/csv"
1104
+ )
1105
+
1106
+
1107
+ # --- Main Application ---
1108
+ def main():
1109
+ render_sidebar()
1110
+
1111
+ st.title("πŸ“ TextGrad Regex Optimizer")
1112
+ st.caption("Automated regex generation with TextGrad text-based optimization")
1113
+
1114
+ tab1, tab2, tab3 = st.tabs([
1115
+ "πŸ“₯ Data Ingestion",
1116
+ "πŸ“ Optimization",
1117
+ "πŸ” Testing"
1118
+ ])
1119
+
1120
+ with tab1:
1121
+ render_data_ingestion_tab()
1122
+
1123
+ with tab2:
1124
+ render_optimization_tab()
1125
+
1126
+ with tab3:
1127
+ render_testing_tab()
1128
+
1129
+ # Footer
1130
+ st.divider()
1131
+ st.caption(
1132
+ "Built with Streamlit and TextGrad | "
1133
+ "Configuration is auto-saved in the sidebar"
1134
+ )
1135
+
1136
+
1137
+ if __name__ == "__main__":
1138
+ main()
textgrad_app.py:Zone.Identifier ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [ZoneTransfer]
2
+ ZoneId=3
3
+ ReferrerUrl=https://web.telegram.org/k/
4
+ HostUrl=https://web.telegram.org/k/d/1501535785