VectorV17 commited on
Commit
61e73de
·
verified ·
1 Parent(s): 90f7a75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -235
app.py CHANGED
@@ -1,243 +1,290 @@
1
- import os
2
- import pandas as pd
3
- import numpy as np
4
- import joblib
5
- import gradio as io
6
-
7
- from sklearn.model_selection import train_test_split
8
- from sklearn.preprocessing import StandardScaler, OneHotEncoder
9
- from sklearn.impute import KNNImputer, SimpleImputer
10
- from sklearn.compose import ColumnTransformer
11
- from sklearn.pipeline import Pipeline
12
-
13
- # Model Libraries
14
- from sklearn.linear_model import LogisticRegression
15
- from sklearn.ensemble import RandomForestClassifier, StackingClassifier, VotingClassifier
16
- from xgboost import XGBClassifier
17
- from imblearn.over_sampling import SMOTE
18
- from imblearn.pipeline import Pipeline as ImbPipeline
19
-
20
- MODEL_PATH = "loan_stacking_model.pkl"
21
- DATA_PATH = "loan_dataset.csv"
22
-
23
- # =====================================================================
24
- # HIGH-SPEED CORE TRAINING FUNCTION
25
- # =====================================================================
26
- def train_and_cache_pipeline():
27
- print("Initializing ultra-fast pipeline training framework using current local environment...")
28
-
29
- if not os.path.exists(DATA_PATH):
30
- raise FileNotFoundError(f"Missing '{DATA_PATH}'. Please ensure your dataset is placed in the same repository directory.")
31
-
32
- df = pd.read_csv(DATA_PATH)
33
- X = df.drop('BAD', axis=1)
34
- y = df['BAD']
35
-
36
- # Explicit layout matching to prevent Pandas deprecation warnings
37
- num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
38
- cat_cols = X.select_dtypes(include=['object', 'string']).columns.tolist()
39
-
40
- # Fast Outlier Protection via IQR Capping
41
- def cap_outliers_iqr(data, columns):
42
- data_clean = data.copy()
43
- for col in columns:
44
- Q1 = data_clean[col].quantile(0.25)
45
- Q3 = data_clean[col].quantile(0.75)
46
- IQR = Q3 - Q1
47
- if IQR > 0:
48
- lower_bound = Q1 - 1.5 * IQR
49
- upper_bound = Q3 + 1.5 * IQR
50
- data_clean[col] = np.where(data_clean[col] < lower_bound, lower_bound, data_clean[col])
51
- data_clean[col] = np.where(data_clean[col] > upper_bound, upper_bound, data_clean[col])
52
- return data_clean
53
-
54
- X_cleaned = cap_outliers_iqr(X, num_cols)
55
-
56
- # Fast Feature Transformation Pipelines
57
- num_pipeline = Pipeline([
58
- ('imputer', KNNImputer(n_neighbors=5)),
59
- ('scaler', StandardScaler())
60
- ])
61
-
62
- cat_pipeline = Pipeline([
63
- ('imputer', SimpleImputer(strategy='most_frequent')),
64
- ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
65
- ])
66
-
67
- preprocessor = ColumnTransformer([
68
- ('num', num_pipeline, num_cols),
69
- ('cat', cat_pipeline, cat_cols)
70
- ])
71
-
72
- # Optimized hyper-parameters for near-instant execution
73
- rf_base = RandomForestClassifier(n_estimators=50, max_depth=8, random_state=42, n_jobs=-1)
74
- xgb_base = XGBClassifier(n_estimators=50, learning_rate=0.1, max_depth=4, eval_metric='logloss', random_state=42, n_jobs=-1)
75
- voting_base = VotingClassifier(estimators=[('rf_v', rf_base), ('xgb_v', xgb_base)], voting='soft')
76
-
77
- # Meta Stacking Level Layout
78
- stacking_ensemble = StackingClassifier(
79
- estimators=[('rf', rf_base), ('xgb', xgb_base), ('voting', voting_base)],
80
- final_estimator=LogisticRegression(max_iter=500, C=0.1),
81
- cv=2, # Streamlines cross-validation execution speed down to seconds
82
- n_jobs=-1
83
- )
84
-
85
- pipeline = ImbPipeline([
86
- ('preprocessing', preprocessor),
87
- ('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
88
- ('ensemble_model', stacking_ensemble)
89
- ])
90
-
91
- pipeline.fit(X_cleaned, y)
92
- joblib.dump(pipeline, MODEL_PATH)
93
- print("Model Stacking Pipeline Compiled and Cached Successfully!")
94
- return pipeline
95
-
96
- # =====================================================================
97
- # FAULT-TOLERANT SNAPSHOT INITIALIZATION
98
- # =====================================================================
99
- if os.path.exists(MODEL_PATH):
100
  try:
101
- print("Pre-trained file located. Loading parameters...")
102
- production_pipeline = joblib.load(MODEL_PATH)
103
- print("Pipeline imported successfully!")
104
- except Exception as error_context:
105
- print(f"Version warning/mismatch detected during unpickling: {error_context}")
106
- print("Bypassing incompatible snapshot file to initiate seamless automated fresh compile...")
107
- production_pipeline = train_and_cache_pipeline()
108
- else:
109
- production_pipeline = train_and_cache_pipeline()
110
-
111
-
112
- # =====================================================================
113
- # GRADIO PREDICTION INFERENCE ENGINE
114
- # =====================================================================
115
- def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc):
116
- input_data = pd.DataFrame([{
117
- 'LOAN': float(loan) if loan is not None else 0.0,
118
- 'MORTDUE': float(mortdue) if mortdue is not None else np.nan,
119
- 'VALUE': float(value) if value is not None else np.nan,
120
- 'REASON': reason if reason else 'DebtCon',
121
- 'JOB': job if job else 'Other',
122
- 'YOJ': float(yoj) if yoj is not None else np.nan,
123
- 'DEROG': float(derog) if derog is not None else np.nan,
124
- 'DELINQ': float(delinq) if delinq is not None else np.nan,
125
- 'CLAGE': float(clage) if clage is not None else np.nan,
126
- 'NINQ': float(ninq) if ninq is not None else np.nan,
127
- 'CLNO': float(clno) if clno is not None else np.nan,
128
- 'DEBTINC': float(debtinc) if debtinc is not None else np.nan
129
- }])
130
-
131
- prediction_proba = production_pipeline.predict_proba(input_data)[0]
132
- risk_of_default = prediction_proba[1]
133
-
134
- if risk_of_default > 0.40:
135
- bg_gradient = "linear-gradient(135deg, #3b1111 0%, #1a0505 100%)"
136
- accent_color = "#f87171"
137
- status_text = "❌ RISK ASSESSMENT: APPLICATION REJECTED"
138
- description = "The calculated default risk probability exceeds security margins. Financial variables present elevated interaction risk patterns."
139
- else:
140
- bg_gradient = "linear-gradient(135deg, #062411 0%, #021207 100%)"
141
- accent_color = "#4ade80"
142
- status_text = "✅ RISK ASSESSMENT: APPLICATION APPROVED"
143
- description = "This financial profile displays proper asset coverage stability, balanced leverage indexes, and strong structural repayment probabilities."
144
-
145
- metrics_html = f"""
146
- <div style="background: {bg_gradient}; color: #ffffff; padding: 24px; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 4px 10px rgba(0,0,0,0.45);">
147
- <h3 style="margin-top: 0; color: {accent_color}; font-size: 1.3rem; font-weight: 700; letter-spacing: 0.5px;">{status_text}</h3>
148
- <p style="color: #cbd5e1; font-size: 0.95rem; line-height: 1.6; margin-bottom: 20px;">{description}</p>
149
- <div style="border-top: 1px solid #334155; padding-top: 15px; display: flex; flex-direction: column; gap: 10px; font-family: monospace; font-size: 1rem;">
150
- <div style="display: flex; justify-content: space-between;">
151
- <span style="color: #94a3b8;">RISK PROBABILITY:</span>
152
- <strong style="color: {accent_color}; font-size: 1.1rem;">{risk_of_default * 100:.2f}%</strong>
153
- </div>
154
- <div style="display: flex; justify-content: space-between;">
155
- <span style="color: #94a3b8;">SYSTEM SPECIFICATION:</span>
156
- <strong style="color: #38bdf8;">92.18% Accuracy Achieved</strong>
157
- </div>
158
- </div>
159
- </div>
160
- """
161
- return metrics_html
162
-
163
-
164
- # =====================================================================
165
- # MODERNISED GRAPHIC INTERFACE DESIGN (Gradio 6.0+ Compliant Layout)
166
- # =====================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  custom_css = """
168
- .gradio-container { background-color: #0b0f19 !important; color: #f1f5f9 !important; max-width: 1150px !important; margin: 0 auto !important; }
169
- .section_panel { background-color: #161e2e !important; padding: 20px !important; border-radius: 12px !important; border: 1px solid #1f293d !important; margin-bottom: 15px !important; }
170
- label span { color: #94a3b8 !important; font-weight: 600 !important; font-size: 0.85rem !important; text-transform: uppercase; }
171
- input, select { background-color: #0b0f19 !important; color: #ffffff !important; border: 1px solid #2d3748 !important; border-radius: 6px !important; }
172
- button.primary { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important; color: white !important; font-weight: 700 !important; font-size: 1rem !important; padding: 12px !important; border-radius: 8px !important; border: none !important; cursor: pointer; }
173
- button.primary:hover { filter: brightness(1.1); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  """
175
 
176
- # FIX: Passed browser title parameter directly to Blocks configuration initialization stage
177
- with io.Blocks(title="AI Loan Underwriting Portal") as app:
178
-
179
- # Header Branding Section
180
- io.Markdown(
181
- """
182
- <div style='text-align: center; margin-bottom: 30px; padding: 10px 0; border-bottom: 1px solid #1f293d;'>
183
- <h1 style='color: #38bdf8; font-size: 2.2rem; font-weight: 800; margin-bottom: 5px;'>🏦 Institutional Loan Underwriting Portal</h1>
184
- <p style='color: #64748b; font-size: 1.1rem; margin: 0;'>Automated Corporate Underwriting Risk Pipeline • Optimized Stacking Ensemble <b>(92.18% Accuracy)</b></p>
185
- </div>
186
- """
187
- )
188
-
189
- with io.Row():
190
- # Input Workspace Panel (Left Side)
191
- with io.Column(scale=2):
192
-
193
- with io.Column(elem_classes="section_panel"):
194
- io.Markdown("<span style='color:#38bdf8; font-weight:700;'>📊 SEGMENT 1: REQUESTED CAPITAL</span>")
195
- with io.Row():
196
- loan = io.Number(label="Loan Amount ($) [LOAN]", value=15000)
197
- reason = io.Dropdown(choices=["DebtCon", "HomeImp"], label="Purpose [REASON]", value="DebtCon")
198
-
199
- with io.Column(elem_classes="section_panel"):
200
- io.Markdown("<span style='color:#38bdf8; font-weight:700;'>🏠 SEGMENT 2: FINANCIAL STANDING</span>")
201
- with io.Row():
202
- mortdue = io.Number(label="Mortgage Value Owed ($) [MORTDUE]", value=50000)
203
- value = io.Number(label="Property Asset Value ($) [VALUE]", value=85000)
204
- with io.Row():
205
- job = io.Dropdown(choices=["Other", "Mgr", "Office", "ProfExe", "Sales", "Self"], label="Job Field [JOB]", value="Other")
206
- yoj = io.Number(label="Years at Current Job [YOJ]", value=5)
207
-
208
- with io.Column(elem_classes="section_panel"):
209
- io.Markdown("<span style='color:#38bdf8; font-weight:700;'>💳 SEGMENT 3: REPAYMENT PERFORMANCES</span>")
210
- with io.Row():
211
- debtinc = io.Number(label="Debt-to-Income Ratio (%) [DEBTINC]", value=32.5)
212
- clage = io.Number(label="Oldest Account Line (Months) [CLAGE]", value=180)
213
- with io.Row():
214
- delinq = io.Number(label="Delinquent Credit Lines [DELINQ]", value=0)
215
- derog = io.Number(label="Derogatory Incidents [DEROG]", value=0)
216
- with io.Row():
217
- ninq = io.Number(label="Recent Bureau Inquiries [NINQ]", value=1)
218
- clno = io.Number(label="Total Active Credit Lines [CLNO]", value=20)
219
-
220
- submit_btn = io.Button("⚡ Run Stacking Underwriting Evaluation", variant="primary")
221
-
222
- # Output Feed Hub Panel (Right Side)
223
- with io.Column(scale=1):
224
- with io.Column(elem_classes="section_panel"):
225
- io.Markdown("<span style='color:#64748b; font-weight:700;'>🏁 ANALYSIS HUB</span>")
226
- output_html = io.HTML(
227
- value="""
228
- <div style='color: #475569; background-color: #0b0f19; border-radius: 8px; border: 2px dashed #1f293d; padding: 50px 20px; text-align: center; font-style: italic; font-size: 0.95rem;'>
229
- System standby. Supply application parameters and trigger execution to populate real-time risk diagnostic logs.
230
- </div>
231
- """
232
  )
233
 
234
- # UI Wiring Connectors
235
- submit_btn.click(
236
- fn=evaluate_loan_risk,
237
- inputs=[loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc],
238
- outputs=output_html
239
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
  if __name__ == "__main__":
242
- # FIX: Title keyword removed from here to perfectly comply with Gradio 6.0+ launch constraints
243
- app.launch(css=custom_css, share=True)
 
1
+ import anyascii
2
+ import gradio as gr
3
+ import nltk
4
+ from deep_translator import GoogleTranslator, MyMemoryTranslator
5
+ from langdetect import DetectorFactory, detect
6
+
7
+ # Enforce deterministic language tracking
8
+ DetectorFactory.seed = 0
9
+
10
+ # Ensure NLTK resources are available
11
+ for resource in ['punkt', 'averaged_perceptron_tagger', 'punkt_tab']:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
+ if 'punkt' in resource:
14
+ nltk.data.find(f'tokenizers/{resource}')
15
+ else:
16
+ nltk.data.find(f'taggers/{resource}')
17
+ except LookupError:
18
+ nltk.download(resource, quiet=True)
19
+
20
+ # Language Mapping
21
+ LANGUAGES = {
22
+ 'Auto-Detect': 'auto',
23
+ 'English': 'en',
24
+ 'Hindi (हिंदी)': 'hi',
25
+ 'Spanish (Español)': 'es',
26
+ 'French (Français)': 'fr',
27
+ 'German (Deutsch)': 'de',
28
+ 'Chinese (Simplified)': 'zh-CN',
29
+ 'Chinese (Traditional)': 'zh-TW',
30
+ 'Japanese (日本語)': 'ja',
31
+ 'Malay': 'ms',
32
+ 'Arabic': 'ar',
33
+ 'Russian': 'ru',
34
+ 'Italian': 'it',
35
+ 'Portuguese': 'pt',
36
+ 'Korean': 'ko',
37
+ }
38
+
39
+ LANGUAGE_NAMES = {v: k for k, v in LANGUAGES.items()}
40
+
41
+
42
+ # --- CORE PROCESSING FUNCTION ---
43
+ def execute_agent_task(
44
+ text, source_lang_name, target_lang_name, service_name, action
45
+ ):
46
+ if not text or not text.strip():
47
+ return "Input text space cannot be empty.", "Error"
48
+
49
+ source_lang = LANGUAGES.get(source_lang_name, 'auto')
50
+ target_lang = LANGUAGES.get(target_lang_name, 'en')
51
+
52
+ try:
53
+ # 1. Translation System
54
+ if action == 'translate':
55
+ if service_name == 'MyMemory Shared API Network':
56
+ src = 'en' if source_lang == 'auto' else source_lang
57
+ translator = MyMemoryTranslator(
58
+ source=src, target=target_lang
59
+ )
60
+ else:
61
+ translator = GoogleTranslator(
62
+ source=source_lang, target=target_lang
63
+ )
64
+
65
+ result = translator.translate(text)
66
+ return result, 'Translation'
67
+
68
+ # 2. Transliteration System
69
+ elif action == 'transliterate':
70
+ result = anyascii.anyascii(text)
71
+ if result.lower() == text.lower():
72
+ result = f'[Note: Text is already in Roman/Latin script form]\n\n{result}'
73
+ return result, 'Transliteration'
74
+
75
+ # 3. Morphological Structural Annotation System
76
+ elif action == 'annotate':
77
+ tokens = nltk.word_tokenize(text)
78
+ pos_tags = nltk.pos_tag(tokens)
79
+
80
+ tag_dictionary = {
81
+ 'NN': 'Noun (Singular)',
82
+ 'NNS': 'Noun (Plural)',
83
+ 'NNP': 'Proper Noun',
84
+ 'VB': 'Verb (Base Form)',
85
+ 'VBD': 'Verb (Past Tense)',
86
+ 'VBG': 'Verb (Gerund/Participle)',
87
+ 'JJ': 'Adjective',
88
+ 'RB': 'Adverb',
89
+ 'PRP': 'Pronoun',
90
+ 'DT': 'Determiner',
91
+ 'IN': 'Preposition/Conjunction',
92
+ 'CD': 'Cardinal Number',
93
+ }
94
+
95
+ report = [
96
+ f'--- Linguistic Annotation Report ({len(tokens)} Tokens Identified) ---'
97
+ ]
98
+ for word, tag in pos_tags:
99
+ readable_label = tag_dictionary.get(
100
+ tag, f'Structure Token ({tag})'
101
+ )
102
+ report.append(f'• "{word}" → {readable_label}')
103
+
104
+ return '\n'.join(report), 'Annotation'
105
+
106
+ # 4. Language Detection Engine
107
+ elif action == 'detect':
108
+ raw_code = detect(text).lower()
109
+ readable_lang = LANGUAGE_NAMES.get(
110
+ raw_code, f'Unknown/Unmapped Script ({raw_code.upper()})'
111
+ )
112
+ result = f'--- Language Detection Report ---\n\n• Identified Language: {readable_lang}\n• Standard ISO 639-1 Code: {raw_code}'
113
+ return result, 'Language Detection'
114
+
115
+ except Exception as e:
116
+ return f'Agent processing failure: {str(e)}', 'Processing Error'
117
+
118
+
119
+ # --- CUSTOM CSS FOR EXACT THEME MATCHING ---
120
  custom_css = """
121
+ body, .gradio-container {
122
+ background-color: #0b1818 !important;
123
+ color: #e2f1f1 !important;
124
+ font-family: 'Segoe UI', system-ui, sans-serif;
125
+ }
126
+
127
+ #sidebar {
128
+ background-color: #512da8 !important;
129
+ border-radius: 12px;
130
+ padding: 25px !important;
131
+ color: #ffffff !important;
132
+ }
133
+
134
+ #sidebar h2 {
135
+ color: #ffeb3b !important;
136
+ font-weight: 700 !important;
137
+ font-size: 20px !important;
138
+ margin-bottom: 10px;
139
+ }
140
+
141
+ .action-btn {
142
+ background-color: #1a73e8 !important;
143
+ color: white !important;
144
+ font-weight: bold !important;
145
+ border: none !important;
146
+ border-radius: 6px !important;
147
+ }
148
+
149
+ .action-btn:hover {
150
+ background-color: #155cb4 !important;
151
+ }
152
+
153
+ .status-badge {
154
+ background-color: #173131;
155
+ color: #2e7d32;
156
+ padding: 6px 12px;
157
+ border-radius: 20px;
158
+ font-weight: bold;
159
+ }
160
  """
161
 
162
+ # --- GRADIO INTERFACE BUILD ---
163
+ with gr.Blocks(css=custom_css, title="XTranslate Agentic Studio") as demo:
164
+
165
+ with gr.Row():
166
+ # Left Info Sidebar
167
+ with gr.Column(scale=1, elem_id="sidebar"):
168
+ gr.Markdown("## Welcome to the Linguistic Platform")
169
+ gr.Markdown(
170
+ "It is an active functional platform that bridges global communication gaps, allowing users to effortlessly understand and interact in foreign languages."
171
+ )
172
+ gr.Markdown(
173
+ """
174
+ **<u>🚀 Key Features:-</u>**
175
+ * ✔️ Core Translation
176
+ * ✔️ Language Identification
177
+ * ✔️ Universal Transliteration
178
+ * ✔️ Part-of-Speech Annotation
179
+ """
180
+ )
181
+ gr.Markdown("<br><br><small>Infrastructure State: Online</small>")
182
+
183
+ # Right Main Control Center
184
+ with gr.Column(scale=3):
185
+ # Header
186
+ with gr.Row():
187
+ gr.Markdown(
188
+ "## 🤖 XTranslate Agentic Studio <span style='font-size: 12px; background: #00b4d8; color: black; padding: 2px 6px; border-radius: 4px;'>v2.5</span>"
189
+ )
190
+ gr.Markdown(
191
+ "<div style='text-align: right; color: #a2cfcf;'>🟢 Engine Status: Live</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  )
193
 
194
+ # Workspace Card Grid
195
+ with gr.Row():
196
+ with gr.Column():
197
+ source_lang = gr.Dropdown(
198
+ choices=list(LANGUAGES.keys()),
199
+ value="Auto-Detect",
200
+ label="🌐 Source Language",
201
+ )
202
+ source_input = gr.Textbox(
203
+ lines=8,
204
+ placeholder="Type, paste, or input your textual string here...",
205
+ label="Input Text",
206
+ )
207
+
208
+ with gr.Column():
209
+ target_lang = gr.Dropdown(
210
+ choices=[
211
+ k for k in LANGUAGES.keys() if k != "Auto-Detect"
212
+ ],
213
+ value="English",
214
+ label="📒 Target Language",
215
+ )
216
+ target_output = gr.Textbox(
217
+ lines=8,
218
+ placeholder="Engine processing outputs project here...",
219
+ label="Result View",
220
+ interactive=False,
221
+ )
222
+ mode_badge = gr.Textbox(
223
+ label="Active Output Mode",
224
+ interactive=False,
225
+ value="Ready",
226
+ )
227
+
228
+ # Translation Service Network
229
+ service_select = gr.Dropdown(
230
+ choices=[
231
+ "Google Cloud Neural Network",
232
+ "MyMemory Shared API Network",
233
+ ],
234
+ value="Google Cloud Neural Network",
235
+ label="ACTIVE NEURAL TRANSLATION NETWORK SERVICE SELECTOR",
236
+ )
237
+
238
+ gr.Markdown(
239
+ "<span style='color:#2e7d32; font-weight:bold;'>ENABLED LINGUISTIC SELECT FUNCTIONALITIES:-</span>"
240
+ )
241
+
242
+ # Action Buttons Row
243
+ with gr.Row():
244
+ btn_translate = gr.Button(
245
+ "Translate Text", elem_classes=["action-btn"]
246
+ )
247
+ btn_detect = gr.Button(
248
+ "Detect Language", elem_classes=["action-btn"]
249
+ )
250
+ btn_transliterate = gr.Button(
251
+ "Transliterate Script", elem_classes=["action-btn"]
252
+ )
253
+ btn_annotate = gr.Button(
254
+ "Annotate Structure", elem_classes=["action-btn"]
255
+ )
256
+
257
+ # Handler Routing
258
+ def run_task(text, src, tgt, service, act):
259
+ return execute_agent_task(text, src, tgt, service, act)
260
+
261
+ btn_translate.click(
262
+ fn=lambda t, s, tg, srv: run_task(
263
+ t, s, tg, srv, 'translate'
264
+ ),
265
+ inputs=[source_input, source_lang, target_lang, service_select],
266
+ outputs=[target_output, mode_badge],
267
+ )
268
+
269
+ btn_detect.click(
270
+ fn=lambda t, s, tg, srv: run_task(t, s, tg, srv, 'detect'),
271
+ inputs=[source_input, source_lang, target_lang, service_select],
272
+ outputs=[target_output, mode_badge],
273
+ )
274
+
275
+ btn_transliterate.click(
276
+ fn=lambda t, s, tg, srv: run_task(
277
+ t, s, tg, srv, 'transliterate'
278
+ ),
279
+ inputs=[source_input, source_lang, target_lang, service_select],
280
+ outputs=[target_output, mode_badge],
281
+ )
282
+
283
+ btn_annotate.click(
284
+ fn=lambda t, s, tg, srv: run_task(t, s, tg, srv, 'annotate'),
285
+ inputs=[source_input, source_lang, target_lang, service_select],
286
+ outputs=[target_output, mode_badge],
287
+ )
288
 
289
  if __name__ == "__main__":
290
+ demo.launch()