File size: 5,886 Bytes
870f4fc |
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 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from typing import Dict, List, Set
class ModelFilter:
def __init__(self, json_path: str = "models.json"):
with open(json_path, 'r', encoding='utf-8') as f:
self.data = json.load(f)
self.models = self.data['models']
# 收集所有可用的标签
self.all_tags = {
'data_type': set(),
'task_type': set(),
'domain': set(),
'input_type': set(),
'output_type': set()
}
# 标签类型的中文名称
self.tag_names = {
'data_type': '数据类型',
'task_type': '任务类型',
'domain': '领域',
'input_type': '输入类型',
'output_type': '输出类型'
}
for model in self.models:
tags = model['tags']
for tag_type in self.all_tags:
if tag_type in tags:
if isinstance(tags[tag_type], list):
self.all_tags[tag_type].update(tags[tag_type])
else:
self.all_tags[tag_type].add(tags[tag_type])
def print_tag_type_options(self):
"""打印标签类型选项"""
print("\n可选择的标签类型:")
for i, (tag_type, name) in enumerate(self.tag_names.items(), 1):
print(f"{i}. {name} ({tag_type})")
def print_tag_options(self, tag_type: str):
"""打印特定标签类型的可用选项"""
print(f"\n=== {self.tag_names[tag_type]} ===")
for i, tag in enumerate(sorted(self.all_tags[tag_type]), 1):
print(f"{i}. {tag}")
def filter_models(self, filters: Dict[str, Set[str]]) -> List[Dict]:
"""根据筛选条件过滤模型"""
filtered_models = []
for model in self.models:
match = True
for tag_type, filter_values in filters.items():
if not filter_values: # 如果该类型没有设置筛选条件,跳过
continue
model_tags = model['tags'].get(tag_type, [])
if isinstance(model_tags, str):
model_tags = [model_tags]
# 检查是否有交集
if not set(model_tags) & filter_values:
match = False
break
if match:
filtered_models.append(model)
return filtered_models
def print_models(self, models: List[Dict]):
"""打印模型信息"""
if not models:
print("\n没有找到匹配的模型。")
return
print(f"\n找到 {len(models)} 个匹配的模型:")
for i, model in enumerate(models, 1):
print(f"\n{i}. {model['name']}")
print(f" 描述: {model['description']}")
print(f" 数据集: {model['dataset']}")
print(f" 标签:")
for tag_type, tags in model['tags'].items():
if isinstance(tags, list):
print(f" - {self.tag_names[tag_type]}: {', '.join(tags)}")
else:
print(f" - {self.tag_names[tag_type]}: {tags}")
def get_user_input(prompt: str, valid_options: Set[str]) -> Set[str]:
"""获取用户输入的标签"""
print(f"\n{prompt}")
print("请输入标签编号(多个标签用空格分隔,直接回车跳过):")
while True:
try:
user_input = input().strip()
if not user_input:
return set()
indices = [int(x) - 1 for x in user_input.split()]
selected = set()
sorted_options = sorted(valid_options)
for idx in indices:
if 0 <= idx < len(sorted_options):
selected.add(sorted_options[idx])
else:
print(f"无效的选项编号: {idx + 1}")
continue
return selected
except ValueError:
print("请输入有效的数字编号。")
def get_tag_type_choice() -> str:
"""获取用户选择的标签类型"""
tag_types = list(ModelFilter().tag_names.keys())
while True:
try:
choice = input("\n请选择标签类型编号(直接回车开始筛选):").strip()
if not choice:
return ""
idx = int(choice) - 1
if 0 <= idx < len(tag_types):
return tag_types[idx]
else:
print("无效的选项编号,请重试。")
except ValueError:
print("请输入有效的数字编号。")
def main():
print("欢迎使用模型筛选工具!")
model_filter = ModelFilter()
filters = {}
while True:
# 显示标签类型选项
model_filter.print_tag_type_options()
# 获取用户选择的标签类型
tag_type = get_tag_type_choice()
if not tag_type:
break
# 显示所选标签类型的可用选项
model_filter.print_tag_options(tag_type)
# 获取用户选择的标签
selected = get_user_input(
f"选择{model_filter.tag_names[tag_type]}标签",
model_filter.all_tags[tag_type]
)
if selected:
filters[tag_type] = selected
# 筛选并显示结果
filtered_models = model_filter.filter_models(filters)
model_filter.print_models(filtered_models)
# 询问是否继续
if input("\n是否继续筛选?(y/n): ").lower() == 'y':
main()
else:
print("\n感谢使用!再见!")
if __name__ == "__main__":
main() |