stzhao commited on
Commit
5f8aa69
·
verified ·
1 Parent(s): c1eb185

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -17
app.py CHANGED
@@ -5,33 +5,54 @@ import random
5
  def load_jsonl(file):
6
  """读取上传的jsonl文件并解析为字典列表"""
7
  data = []
8
- file = open(file, "r")
9
- for line in file:
10
- data.append(json.loads(line))
11
  return data
12
 
13
  def random_data_viewer(file):
14
- """随机抽取一条数据并格式化输出"""
15
  if file is None:
16
- return "请上传一个JSONL文件!"
17
 
18
  data = load_jsonl(file)
19
  if len(data) == 0:
20
- return "文件为空或格式不正确!"
21
 
22
  random_entry = random.choice(data)
23
- # 将数据格式化为Markdown形式
 
 
 
 
 
 
 
 
 
 
24
  output = "\n".join([f"**{key}**: {value}" for key, value in random_entry.items()])
25
  return output
26
 
27
- # 创建Gradio界面
28
- iface = gr.Interface(
29
- fn=random_data_viewer,
30
- inputs=gr.File(file_types=[".jsonl"], label="上传JSONL文件"),
31
- outputs=gr.Textbox(label="随机数据", lines=10, max_lines=20), # 使用Textbox组件显示Markdown
32
- title="JSONL 数据查看器",
33
- description="上传一个JSONL文件,随机展示其中一条数据。",
34
- )
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # 启动Gradio应用
37
- iface.launch()
 
5
  def load_jsonl(file):
6
  """读取上传的jsonl文件并解析为字典列表"""
7
  data = []
8
+ with open(file, "r", encoding="utf-8") as f:
9
+ for line in f:
10
+ data.append(json.loads(line))
11
  return data
12
 
13
  def random_data_viewer(file):
14
+ """读取文件并随机抽取一条数据"""
15
  if file is None:
16
+ return "请上传一个JSONL文件!", None
17
 
18
  data = load_jsonl(file)
19
  if len(data) == 0:
20
+ return "文件为空或格式不正确!", None
21
 
22
  random_entry = random.choice(data)
23
+ # 格式化输出为Markdown
24
+ output = "\n".join([f"**{key}**: {value}" for key, value in random_entry.items()])
25
+ return output, data # 返回数据以存储供后续使用
26
+
27
+ def sample_more(data):
28
+ """从已有数据中再采样一条"""
29
+ if not data:
30
+ return "没有可用数据,请先上传JSONL文件!"
31
+
32
+ random_entry = random.choice(data)
33
+ # 格式化输出为Markdown
34
  output = "\n".join([f"**{key}**: {value}" for key, value in random_entry.items()])
35
  return output
36
 
37
+ # Gradio 界面
38
+ with gr.Blocks() as app:
39
+ gr.Markdown("# JSONL 数据查看器")
40
+ gr.Markdown("上传一个JSONL文件,随机展示其中一条数据。点击按钮可以重新采样。")
41
+
42
+ with gr.Row():
43
+ file_upload = gr.File(file_types=[".jsonl"], label="上传JSONL文件")
44
+ sample_button = gr.Button("再采样")
45
+
46
+ output_box = gr.Textbox(label="随机数据", lines=10, max_lines=20)
47
+
48
+ # 用于存储加载后的数据
49
+ state_data = gr.State()
50
+
51
+ # 绑定事件:上传文件后随机取一条数据
52
+ file_upload.change(random_data_viewer, inputs=file_upload, outputs=[output_box, state_data])
53
+
54
+ # 绑定事件:点击按钮后从已有数据中再采样
55
+ sample_button.click(sample_more, inputs=state_data, outputs=output_box)
56
 
57
+ # 启动 Gradio 应用
58
+ app.launch()