|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Automatically fetch the list of all models for the FlagRelease organization via the ModelScope official API. |
| 4 | +Version: 2.1 (Enhanced detection, compatible with both dictionary and list types for the Model field) |
| 5 | +""" |
| 6 | + |
| 7 | +import requests |
| 8 | +import json |
| 9 | +import time |
| 10 | +import os |
| 11 | +from collections import Counter |
| 12 | + |
| 13 | +def fetch_all_models(): |
| 14 | + url = "https://modelscope.cn/api/v1/dolphin/models" |
| 15 | + all_models = [] |
| 16 | + page = 1 |
| 17 | + page_size = 20 |
| 18 | + |
| 19 | + payload_template = { |
| 20 | + "PageSize": page_size, |
| 21 | + "PageNumber": 1, |
| 22 | + "SortBy": "GmtModified", |
| 23 | + "Name": "", |
| 24 | + "IncludePrePublish": True, |
| 25 | + "Criterion": [{"category": "organizations", "predicate": "contains", "values": ["FlagRelease"]}] |
| 26 | + } |
| 27 | + |
| 28 | + headers = { |
| 29 | + 'Content-Type': 'application/json', |
| 30 | + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', |
| 31 | + 'Accept': 'application/json, text/plain, */*', |
| 32 | + 'Referer': 'https://modelscope.cn/organization/FlagRelease?tab=model', |
| 33 | + 'Origin': 'https://modelscope.cn', |
| 34 | + } |
| 35 | + |
| 36 | + print(f"Starting to fetch model list ({page_size} per page)...") |
| 37 | + |
| 38 | + while page <= 50: # Safety upper limit |
| 39 | + payload_template["PageNumber"] = page |
| 40 | + try: |
| 41 | + print(f" Fetching page {page}...") |
| 42 | + resp = requests.put(url, headers=headers, data=json.dumps(payload_template), timeout=30) |
| 43 | + resp.raise_for_status() |
| 44 | + data = resp.json() |
| 45 | + |
| 46 | + # 1. Check basic response structure |
| 47 | + if data.get('Code') not in [200, '200']: |
| 48 | + print(f" Abnormal response code: {data.get('Code')} - {data.get('Message')}") |
| 49 | + break |
| 50 | + |
| 51 | + data_field = data.get('Data', {}) |
| 52 | + if not isinstance(data_field, dict): |
| 53 | + print(f" The 'Data' field is not a dictionary: {type(data_field)}") |
| 54 | + break |
| 55 | + |
| 56 | + # 2. Core: Intelligently parse the 'Model' field |
| 57 | + model_container = data_field.get('Model') |
| 58 | + items_to_process = [] |
| 59 | + |
| 60 | + if isinstance(model_container, list): |
| 61 | + print(f" The 'Model' field is a list, length: {len(model_container)}") |
| 62 | + items_to_process = model_container |
| 63 | + elif isinstance(model_container, dict): |
| 64 | + print(f" The 'Model' field is a dictionary, its keys: {list(model_container.keys())}") |
| 65 | + # Try to find a list within this dictionary |
| 66 | + possible_list_keys = ['Items', 'Models', 'List', 'records', 'data', 'hits'] |
| 67 | + found = False |
| 68 | + for key in possible_list_keys: |
| 69 | + if key in model_container and isinstance(model_container[key], list): |
| 70 | + items_to_process = model_container[key] |
| 71 | + print(f" Found a list in Model['{key}'], length: {len(items_to_process)}") |
| 72 | + found = True |
| 73 | + break |
| 74 | + if not found: |
| 75 | + print(" Warning: No common list field found in the Model dictionary.") |
| 76 | + else: |
| 77 | + print(f" Unexpected type for 'Model' field: {type(model_container)}") |
| 78 | + |
| 79 | + # 3. Process the found model entries |
| 80 | + current_page_count = 0 |
| 81 | + if items_to_process: |
| 82 | + for item in items_to_process: |
| 83 | + model_id = None |
| 84 | + if isinstance(item, dict): |
| 85 | + # Try multiple possible field names |
| 86 | + model_id = item.get('model_id') or item.get('ModelId') or item.get('id') |
| 87 | + if not model_id and item.get('Name'): |
| 88 | + org = item.get('Organization', {}).get('Name', 'FlagRelease') |
| 89 | + model_id = f"{org}/{item['Name']}" |
| 90 | + |
| 91 | + if model_id: |
| 92 | + if not model_id.startswith('FlagRelease/'): |
| 93 | + model_id = f"FlagRelease/{model_id}" |
| 94 | + if model_id not in all_models: |
| 95 | + all_models.append(model_id) |
| 96 | + current_page_count += 1 |
| 97 | + if current_page_count <= 3: # Print only the first 3 per page to avoid clutter |
| 98 | + print(f" Found: {model_id}") |
| 99 | + print(f" Page {page} extracted {current_page_count} new models.") |
| 100 | + else: |
| 101 | + print(f" Page {page} has no processable model entries.") |
| 102 | + |
| 103 | + # 4. Pagination judgment |
| 104 | + if current_page_count < page_size: |
| 105 | + print(f" Reached the last page (items on this page {current_page_count} < {page_size}), stopping pagination.") |
| 106 | + break |
| 107 | + |
| 108 | + page += 1 |
| 109 | + time.sleep(0.3) |
| 110 | + |
| 111 | + except Exception as e: |
| 112 | + print(f" Error processing page {page}: {type(e).__name__}: {e}") |
| 113 | + break |
| 114 | + |
| 115 | + return all_models |
| 116 | + |
| 117 | +if __name__ == '__main__': |
| 118 | + print("=" * 60) |
| 119 | + print("FlagRelease Organization Model List Fetcher v2.1 (Enhanced Detection)") |
| 120 | + print("=" * 60) |
| 121 | + models = fetch_all_models() |
| 122 | + |
| 123 | + if not models: |
| 124 | + print("\nWarning: Failed to fetch models. Please run diagnostics or check network.") |
| 125 | + else: |
| 126 | + unique_models = sorted(set(models)) |
| 127 | + print(f"\nSuccessfully fetched {len(unique_models)} unique models.") |
| 128 | + |
| 129 | + # Save the file (adjust the path according to your project structure) |
| 130 | + script_dir = os.path.dirname(os.path.abspath(__file__)) |
| 131 | + output_path = os.path.normpath(os.path.join(script_dir, '..', 'flagrelease_en', 'model_list.txt')) |
| 132 | + os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| 133 | + |
| 134 | + with open(output_path, 'w', encoding='utf-8') as f: |
| 135 | + for model in unique_models: |
| 136 | + f.write(f"{model}\n") |
| 137 | + print(f"List saved to: {output_path}") |
| 138 | + |
| 139 | + # Simple statistics |
| 140 | + series_counter = Counter() |
| 141 | + for model in unique_models: |
| 142 | + short_name = model.replace('FlagRelease/', '') |
| 143 | + series = short_name.split('-')[0] if '-' in short_name else short_name[:10] |
| 144 | + series_counter[series] += 1 |
| 145 | + print(f"Total of {len(series_counter)} different model series.") |
0 commit comments