VectorV17 commited on
Commit
3f3c34a
·
verified ·
1 Parent(s): 1070b85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -370
app.py CHANGED
@@ -1,375 +1,205 @@
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 detection
8
- DetectorFactory.seed = 0
9
-
10
- # Ensure required NLTK tokenizers and taggers 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
- # ISO Code mappings
21
- LANGUAGES = {
22
- 'Auto-Detect Language': '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
- 'Japanese (日本語)': 'ja',
30
- 'Malay': 'ms',
31
- 'Arabic': 'ar',
32
- 'Russian': 'ru',
33
- 'Italian': 'it',
34
- 'Portuguese': 'pt',
35
- 'Korean': 'ko',
36
- }
37
-
38
- LANGUAGE_NAMES = {v: k for k, v in LANGUAGES.items()}
39
-
40
-
41
- # --- CORE PROCESSING FUNCTION ---
42
- def execute_agent_task(
43
- text, source_lang_name, target_lang_name, service_name, action
44
- ):
45
- if not text or not text.strip():
46
- return 'Input text space cannot be empty.'
47
-
48
- source_lang = LANGUAGES.get(source_lang_name, 'auto')
49
- target_lang = LANGUAGES.get(target_lang_name, 'en')
50
-
51
- try:
52
- if action == 'translate':
53
- if service_name == 'MyMemory Shared API Network':
54
- src = 'en' if source_lang == 'auto' else source_lang
55
- translator = MyMemoryTranslator(
56
- source=src, target=target_lang
57
- )
58
- else:
59
- translator = GoogleTranslator(
60
- source=source_lang, target=target_lang
61
- )
62
- return translator.translate(text)
63
-
64
- elif action == 'transliterate':
65
- result = anyascii.anyascii(text)
66
- if result.lower() == text.lower():
67
- result = f'[Note: Text is already in Roman/Latin script form]\n\n{result}'
68
- return result
69
-
70
- elif action == 'annotate':
71
- tokens = nltk.word_tokenize(text)
72
- pos_tags = nltk.pos_tag(tokens)
73
-
74
- tag_dictionary = {
75
- 'NN': 'Noun (Singular)',
76
- 'NNS': 'Noun (Plural)',
77
- 'NNP': 'Proper Noun',
78
- 'VB': 'Verb (Base Form)',
79
- 'VBD': 'Verb (Past Tense)',
80
- 'VBG': 'Verb (Gerund/Participle)',
81
- 'JJ': 'Adjective',
82
- 'RB': 'Adverb',
83
- 'PRP': 'Pronoun',
84
- 'DT': 'Determiner',
85
- 'IN': 'Preposition/Conjunction',
86
- 'CD': 'Cardinal Number',
87
- }
88
-
89
- report = [
90
- f'--- Linguistic Annotation Report ({len(tokens)} Tokens Identified) ---'
91
- ]
92
- for word, tag in pos_tags:
93
- readable_label = tag_dictionary.get(
94
- tag, f'Structure Token ({tag})'
95
- )
96
- report.append(f'• "{word}" → {readable_label}')
97
-
98
- return '\n'.join(report)
99
-
100
- elif action == 'detect':
101
- raw_code = detect(text).lower()
102
- readable_lang = LANGUAGE_NAMES.get(
103
- raw_code, f'Unknown/Unmapped Script ({raw_code.upper()})'
104
- )
105
- return f'--- Language Detection Report ---\n\n• Identified Language: {readable_lang}\n• Standard ISO 639-1 Code: {raw_code}'
106
-
107
- except Exception as e:
108
- return f'Agent processing failure: {str(e)}'
109
-
110
-
111
- # --- BALANCED DARK THEME STYLING ---
112
- custom_css = """
113
- body, .gradio-container {
114
- background-color: #0b1818 !important;
115
- font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, sans-serif !important;
116
- color: #e2f1f1 !important;
117
- }
118
-
119
- footer { display: none !important; }
120
-
121
- /* Main Layout Wrapper */
122
- #main-workspace {
123
- background-color: #112424;
124
- border-radius: 16px;
125
- border: 1px solid #1a3a3a;
126
- box-shadow: 0 20px 50px rgba(0,0,0,0.5);
127
- overflow: hidden;
128
- padding: 0 !important;
129
- }
130
-
131
- /* Sidebar Styling */
132
- #sidebar-panel {
133
- background-color: #512da8 !important;
134
- padding: 35px 25px !important;
135
- display: flex;
136
- flex-direction: column;
137
- justify-content: space-between;
138
- }
139
-
140
- /* Right Main Panel Padding */
141
- #main-control-center {
142
- padding: 30px !important;
143
- }
144
-
145
- /* Textarea Card Styling */
146
- .card-box {
147
- background-color: #ffffff !important;
148
- border-radius: 10px !important;
149
- border: 1px solid #cfd8dc !important;
150
- overflow: hidden !important;
151
- padding: 0 !important;
152
- }
153
-
154
- .input-textarea textarea {
155
- background-color: #ffffff !important;
156
- color: #263238 !important;
157
- font-size: 15px !important;
158
- border: none !important;
159
- outline: none !important;
160
- box-shadow: none !important;
161
- }
162
-
163
- .output-textarea textarea {
164
- background-color: #fafafa !important;
165
- color: #37474f !important;
166
- font-size: 15px !important;
167
- border: none !important;
168
- outline: none !important;
169
- box-shadow: none !important;
170
- }
171
-
172
- /* Dropdown styling */
173
- .custom-dropdown {
174
- background-color: #162e2e !important;
175
- border: 1px solid #204545 !important;
176
- border-radius: 6px !important;
177
- color: #ffffff !important;
178
- }
179
-
180
- /* Primary Action Buttons */
181
- .blue-btn button {
182
- background-color: #1a73e8 !important;
183
- color: #ffffff !important;
184
- font-weight: 600 !important;
185
- font-size: 14px !important;
186
- border-radius: 6px !important;
187
- border: none !important;
188
- padding: 12px 16px !important;
189
- box-shadow: 0 4px 12px rgba(26,115,232,0.3) !important;
190
- transition: all 0.2s ease !important;
191
- }
192
-
193
- .blue-btn button:hover {
194
- background-color: #155cb4 !important;
195
  }
 
 
 
196
  """
197
 
198
- # --- GRADIO BUILD ---
199
- with gr.Blocks(title="XTranslate Agentic Studio") as demo:
200
-
201
- with gr.Row(elem_id="main-workspace"):
202
-
203
- # LEFT SIDEBAR
204
- with gr.Column(scale=1, elem_id="sidebar-panel"):
205
- gr.HTML(
206
- """
207
- <h2 style="font-weight:bold; color:yellow; font-size: 22px; margin-bottom: 12px;">Welcome to the Linguistic Platform</h2>
208
- <p style="font-size: 14px; font-weight:bold; line-height: 1.5; color: #f3e5f5;">
209
- It is an active functional platform that bridges global communication gaps, allowing users to effortlessly understand and interact in foreign languages.
210
- </p>
211
- <br>
212
- <ul style="list-style: none; padding: 0; margin-top: 10px; font-size: 14px;">
213
- <li style="font-style:italic; text-decoration: underline; font-weight:bold; margin-bottom: 10px; color: #ffffff;">🚀 Key Features:-</li>
214
- <li style="margin-bottom: 8px;">✔ Core Translation</li>
215
- <li style="margin-bottom: 8px;">✔ Language Identification</li>
216
- <li style="margin-bottom: 8px;">✔ Universal Transliteration</li>
217
- <li style="margin-bottom: 8px;">✔ Part-of-Speech Annotation</li>
218
- </ul>
219
- <br><br>
220
- <div style="font-size: 12px; color: #b39ddb;">Infrastructure State: Online</div>
221
- """
222
- )
223
-
224
- # RIGHT MAIN CONTROL CENTER
225
- with gr.Column(scale=3, elem_id="main-control-center"):
226
 
227
- # 1. TOP HEADER & STATUS
228
- gr.HTML(
229
- """
230
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
231
- <div style="display: flex; align-items: center; gap: 10px;">
232
- <span style="font-size: 26px;">🤖</span>
233
- <h1 style="font-size: 22px; font-weight: 700; color: #ffffff; margin: 0;">
234
- XTranslate Agentic Studio
235
- <span style="font-size: 11px; background: #00b4d8; color: #0b1818; padding: 2px 6px; border-radius: 4px; vertical-align: middle;">v2.5</span>
236
- </h1>
237
- </div>
238
- <div style="font-size: 13px; background-color: #173131; padding: 6px 12px; border-radius: 20px; color: #a2cfcf;">
239
- 🟢 Engine Status: Live
240
- </div>
241
- </div>
242
- """
243
- )
244
-
245
- # 2. FUNCTIONALITIES AT TOP (ACTION BUTTONS & NETWORK SELECTOR)
246
- gr.HTML(
247
- """<div style="margin-bottom: 8px; font-size: 14px; font-weight: bold; color: #20c997;">ENABLED LINGUISTIC SELECT FUNCTIONALITIES:-</div>"""
248
- )
249
-
250
- with gr.Column():
251
- btn_translate = gr.Button(
252
- "Translate Text", elem_classes=["blue-btn"]
253
- )
254
- btn_detect = gr.Button(
255
- "Detect Language", elem_classes=["blue-btn"]
256
- )
257
- btn_transliterate = gr.Button(
258
- "Transliterate Script", elem_classes=["blue-btn"]
259
- )
260
- btn_annotate = gr.Button(
261
- "Annotate Structure", elem_classes=["blue-btn"]
262
- )
263
-
264
- gr.HTML(
265
- """<div style="margin-top: 15px; margin-bottom: 5px; font-size: 12px; font-weight: bold; color: #81a1a1; text-transform: uppercase;">ACTIVE NEURAL TRANSLATION NETWORK SERVICE SELECTOR</div>"""
266
- )
267
- service_select = gr.Dropdown(
268
- choices=[
269
- "Google Cloud Neural Network",
270
- "MyMemory Shared API Network",
271
- ],
272
- value="Google Cloud Neural Network",
273
- show_label=False,
274
- container=False,
275
- elem_classes=["custom-dropdown"],
276
- )
277
-
278
- # 3. INPUT / OUTPUT (I/O) BELOW FUNCTIONALITIES
279
- gr.HTML(
280
- """<div style="margin-top: 20px; margin-bottom: 8px; font-size: 12px; font-weight: bold; color: #81a1a1; text-transform: uppercase;">INPUT / OUTPUT WORKSPACE</div>"""
281
- )
282
-
283
- with gr.Row():
284
- # LEFT INPUT CARD
285
- with gr.Column(elem_classes=["card-box"]):
286
- source_lang = gr.Dropdown(
287
- choices=list(LANGUAGES.keys()),
288
- value="Auto-Detect Language",
289
- show_label=False,
290
- container=False,
291
- )
292
- source_input = gr.Textbox(
293
- lines=9,
294
- placeholder="Type, paste, or input your textual string here...",
295
- show_label=False,
296
- container=False,
297
- elem_classes=["input-textarea"],
298
- )
299
-
300
- # RIGHT OUTPUT CARD
301
- with gr.Column(elem_classes=["card-box"]):
302
- target_lang = gr.Dropdown(
303
- choices=[
304
- k
305
- for k in LANGUAGES.keys()
306
- if k != "Auto-Detect Language"
307
- ],
308
- value="English",
309
- show_label=False,
310
- container=False,
311
- )
312
- target_output = gr.Textbox(
313
- lines=9,
314
- placeholder="Engine processing outputs project here...",
315
- show_label=False,
316
- container=False,
317
- interactive=False,
318
- elem_classes=["output-textarea"],
319
- )
320
-
321
- # EVENT ROUTING
322
- btn_translate.click(
323
- fn=lambda t, s, tg, srv: execute_agent_task(
324
- t, s, tg, srv, "translate"
325
- ),
326
- inputs=[
327
- source_input,
328
- source_lang,
329
- target_lang,
330
- service_select,
331
- ],
332
- outputs=[target_output],
333
- )
334
-
335
- btn_detect.click(
336
- fn=lambda t, s, tg, srv: execute_agent_task(
337
- t, s, tg, srv, "detect"
338
- ),
339
- inputs=[
340
- source_input,
341
- source_lang,
342
- target_lang,
343
- service_select,
344
- ],
345
- outputs=[target_output],
346
- )
347
-
348
- btn_transliterate.click(
349
- fn=lambda t, s, tg, srv: execute_agent_task(
350
- t, s, tg, srv, "transliterate"
351
- ),
352
- inputs=[
353
- source_input,
354
- source_lang,
355
- target_lang,
356
- service_select,
357
- ],
358
- outputs=[target_output],
359
- )
360
-
361
- btn_annotate.click(
362
- fn=lambda t, s, tg, srv: execute_agent_task(
363
- t, s, tg, srv, "annotate"
364
- ),
365
- inputs=[
366
- source_input,
367
- source_lang,
368
- target_lang,
369
- service_select,
370
- ],
371
- outputs=[target_output],
372
- )
373
-
374
- if __name__ == "__main__":
375
- demo.launch(css=custom_css)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ import time
4
  import gradio as gr
5
+ import plotly.express as px
6
+ import pandas as pd
7
+ import requests
8
+ from server import app as flask_app
9
+
10
+ # 1. Start Flask REST API Engine in background
11
+ def start_flask():
12
+ flask_app.run(host='127.0.0.1', port=5000)
13
+
14
+
15
+ flask_thread = threading.Thread(target=start_flask, daemon=True)
16
+ flask_thread.start()
17
+ time.sleep(1.5) # Pause briefly for server initialization
18
+
19
+ # 2. Custom CSS for Enterprise Analytics Theme (Inspired by Templates)
20
+ CUSTOM_CSS = """
21
+ .container { max-width: 1280px; margin: auto; }
22
+ .kpi-card {
23
+ background: #1f2937;
24
+ border: 1px solid #374151;
25
+ border-radius: 10px;
26
+ padding: 16px;
27
+ color: white;
28
+ text-align: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
+ .kpi-title { font-size: 0.85rem; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; }
31
+ .kpi-value { font-size: 2rem; font-weight: 700; color: #3b82f6; margin-top: 4px; }
32
+ .kpi-sub { font-size: 0.8rem; color: #10b981; margin-top: 4px; }
33
  """
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # 3. Prediction & Analytics Handler Function
37
+ def dashboard_pipeline(
38
+ lagging_kvarh,
39
+ leading_kvarh,
40
+ lagging_pf,
41
+ leading_pf,
42
+ nsm,
43
+ week_status,
44
+ day_of_week,
45
+ load_type,
46
+ ):
47
+ payload = {
48
+ 'Lagging_Current_Reactive_Power_kVarh': float(lagging_kvarh),
49
+ 'Leading_Current_Reactive_Power_kVarh': float(leading_kvarh),
50
+ 'Lagging_Current_Power_Factor': float(lagging_pf),
51
+ 'Leading_Current_Power_Factor': float(leading_pf),
52
+ 'NSM': int(nsm),
53
+ 'WeekStatus': week_status,
54
+ 'Day_of_week': day_of_week,
55
+ 'Load_Type': load_type,
56
+ }
57
+
58
+ try:
59
+ # Query Flask API
60
+ resp = requests.post('http://127.0.0.1:5000/predict', json=payload)
61
+ if resp.status_code == 200:
62
+ res = resp.json()
63
+
64
+ kwh_val = f"{res['predicted_usage_kwh']} kWh"
65
+ co2_val = f"{res['estimated_co2']} tCO2"
66
+ status_val = res['mitigation_status']
67
+
68
+ # Query History for Dynamic Chart
69
+ hist_resp = requests.get('http://127.0.0.1:5000/history')
70
+ if hist_resp.status_code == 200 and hist_resp.json()['status'] == 'success':
71
+ logs = hist_resp.json()['data']
72
+ if logs:
73
+ df_logs = pd.DataFrame(logs)
74
+ fig = px.line(
75
+ df_logs,
76
+ x='id',
77
+ y='predicted_usage_kwh',
78
+ title='Recent Power Consumption Trend (MySQL Logs)',
79
+ labels={
80
+ 'id': 'Prediction Index',
81
+ 'predicted_usage_kwh': 'Power (kWh)',
82
+ },
83
+ markers=True,
84
+ )
85
+ fig.update_layout(
86
+ template='plotly_dark', paper_bgcolor='#111827', plot_bgcolor='#1f2937'
87
+ )
88
+ else:
89
+ fig = px.line(title='No logs recorded yet')
90
+ else:
91
+ fig = px.line(title='Chart unavailable')
92
+
93
+ return kwh_val, co2_val, f'{lagging_pf}%', status_val, fig
94
+
95
+ return 'Error', 'Error', 'Error', 'Failed API Call', px.line()
96
+
97
+ except Exception as e:
98
+ return 'Error', 'Error', 'Error', str(e), px.line()
99
+
100
+
101
+ # 4. Construct Dashboard UI Interface
102
+ with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
103
+ gr.Markdown(
104
+ """
105
+ # ⚡ SteelPlant FinVista - Energy & Carbon Analytics Engine
106
+ ### Real-time Power Demand Prediction & Carbon Mitigation Dashboard
107
+ """
108
+ )
109
+
110
+ # --- TOP KPI METRIC CARDS (Inspired by Images 1, 2, & 3) ---
111
+ with gr.Row():
112
+ with gr.Column(scale=1):
113
+ kpi_kwh = gr.Textbox(
114
+ label='Predicted Usage', value='-- kWh', interactive=False
115
+ )
116
+ with gr.Column(scale=1):
117
+ kpi_co2 = gr.Textbox(
118
+ label='Estimated Carbon', value='-- tCO2', interactive=False
119
+ )
120
+ with gr.Column(scale=1):
121
+ kpi_pf = gr.Textbox(
122
+ label='Power Factor Efficiency', value='-- %', interactive=False
123
+ )
124
+ with gr.Column(scale=1):
125
+ kpi_status = gr.Textbox(
126
+ label='Mitigation Status', value='Awaiting Input', interactive=False
127
+ )
128
+
129
+ gr.Divider()
130
+
131
+ # --- MAIN CONTROL BAR & ANALYTICS LAYOUT ---
132
+ with gr.Row():
133
+ # Left Column: Input Control Panel
134
+ with gr.Column(scale=1):
135
+ gr.Markdown('### 🎛️ High-Voltage Plant Parameters')
136
+
137
+ lagging_kvarh = gr.Number(
138
+ label='Lagging Reactive Power (kVarh)', value=2.95
139
+ )
140
+ leading_kvarh = gr.Number(
141
+ label='Leading Reactive Power (kVarh)', value=0.0
142
+ )
143
+ lagging_pf = gr.Slider(
144
+ minimum=0, maximum=100, value=73.21, label='Lagging Power Factor (%)'
145
+ )
146
+ leading_pf = gr.Slider(
147
+ minimum=0, maximum=100, value=100.0, label='Leading Power Factor (%)'
148
+ )
149
+ nsm = gr.Slider(
150
+ minimum=0,
151
+ maximum=86400,
152
+ step=900,
153
+ value=900,
154
+ label='Seconds from Midnight (NSM)',
155
+ )
156
+
157
+ with gr.Row():
158
+ week_status = gr.Dropdown(
159
+ choices=['Weekday', 'Weekend'], value='Weekday', label='Week Status'
160
+ )
161
+ day_of_week = gr.Dropdown(
162
+ choices=[
163
+ 'Monday',
164
+ 'Tuesday',
165
+ 'Wednesday',
166
+ 'Thursday',
167
+ 'Friday',
168
+ 'Saturday',
169
+ 'Sunday',
170
+ ],
171
+ value='Monday',
172
+ label='Day',
173
+ )
174
+
175
+ load_type = gr.Dropdown(
176
+ choices=['Light_Load', 'Medium_Load', 'Maximum_Load'],
177
+ value='Light_Load',
178
+ label='Load Type',
179
+ )
180
+
181
+ btn_predict = gr.Button('⚡ Run Analytics & Log Prediction', variant='primary')
182
+
183
+ # Right Column: Visual Charts & Analytics Display (Inspired by Images 1 & 2)
184
+ with gr.Column(scale=2):
185
+ gr.Markdown('### 📈 Energy Trend Analytics')
186
+ chart_output = gr.Plot(label='Historical Energy Demand Curve')
187
+
188
+ # Connect Button Event
189
+ btn_predict.click(
190
+ fn=dashboard_pipeline,
191
+ inputs=[
192
+ lagging_kvarh,
193
+ leading_kvarh,
194
+ lagging_pf,
195
+ leading_pf,
196
+ nsm,
197
+ week_status,
198
+ day_of_week,
199
+ load_type,
200
+ ],
201
+ outputs=[kpi_kwh, kpi_co2, kpi_pf, kpi_status, chart_output],
202
+ )
203
+
204
+ if __name__ == '__main__':
205
+ demo.launch(server_name='0.0.0.0', server_port=7860)