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