朱东升 commited on
Commit
890be77
·
1 Parent(s): b39d9cc
Files changed (1) hide show
  1. app.py +173 -43
app.py CHANGED
@@ -470,7 +470,18 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
470
  with gr.Tab("任务队列状态"):
471
  status_html = gr.HTML(render_queue_status)
472
  refresh_button = gr.Button("刷新状态")
473
- refresh_button.click(fn=refresh_ui, outputs=status_html)
 
 
 
 
 
 
 
 
 
 
 
474
 
475
  # 使用正确的轮询方式替代
476
  dummy_input = gr.Textbox(value="", visible=False)
@@ -481,7 +492,7 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
481
  # JavaScript-based auto-refresh solution
482
  gr.HTML("""
483
  <script>
484
- // 为Hugging Face Spaces环境优化的自动刷新机制
485
  function setupAutoRefresh() {
486
  // 在HF Spaces中更保守的刷新间隔,避免过多请求
487
  const refreshInterval = 3000; // 3秒刷新一次
@@ -491,32 +502,75 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
491
  // 查找刷新按钮并模拟点击
492
  function autoRefresh() {
493
  try {
494
- // 获取所有按钮元素
495
  const buttons = document.querySelectorAll('button');
496
- // 查找刷新状态按钮
 
 
497
  for (const button of buttons) {
498
- if (button.textContent === '刷新状态') {
499
- button.click();
500
-
501
- // 检查任务数量是否变化 (动态优化刷新频率的预留代码)
502
- setTimeout(() => {
503
- const activeTasks = document.querySelectorAll('table tbody tr');
504
- const currentTaskCount = activeTasks.length;
505
-
506
- if (currentTaskCount === lastTaskCount) {
507
- consecutiveNoChange++;
508
- } else {
509
- consecutiveNoChange = 0;
510
- }
511
-
512
- lastTaskCount = currentTaskCount;
513
- }, 500);
514
-
515
  break;
516
  }
517
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  } catch (e) {
519
- console.error("Auto-refresh error:", e);
520
  }
521
  }
522
 
@@ -535,8 +589,8 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
535
  }
536
  });
537
 
538
- // 设置首次加载时立即刷新一次
539
- setTimeout(autoRefresh, 100);
540
  }
541
 
542
  // 确保在DOM完全加载后运行
@@ -560,8 +614,14 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
560
 
561
  with gr.Column():
562
  result_output = gr.Textbox(label="提交结果", lines=5)
563
-
564
- submit_button.click(fn=submit_json_data, inputs=json_input, outputs=[result_output, status_html])
 
 
 
 
 
 
565
 
566
  with gr.Tab("API文档"):
567
  gr.Markdown("""
@@ -621,23 +681,93 @@ with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
621
  with gr.Row(visible=False):
622
  api_input = gr.JSON()
623
  api_output = gr.JSON()
624
- api_input.change(fn=evaluate, inputs=api_input, outputs=api_output)
 
 
 
 
 
 
 
625
 
626
  if __name__ == "__main__":
627
- # 设置队列,并添加API支持
628
- demo.queue(api_open=True, concurrency_count=2, max_size=30)
629
-
630
- # 针对Hugging Face Spaces环境的优化配置
631
- is_hf_space = os.environ.get("SPACE_ID") is not None
632
- server_port = int(os.environ.get("PORT", 7860))
633
- server_name = "0.0.0.0" if is_hf_space else "127.0.0.1"
634
 
635
- # 启动应用
636
- demo.launch(
637
- server_name=server_name,
638
- server_port=server_port,
639
- share=False, # 在HF Spaces环境中无需share
640
- debug=False, # 在HF Spaces环境中关闭调试,提高稳定性
641
- show_api=True,
642
- max_threads=2 # 限制最大线程数,避免资源耗尽
643
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  with gr.Tab("任务队列状态"):
471
  status_html = gr.HTML(render_queue_status)
472
  refresh_button = gr.Button("刷新状态")
473
+
474
+ # 根据Gradio版本使用不同的事件注册方法
475
+ if 'gradio_version' not in locals():
476
+ import gradio
477
+ gradio_version = getattr(gradio, "__version__", "unknown")
478
+
479
+ if gradio_version.startswith("3."):
480
+ # Gradio 3.x 方式
481
+ refresh_button.click(fn=refresh_ui, outputs=status_html, concurrency_limit=2)
482
+ else:
483
+ # Gradio 4.x 方式 (不使用concurrency_limit参数)
484
+ refresh_button.click(fn=refresh_ui, outputs=status_html)
485
 
486
  # 使用正确的轮询方式替代
487
  dummy_input = gr.Textbox(value="", visible=False)
 
492
  # JavaScript-based auto-refresh solution
493
  gr.HTML("""
494
  <script>
495
+ // 兼容Gradio 3.x和4.x的自动刷新机制
496
  function setupAutoRefresh() {
497
  // 在HF Spaces中更保守的刷新间隔,避免过多请求
498
  const refreshInterval = 3000; // 3秒刷新一次
 
502
  // 查找刷新按钮并模拟点击
503
  function autoRefresh() {
504
  try {
505
+ // 兼容Gradio 3.x和4.x的按钮查找方法
506
  const buttons = document.querySelectorAll('button');
507
+ let refreshButton = null;
508
+
509
+ // 尝试通过文本查找按钮
510
  for (const button of buttons) {
511
+ if (button.textContent === '刷新状态' ||
512
+ button.textContent.includes('刷新') ||
513
+ button.innerHTML.includes('刷新状态')) {
514
+ refreshButton = button;
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  break;
516
  }
517
  }
518
+
519
+ // 如果没找到,尝试查找第一个标签页中的第一个按钮
520
+ if (!refreshButton) {
521
+ const firstTab = document.querySelector('.tabitem');
522
+ if (firstTab) {
523
+ const firstTabButton = firstTab.querySelector('button');
524
+ if (firstTabButton) {
525
+ refreshButton = firstTabButton;
526
+ }
527
+ }
528
+ }
529
+
530
+ // 如果找到按钮,模拟点击
531
+ if (refreshButton) {
532
+ refreshButton.click();
533
+ console.log("自动刷新已触发");
534
+ } else {
535
+ console.warn("未找到刷新按钮");
536
+ // 如果找不到按钮,尝试重新加载整个页面
537
+ // 但要限制频率,避免无限刷新
538
+ if (consecutiveNoChange > 10) {
539
+ console.log("长时间未找到刷新按钮,刷新页面");
540
+ location.reload();
541
+ return;
542
+ }
543
+ }
544
+
545
+ // 在Gradio 3.x和4.x中检查任务数量变化
546
+ setTimeout(() => {
547
+ // 尝试不同的选择器来适配不同版本
548
+ const tables = document.querySelectorAll('table');
549
+ let activeTasks = [];
550
+
551
+ if (tables.length > 0) {
552
+ // 在所有表格中查找行
553
+ for (const table of tables) {
554
+ const rows = table.querySelectorAll('tbody tr');
555
+ if (rows.length > 0) {
556
+ activeTasks = rows;
557
+ break;
558
+ }
559
+ }
560
+ }
561
+
562
+ const currentTaskCount = activeTasks.length || 0;
563
+
564
+ if (currentTaskCount === lastTaskCount) {
565
+ consecutiveNoChange++;
566
+ } else {
567
+ consecutiveNoChange = 0;
568
+ }
569
+
570
+ lastTaskCount = currentTaskCount;
571
+ }, 500);
572
  } catch (e) {
573
+ console.error("自动刷新错误:", e);
574
  }
575
  }
576
 
 
589
  }
590
  });
591
 
592
+ // 设置首次加载时立即刷新一次,但稍微延迟确保DOM已加载
593
+ setTimeout(autoRefresh, 500);
594
  }
595
 
596
  // 确保在DOM完全加载后运行
 
614
 
615
  with gr.Column():
616
  result_output = gr.Textbox(label="提交结果", lines=5)
617
+
618
+ # 根据Gradio版本使用不同的事件注册方法
619
+ if gradio_version.startswith("3."):
620
+ # Gradio 3.x 方式
621
+ submit_button.click(fn=submit_json_data, inputs=json_input, outputs=[result_output, status_html], concurrency_limit=2)
622
+ else:
623
+ # Gradio 4.x 方式
624
+ submit_button.click(fn=submit_json_data, inputs=json_input, outputs=[result_output, status_html])
625
 
626
  with gr.Tab("API文档"):
627
  gr.Markdown("""
 
681
  with gr.Row(visible=False):
682
  api_input = gr.JSON()
683
  api_output = gr.JSON()
684
+
685
+ # 根据Gradio版本使用不同的事件注册方法
686
+ if gradio_version.startswith("3."):
687
+ # Gradio 3.x 方式
688
+ api_input.change(fn=evaluate, inputs=api_input, outputs=api_output, concurrency_limit=2)
689
+ else:
690
+ # Gradio 4.x 方式
691
+ api_input.change(fn=evaluate, inputs=api_input, outputs=api_output)
692
 
693
  if __name__ == "__main__":
694
+ # 检测Gradio版本以适配不同版本的API
695
+ import gradio
696
+ gradio_version = getattr(gradio, "__version__", "unknown")
697
+ print(f"当前Gradio版本: {gradio_version}")
 
 
 
698
 
699
+ try:
700
+ # 设置队列,并添加API支持
701
+ try:
702
+ # 根据Gradio版本使用不同的队列配置
703
+ if gradio_version.startswith("3."):
704
+ # Gradio 3.x 版本
705
+ demo.queue(api_open=True, max_size=30)
706
+ else:
707
+ # Gradio 4.x 或更高版本可能有不同的队列API
708
+ try:
709
+ # 尝试新版本的queue方法
710
+ demo.queue(api_name="/api", max_size=30)
711
+ except:
712
+ # 如果失败,尝试不带参数的queue方法
713
+ demo.queue()
714
+ except Exception as e:
715
+ # 任何队列配置错误,记录后继续
716
+ print(f"配置队列时出错: {e}")
717
+ print("继续启动应用,但队列功能可能不可用")
718
+
719
+ # 针对Hugging Face Spaces环境的优化配置
720
+ is_hf_space = os.environ.get("SPACE_ID") is not None
721
+ server_port = int(os.environ.get("PORT", 7860))
722
+ server_name = "0.0.0.0" if is_hf_space else "127.0.0.1"
723
+
724
+ # 尝试使用兼容所有版本的参数启动
725
+ launch_kwargs = {
726
+ "server_name": server_name,
727
+ "server_port": server_port,
728
+ "share": False,
729
+ }
730
+
731
+ # 对于Gradio 3.x添加额外参数
732
+ if gradio_version.startswith("3."):
733
+ launch_kwargs.update({
734
+ "debug": False,
735
+ "show_api": True,
736
+ "max_threads": 5,
737
+ "concurrency_limit": 2
738
+ })
739
+
740
+ # 启动应用
741
+ demo.launch(**launch_kwargs)
742
+ except Exception as e:
743
+ # 记录错误并使用最简配置重试
744
+ print(f"启动时发生错误: {e}")
745
+ print("使用最小配置重试...")
746
+ try:
747
+ # 最小配置,确保应用能启动
748
+ demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
749
+ except Exception as e2:
750
+ print(f"最小配置启动也失败: {e2}")
751
+
752
+ # 终极回退方案:创建最简单的接口并启动
753
+ print("尝试创建备用界面...")
754
+ try:
755
+ import gradio as gr
756
+
757
+ def simple_evaluate(json_data):
758
+ try:
759
+ return evaluate(json.loads(json_data) if isinstance(json_data, str) else json_data)
760
+ except Exception as e:
761
+ return {"error": str(e)}
762
+
763
+ backup_demo = gr.Interface(
764
+ fn=simple_evaluate,
765
+ inputs=gr.Textbox(label="JSON输入"),
766
+ outputs=gr.JSON(label="结果"),
767
+ title="代码评估服务 (备用界面)",
768
+ description="原界面启动失败,这是简化版本"
769
+ )
770
+
771
+ backup_demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
772
+ except Exception as e3:
773
+ print(f"备用界面也启动失败: {e3}")