File size: 26,751 Bytes
d988980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28f8ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a21bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28f8ac4
dc56cce
 
 
 
 
a21bd5b
dc56cce
28f8ac4
 
dc56cce
28f8ac4
dc56cce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d988980
a21bd5b
d988980
28f8ac4
d988980
dc56cce
d988980
a21bd5b
dc56cce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a21bd5b
 
dc56cce
 
 
 
 
 
 
a21bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc56cce
 
a21bd5b
 
 
 
 
 
 
 
 
dc56cce
 
 
 
 
 
a21bd5b
 
 
dc56cce
a21bd5b
 
 
 
 
dc56cce
 
 
a21bd5b
dc56cce
 
 
a21bd5b
 
 
 
 
 
 
dc56cce
a21bd5b
dc56cce
 
 
 
 
a21bd5b
dc56cce
a21bd5b
 
dc56cce
 
 
 
 
 
a21bd5b
 
 
dc56cce
 
a21bd5b
 
 
dc56cce
 
a21bd5b
 
dc56cce
a21bd5b
 
 
 
dc56cce
 
a21bd5b
 
dc56cce
a21bd5b
dc56cce
 
a21bd5b
 
 
dc56cce
a21bd5b
 
dc56cce
 
a21bd5b
dc56cce
a21bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc56cce
 
 
 
 
a21bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc56cce
 
 
d988980
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
# import gradio as gr
# import subprocess
# import os
# import sys
# from datetime import datetime
#
# # The name of your existing training script
# TRAINING_SCRIPT = "LayoutLM_Train_Passage.py"
#
# # --- CORRECTED MODEL PATH BASED ON LayoutLM_Train_Passage.py ---
# MODEL_OUTPUT_DIR = "checkpoints"
# MODEL_FILE_NAME = "layoutlmv3_crf_passage.pth"
# MODEL_FILE_PATH = os.path.join(MODEL_OUTPUT_DIR, MODEL_FILE_NAME)
#
#
# # ----------------------------------------------------------------
#
#
# def train_model(dataset_file: gr.File, batch_size: int, epochs: int, lr: float, max_len: int, progress=gr.Progress()):
#     """
#     Handles the Gradio submission and executes the training script using subprocess.
#     """
#
#     # 1. Setup: Create output directory if it doesn't exist
#     os.makedirs(MODEL_OUTPUT_DIR, exist_ok=True)
#
#     # 2. File Handling: Use the temporary path of the uploaded file
#     # if dataset_file is None or not dataset_file.path.endswith(".json"):
#     #     return "❌ ERROR: Please upload a valid Label Studio JSON file.", None
#
#     input_path = dataset_file.path
#
#     progress(0.1, desc="Starting LayoutLMv3 Training...")
#
#     log_output = f"--- Training Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ---\n"
#
#     # 3. Construct the subprocess command
#     command = [
#         sys.executable,
#         TRAINING_SCRIPT,
#         "--mode", "train",
#         "--input", input_path,
#         "--batch_size", str(batch_size),
#         "--epochs", str(epochs),
#         "--lr", str(lr),
#         "--max_len", str(max_len)
#     ]
#
#     log_output += f"Executing command: {' '.join(command)}\n\n"
#
#     try:
#         # 4. Run the training script and capture output
#         process = subprocess.Popen(
#             command,
#             stdout=subprocess.PIPE,
#             stderr=subprocess.STDOUT,
#             text=True,
#             bufsize=1
#         )
#
#         # Stream logs in real-time
#         for line in iter(process.stdout.readline, ""):
#             log_output += line
#             yield log_output, None  # Send partial log to Gradio output
#
#         process.stdout.close()
#         return_code = process.wait()
#
#         # 5. Check for successful completion
#         if return_code == 0:
#             log_output += "\nβœ… TRAINING COMPLETE! Model saved."
#
#             # 6. Prepare download links based on script's saved path
#             model_exists = os.path.exists(MODEL_FILE_PATH)
#
#             if model_exists:
#                 log_output += f"\nModel path: {MODEL_FILE_PATH}"
#                 # Return final log, and the file path for Gradio's download component
#                 return log_output, MODEL_FILE_PATH
#             else:
#                 log_output += f"\n⚠️ WARNING: Training completed, but model file not found at expected path ({MODEL_FILE_PATH})."
#                 return log_output, None
#         else:
#             log_output += f"\n\n❌ TRAINING FAILED with return code {return_code}. Check logs above."
#             return log_output, None
#
#     except FileNotFoundError:
#         return f"❌ ERROR: The training script '{TRAINING_SCRIPT}' was not found. Ensure it is in the root directory of your Space.", None
#     except Exception as e:
#         return f"❌ An unexpected error occurred: {e}", None
#
#
# # --- Gradio Interface Setup (using Blocks for a nicer layout) ---
# with gr.Blocks(title="LayoutLMv3 Fine-Tuning App") as demo:
#     gr.Markdown("# πŸš€ LayoutLMv3 Fine-Tuning on Hugging Face Spaces")
#     gr.Markdown(
#         """
#         Upload your Label Studio JSON file, set your hyperparameters, and click **Train Model** to fine-tune the LayoutLMv3 model using your script.
#
#         **Note:** The trained model is saved in the **`checkpoints/`** folder as **`layoutlmv3_crf_passage.pth`**.
#         """
#     )
#
#     with gr.Row():
#         with gr.Column(scale=1):
#             file_input = gr.File(
#                 label="1. Upload Label Studio JSON Dataset"
#             )
#
#             gr.Markdown("---")
#             gr.Markdown("### βš™οΈ Training Parameters")
#
#             batch_size_input = gr.Slider(
#                 minimum=1, maximum=32, step=1, value=4, label="Batch Size (--batch_size)"
#             )
#             epochs_input = gr.Slider(
#                 minimum=1, maximum=20, step=1, value=5, label="Epochs (--epochs)"
#             )
#             lr_input = gr.Number(
#                 value=5e-5, label="Learning Rate (--lr)"
#             )
#             max_len_input = gr.Number(
#                 value=512, label="Max Sequence Length (--max_len)"
#             )
#
#         with gr.Column(scale=2):
#             train_button = gr.Button("πŸ”₯ Train Model", variant="primary")
#
#             log_output = gr.Textbox(
#                 label="Training Log Output",
#                 lines=20,
#                 autoscroll=True,
#                 placeholder="Click 'Train Model' to start and see real-time logs..."
#             )
#
#             gr.Markdown("---")
#             gr.Markdown(f"### πŸŽ‰ Trained Model Output (Saved to `{MODEL_OUTPUT_DIR}/`)")
#
#             # Only providing the download link for the saved .pth model file
#             model_download = gr.File(label=f"Trained Model File ({MODEL_FILE_NAME})", interactive=False)
#
#     # Define the action when the button is clicked
#     train_button.click(
#         fn=train_model,
#         inputs=[file_input, batch_size_input, epochs_input, lr_input, max_len_input],
#         outputs=[log_output, model_download]
#     )
#
# if __name__ == "__main__":
#     demo.launch(server_port=7860, server_name="0.0.0.0")


# import gradio as gr
# import subprocess
# import os
# import sys
# from datetime import datetime
#
# # The name of your existing training script
# TRAINING_SCRIPT = "LayoutLM_Train_Passage.py"
#
# # --- CORRECTED MODEL PATH BASED ON LayoutLM_Train_Passage.py ---
# MODEL_OUTPUT_DIR = "checkpoints"
# MODEL_FILE_NAME = "layoutlmv3_crf_passage.pth"
# MODEL_FILE_PATH = os.path.join(MODEL_OUTPUT_DIR, MODEL_FILE_NAME)
#
#
# # ----------------------------------------------------------------
#
#
# def train_model(dataset_file: gr.File, batch_size: int, epochs: int, lr: float, max_len: int, progress=gr.Progress()):
#     """
#     Handles the Gradio submission and executes the training script using subprocess.
#     """
#
#     # 1. Setup: Create output directory if it doesn't exist
#     os.makedirs(MODEL_OUTPUT_DIR, exist_ok=True)
#
#     # 2. File Handling: Use the temporary path of the uploaded file
#     if dataset_file is None:
#         yield "❌ ERROR: Please upload a file.", None
#         return
#
#     # FIX: Gradio returns the path in the .name attribute, not .path
#     input_path = dataset_file.name
#
#     if not input_path.lower().endswith(".json"):
#         yield "❌ ERROR: Please upload a valid Label Studio JSON file (.json).", None
#         return
#
#     progress(0.1, desc="Starting LayoutLMv3 Training...")
#
#     log_output = f"--- Training Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ---\n"
#
#     # 3. Construct the subprocess command
#     command = [
#         sys.executable,
#         TRAINING_SCRIPT,
#         "--mode", "train",
#         "--input", input_path,
#         "--batch_size", str(batch_size),
#         "--epochs", str(epochs),
#         "--lr", str(lr),
#         "--max_len", str(max_len)
#     ]
#
#     log_output += f"Executing command: {' '.join(command)}\n\n"
#     yield log_output, None  # Yield the command to the log output
#
#     try:
#         # 4. Run the training script and capture output
#         process = subprocess.Popen(
#             command,
#             stdout=subprocess.PIPE,
#             stderr=subprocess.STDOUT,
#             text=True,
#             bufsize=1
#         )
#
#         # Stream logs in real-time
#         for line in iter(process.stdout.readline, ""):
#             log_output += line
#             yield log_output, None  # Send partial log to Gradio output
#
#         process.stdout.close()
#         return_code = process.wait()
#
#         # 5. Check for successful completion
#         if return_code == 0:
#             log_output += "\nβœ… TRAINING COMPLETE! Model saved."
#
#             # 6. Prepare download links based on script's saved path
#             model_exists = os.path.exists(MODEL_FILE_PATH)
#
#             if model_exists:
#                 log_output += f"\nModel path: {MODEL_FILE_PATH}"
#                 # Return final log, and the file path for Gradio's download component
#                 return log_output, MODEL_FILE_PATH
#             else:
#                 log_output += f"\n⚠️ WARNING: Training completed, but model file not found at expected path ({MODEL_FILE_PATH})."
#                 return log_output, None
#         else:
#             log_output += f"\n\n❌ TRAINING FAILED with return code {return_code}. Check logs above."
#             return log_output, None
#
#     except FileNotFoundError:
#         return f"❌ ERROR: The training script '{TRAINING_SCRIPT}' was not found. Ensure it is in the root directory of your Space.", None
#     except Exception as e:
#         return f"❌ An unexpected error occurred: {e}", None
#
#
# # --- Gradio Interface Setup (using Blocks for a nicer layout) ---
# with gr.Blocks(title="LayoutLMv3 Fine-Tuning App") as demo:
#     gr.Markdown("# πŸš€ LayoutLMv3 Fine-Tuning on Hugging Face Spaces")
#     gr.Markdown(
#         """
#         Upload your Label Studio JSON file, set your hyperparameters, and click **Train Model** to fine-tune the LayoutLMv3 model using your script.
#
#         **Note:** The trained model is saved in the **`checkpoints/`** folder as **`layoutlmv3_crf_passage.pth`**.
#         """
#     )
#
#     with gr.Row():
#         with gr.Column(scale=1):
#             file_input = gr.File(
#                 label="1. Upload Label Studio JSON Dataset"
#             )
#
#             gr.Markdown("---")
#             gr.Markdown("### βš™οΈ Training Parameters")
#
#             batch_size_input = gr.Slider(
#                 minimum=1, maximum=32, step=1, value=4, label="Batch Size (--batch_size)"
#             )
#             epochs_input = gr.Slider(
#                 minimum=1, maximum=20, step=1, value=5, label="Epochs (--epochs)"
#             )
#             lr_input = gr.Number(
#                 value=5e-5, label="Learning Rate (--lr)"
#             )
#             max_len_input = gr.Number(
#                 value=512, label="Max Sequence Length (--max_len)"
#             )
#
#         with gr.Column(scale=2):
#             train_button = gr.Button("πŸ”₯ Train Model", variant="primary")
#
#             log_output = gr.Textbox(
#                 label="Training Log Output",
#                 lines=20,
#                 autoscroll=True,
#                 placeholder="Click 'Train Model' to start and see real-time logs..."
#             )
#
#             gr.Markdown("---")
#             gr.Markdown(f"### πŸŽ‰ Trained Model Output (Saved to `{MODEL_OUTPUT_DIR}/`)")
#
#             # Only providing the download link for the saved .pth model file
#             model_download = gr.File(label=f"Trained Model File ({MODEL_FILE_NAME})", interactive=False)
#
#     # Define the action when the button is clicked
#     train_button.click(
#         fn=train_model,
#         inputs=[file_input, batch_size_input, epochs_input, lr_input, max_len_input],
#         outputs=[log_output, model_download]
#     )
#
# if __name__ == "__main__":
#     # Removed server_port and server_name as they are often unnecessary
#     # and sometimes cause issues in managed Space environments.
#     demo.launch()

#
# import gradio as gr
# import subprocess
# import os
# import sys
# from datetime import datetime
#
# # FIX: Update the script name to the correct one you uploaded
# TRAINING_SCRIPT = "HF_LayoutLM_with_Passage.py"
#
# # --- CORRECTED MODEL PATH BASED ON YOUR SCRIPT ---
# MODEL_OUTPUT_DIR = "checkpoints"
# MODEL_FILE_NAME = "layoutlmv3_crf_passage.pth"
# MODEL_FILE_PATH = os.path.join(MODEL_OUTPUT_DIR, MODEL_FILE_NAME)
#
#
# # ----------------------------------------------------------------
#
#
# def train_model(dataset_file: gr.File, batch_size: int, epochs: int, lr: float, max_len: int, progress=gr.Progress()):
#     """
#     Handles the Gradio submission and executes the training script using subprocess.
#     """
#
#     # 1. Setup: Create output directory if it doesn't exist
#     os.makedirs(MODEL_OUTPUT_DIR, exist_ok=True)
#
#     # 2. File Handling: Use the temporary path of the uploaded file
#     if dataset_file is None:
#         yield "❌ ERROR: Please upload a file.", None
#         return
#
#     # Using .name (Corrected in previous steps)
#     input_path = dataset_file.name
#
#     if not input_path.lower().endswith(".json"):
#         yield "❌ ERROR: Please upload a valid Label Studio JSON file (.json).", None
#         return
#
#     progress(0.1, desc="Starting LayoutLMv3 Training...")
#
#     log_output = f"--- Training Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ---\n"
#
#     # 3. Construct the subprocess command
#     command = [
#         sys.executable,
#         # Now uses the corrected TRAINING_SCRIPT variable
#         TRAINING_SCRIPT,
#         "--mode", "train",
#         "--input", input_path,
#         "--batch_size", str(batch_size),
#         "--epochs", str(epochs),
#         "--lr", str(lr),
#         "--max_len", str(max_len)
#     ]
#
#     log_output += f"Executing command: {' '.join(command)}\n\n"
#     yield log_output, None  # Yield the command to the log output
#
#     try:
#         # 4. Run the training script and capture output
#         process = subprocess.Popen(
#             command,
#             stdout=subprocess.PIPE,
#             stderr=subprocess.STDOUT,
#             text=True,
#             bufsize=1
#         )
#
#         # Stream logs in real-time
#         for line in iter(process.stdout.readline, ""):
#             log_output += line
#             yield log_output, None  # Send partial log to Gradio output
#
#         process.stdout.close()
#         return_code = process.wait()
#
#         # 5. Check for successful completion
#         if return_code == 0:
#             log_output += "\nβœ… TRAINING COMPLETE! Model saved."
#
#             # 6. Prepare download links based on script's saved path
#             model_exists = os.path.exists(MODEL_FILE_PATH)
#
#             if model_exists:
#                 log_output += f"\nModel path: {MODEL_FILE_PATH}"
#                 # Return final log, and the file path for Gradio's download component
#                 return log_output, MODEL_FILE_PATH
#             else:
#                 log_output += f"\n⚠️ WARNING: Training completed, but model file not found at expected path ({MODEL_FILE_PATH})."
#                 return log_output, None
#         else:
#             log_output += f"\n\n❌ TRAINING FAILED with return code {return_code}. Check logs above."
#             return log_output, None
#
#     except FileNotFoundError:
#         return f"❌ ERROR: The training script '{TRAINING_SCRIPT}' was not found. Ensure it is in the root directory of your Space.", None
#     except Exception as e:
#         return f"❌ An unexpected error occurred: {e}", None
#
#
# # --- Gradio Interface Setup (using Blocks for a nicer layout) ---
# with gr.Blocks(title="LayoutLMv3 Fine-Tuning App") as demo:
#     gr.Markdown("# πŸš€ LayoutLMv3 Fine-Tuning on Hugging Face Spaces")
#     gr.Markdown(
#         """
#         Upload your Label Studio JSON file, set your hyperparameters, and click **Train Model** to fine-tune the LayoutLMv3 model using your script.
#
#         **Note:** The trained model is saved in the **`checkpoints/`** folder as **`layoutlmv3_crf_passage.pth`**.
#         """
#     )
#
#     with gr.Row():
#         with gr.Column(scale=1):
#             file_input = gr.File(
#                 label="1. Upload Label Studio JSON Dataset"
#             )
#
#             gr.Markdown("---")
#             gr.Markdown("### βš™οΈ Training Parameters")
#
#             batch_size_input = gr.Slider(
#                 minimum=1, maximum=32, step=1, value=4, label="Batch Size (--batch_size)"
#             )
#             epochs_input = gr.Slider(
#                 minimum=1, maximum=20, step=1, value=5, label="Epochs (--epochs)"
#             )
#             lr_input = gr.Number(
#                 value=5e-5, label="Learning Rate (--lr)"
#             )
#             max_len_input = gr.Number(
#                 value=512, label="Max Sequence Length (--max_len)"
#             )
#
#         with gr.Column(scale=2):
#             train_button = gr.Button("πŸ”₯ Train Model", variant="primary")
#
#             log_output = gr.Textbox(
#                 label="Training Log Output",
#                 lines=20,
#                 autoscroll=True,
#                 placeholder="Click 'Train Model' to start and see real-time logs..."
#             )
#
#             gr.Markdown("---")
#             gr.Markdown(f"### πŸŽ‰ Trained Model Output (Saved to `{MODEL_OUTPUT_DIR}/`)")
#
#             # Only providing the download link for the saved .pth model file
#             model_download = gr.File(label=f"Trained Model File ({MODEL_FILE_NAME})", interactive=False)
#
#     # Define the action when the button is clicked
#     train_button.click(
#         fn=train_model,
#         inputs=[file_input, batch_size_input, epochs_input, lr_input, max_len_input],
#         outputs=[log_output, model_download]
#     )
#
# if __name__ == "__main__":
#     demo.launch()


import gradio as gr
import subprocess
import os
import sys
from datetime import datetime
import shutil

# FIX: Update the script name to the correct one you uploaded
TRAINING_SCRIPT = "HF_LayoutLM_with_Passage.py"

# --- CORRECTED MODEL PATH BASED ON YOUR SCRIPT ---
MODEL_OUTPUT_DIR = "checkpoints"
MODEL_FILE_NAME = "layoutlmv3_crf_passage.pth"
MODEL_FILE_PATH = os.path.join(MODEL_OUTPUT_DIR, MODEL_FILE_NAME)


# ----------------------------------------------------------------


def train_model(dataset_file: gr.File, batch_size: int, epochs: int, lr: float, max_len: int, progress=gr.Progress()):
    """
    Handles the Gradio submission and executes the training script using subprocess.
    """

    # 1. Setup: Create output directory if it doesn't exist
    os.makedirs(MODEL_OUTPUT_DIR, exist_ok=True)

    # 2. File Handling: Use the temporary path of the uploaded file
    if dataset_file is None:
        return "❌ ERROR: Please upload a file.", None

    # Using .name (Corrected in previous steps)
    input_path = dataset_file.name

    if not input_path.lower().endswith(".json"):
        return "❌ ERROR: Please upload a valid Label Studio JSON file (.json).", None

    progress(0.1, desc="Starting LayoutLMv3 Training...")

    log_output = f"--- Training Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ---\n"

    # 3. Construct the subprocess command
    command = [
        sys.executable,
        TRAINING_SCRIPT,
        "--mode", "train",
        "--input", input_path,
        "--batch_size", str(batch_size),
        "--epochs", str(epochs),
        "--lr", str(lr),
        "--max_len", str(max_len)
    ]

    log_output += f"Executing command: {' '.join(command)}\n\n"

    try:
        # 4. Run the training script and capture output
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1
        )

        # Stream logs in real-time
        for line in iter(process.stdout.readline, ""):
            log_output += line
            # Print to console as well for debugging
            print(line, end='')

        process.stdout.close()
        return_code = process.wait()

        # 5. Check for successful completion
        if return_code == 0:
            log_output += "\nβœ… TRAINING COMPLETE! Model saved."
            print("\nβœ… TRAINING COMPLETE! Model saved.")

            # 6. Verify model file exists
            if os.path.exists(MODEL_FILE_PATH):
                file_size = os.path.getsize(MODEL_FILE_PATH) / (1024 * 1024)  # Size in MB
                log_output += f"\nπŸ“¦ Model file: {MODEL_FILE_PATH}"
                log_output += f"\nπŸ“Š Model size: {file_size:.2f} MB"
                log_output += f"\n⬇️ Click the download button below to save your model!"

                print(f"\nβœ… Model exists at: {MODEL_FILE_PATH} ({file_size:.2f} MB)")

                # Create a copy in the root directory for easier access
                root_copy = MODEL_FILE_NAME
                try:
                    shutil.copy2(MODEL_FILE_PATH, root_copy)
                    log_output += f"\nπŸ“‹ Copy created: {root_copy}"
                    print(f"βœ… Created copy at: {root_copy}")
                except Exception as e:
                    log_output += f"\n⚠️ Could not create root copy: {e}"
                    root_copy = MODEL_FILE_PATH

                # Return the full absolute path to ensure Gradio can find it
                absolute_path = os.path.abspath(root_copy)
                log_output += f"\nπŸ”— Download path: {absolute_path}"

                return log_output, absolute_path
            else:
                log_output += f"\n⚠️ WARNING: Training completed, but model file not found at expected path ({MODEL_FILE_PATH})."
                log_output += f"\nπŸ” Checking directory contents..."

                # List files in checkpoints directory for debugging
                if os.path.exists(MODEL_OUTPUT_DIR):
                    files = os.listdir(MODEL_OUTPUT_DIR)
                    log_output += f"\nπŸ“ Files in {MODEL_OUTPUT_DIR}: {files}"
                else:
                    log_output += f"\n❌ Directory {MODEL_OUTPUT_DIR} does not exist!"

                return log_output, None
        else:
            log_output += f"\n\n❌ TRAINING FAILED with return code {return_code}. Check logs above."
            return log_output, None

    except FileNotFoundError:
        error_msg = f"❌ ERROR: The training script '{TRAINING_SCRIPT}' was not found. Ensure it is in the root directory of your Space."
        print(error_msg)
        return error_msg, None
    except Exception as e:
        error_msg = f"❌ An unexpected error occurred: {e}"
        print(error_msg)
        import traceback
        print(traceback.format_exc())
        return error_msg, None


# --- Gradio Interface Setup (using Blocks for a nicer layout) ---
with gr.Blocks(title="LayoutLMv3 Fine-Tuning App", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸš€ LayoutLMv3 Fine-Tuning on Hugging Face Spaces")
    gr.Markdown(
        """
        Upload your Label Studio JSON file, set your hyperparameters, and click **Train Model** to fine-tune the LayoutLMv3 model.

        **⚠️ IMPORTANT - Free Tier Users:**
        - **Download your model IMMEDIATELY** after training completes! 
        - The model file is **temporary** and will be deleted when the Space restarts.
        - The download button will appear below once training is complete.
        - Model is saved as: **`layoutlmv3_crf_passage.pth`**

        **⏱️ Timeout Note:** Training may timeout on free tier. Consider reducing epochs or batch size for faster training.
        """
    )

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“ Dataset Upload")
            file_input = gr.File(
                label="Upload Label Studio JSON Dataset",
                file_types=[".json"]
            )

            gr.Markdown("---")
            gr.Markdown("### βš™οΈ Training Parameters")

            batch_size_input = gr.Slider(
                minimum=1, maximum=16, step=1, value=4,
                label="Batch Size",
                info="Smaller = less memory, slower training"
            )
            epochs_input = gr.Slider(
                minimum=1, maximum=10, step=1, value=3,
                label="Epochs",
                info="Fewer epochs = faster training (recommended: 3-5)"
            )
            lr_input = gr.Number(
                value=5e-5, label="Learning Rate",
                info="Default: 5e-5"
            )
            max_len_input = gr.Slider(
                minimum=128, maximum=512, step=128, value=512,
                label="Max Sequence Length",
                info="Shorter = faster training, less memory"
            )

            train_button = gr.Button("πŸ”₯ Start Training", variant="primary", size="lg")

        with gr.Column(scale=2):
            gr.Markdown("### πŸ“Š Training Progress")

            log_output = gr.Textbox(
                label="Training Logs",
                lines=25,
                max_lines=30,
                autoscroll=True,
                show_copy_button=True,
                placeholder="Click 'Start Training' to begin...\n\nLogs will appear here in real-time."
            )

            gr.Markdown("### ⬇️ Download Trained Model")

            model_download = gr.File(
                label="Trained Model File (layoutlmv3_crf_passage.pth)",
                interactive=False,
                visible=True
            )

            gr.Markdown(
                """
                **πŸ“₯ Download Instructions:**
                1. Wait for training to complete (βœ… appears in logs)
                2. Click the download button/icon that appears above
                3. Save the `.pth` file to your local machine
                4. **Do this immediately** - file is temporary!

                **πŸ”§ Troubleshooting:**
                - If download button doesn't appear, check the logs for errors
                - Try reducing epochs or batch size if timeout occurs
                - Ensure your JSON file is properly formatted
                """
            )

    # Define the action when the button is clicked
    train_button.click(
        fn=train_model,
        inputs=[file_input, batch_size_input, epochs_input, lr_input, max_len_input],
        outputs=[log_output, model_download],
        api_name="train"
    )

    # Add example info
    gr.Markdown(
        """
        ---
        ### πŸ“– About
        This Space fine-tunes LayoutLMv3 with CRF for document understanding tasks including:
        - Questions, Options, Answers
        - Section Headings
        - Passages

        **Model Details:** LayoutLMv3-base + CRF layer for sequence labeling
        """
    )

if __name__ == "__main__":
    demo.launch()