Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,33 +5,54 @@ import random
|
|
| 5 |
def load_jsonl(file):
|
| 6 |
"""读取上传的jsonl文件并解析为字典列表"""
|
| 7 |
data = []
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
output = "\n".join([f"**{key}**: {value}" for key, value in random_entry.items()])
|
| 25 |
return output
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
# 启动Gradio应用
|
| 37 |
-
|
|
|
|
| 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()
|