tomo2chin2 commited on
Commit
93f9458
·
verified ·
1 Parent(s): f1c1b55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -143
app.py CHANGED
@@ -11,93 +11,22 @@ MODEL_REPO = os.environ.get("MODEL_REPO", None)
11
  LORA_REPO = os.environ.get("LORA_REPO", None)
12
  CIVITAI_TOKEN = os.environ.get("CIVITAI_TOKEN", None) # Civitai用トークン
13
 
14
- # Hugging Face APIの初期化
15
  api = HfApi()
16
 
17
- def extract_model_id(url):
18
- """
19
- CivitaiのダウンロードURLからモデルIDを抽出する関数。
20
- 例: https://civitai.com/api/download/models/546416@685247?type=Model&format=SafeTensor
21
- から '546416' を抽出。
22
- """
23
- match = re.search(r'/api/download/models/([\w@]+)', url)
24
- if match:
25
- full_id = match.group(1)
26
- # '@'が含まれている場合、前半部分を使用
27
- if '@' in full_id:
28
- return full_id.split('@')[0]
29
- return full_id
30
- else:
31
- return None
32
-
33
- def get_metadata(model_id):
34
- """
35
- Civitai APIからモデルのトリガーワードと推奨強度を取得する関数。
36
- """
37
- if not model_id:
38
- return "N/A", "N/A"
39
-
40
- api_url = f"https://civitai.com/api/v1/models/{model_id}"
41
- headers = {}
42
- if CIVITAI_TOKEN:
43
- headers["Authorization"] = f"Bearer {CIVITAI_TOKEN}"
44
-
45
- try:
46
- response = requests.get(api_url, headers=headers)
47
- response.raise_for_status()
48
- data = response.json()
49
-
50
- # デバッグ: レスポンス全体を確認
51
- print("Civitai API Response:")
52
- print(json.dumps(data, indent=4, ensure_ascii=False))
53
-
54
- # トリガーワードの取得
55
- # 実際のフィールド名を確認し、適宜修正してください
56
- trigger_words = data.get('trainedWords', 'N/A') # 例: ['word1', 'word2']
57
-
58
- # 推奨強度の取得
59
- description = data.get('description', '')
60
- # 正規表現を柔軟にして、様々な記述形式に対応
61
- strength_match = re.search(r'strength[:=]?\s*([\d.]+)', description, re.IGNORECASE)
62
- if strength_match:
63
- strength = float(strength_match.group(1))
64
- else:
65
- strength = "N/A"
66
-
67
- return strength, trigger_words
68
- except Exception as e:
69
- print(f"メタデータ取得エラー: {e}")
70
- return "N/A", "N/A"
71
-
72
  def download_and_upload(url, repo_type):
73
  if not url or not repo_type:
74
  return "URLまたはタイプが未指定です。"
75
 
76
- # URLのバリデーション
77
- def is_valid_civitai_url(url):
78
- pattern = r'https?://civitai\.com/api/download/models/[\w@]+\?type=(Model|LoRA)&format=SafeTensor'
79
- return re.match(pattern, url) is not None
80
-
81
- if not is_valid_civitai_url(url):
82
- return "無効なCivitaiモデルAPIのURLです。形式を確認してください。"
83
-
84
- # モデルIDの抽出
85
- model_id = extract_model_id(url)
86
- if not model_id:
87
- return "URLからモデルIDを抽出できませんでした。URL形式を確認してください。"
88
-
89
  headers = {}
90
  if CIVITAI_TOKEN:
91
  headers["Authorization"] = f"Bearer {CIVITAI_TOKEN}"
92
 
93
  try:
94
- # ファイルのダウンロード
95
  response = requests.get(url, headers=headers)
96
  response.raise_for_status()
97
  except Exception as e:
98
  return f"ファイルのダウンロードに失敗しました: {e}"
99
 
100
- # ファイル名の取得
101
  content_disp = response.headers.get("content-disposition", "")
102
  filename = None
103
  if content_disp:
@@ -107,65 +36,19 @@ def download_and_upload(url, repo_type):
107
 
108
  if not filename:
109
  filename = "downloaded_file.bin"
 
 
 
110
 
111
- # ファイルの保存
112
- try:
113
- with open(filename, "wb") as f:
114
- f.write(response.content)
115
- except Exception as e:
116
- return f"ファイルの保存に失敗しました: {e}"
117
-
118
- # メタデータの取得
119
- strength, trigger_words = get_metadata(model_id)
120
-
121
- # メタデータのダウンロード
122
- metadata_filename = "metadata.json"
123
- metadata = []
124
- target_repo = MODEL_REPO if repo_type == "model" else LORA_REPO
125
 
126
  if not target_repo:
127
  return f"{repo_type}用リポジトリが環境変数で設定されていません。"
128
 
129
  try:
130
- # メタデータファイルをリポジトリからダウンロード
131
- api.repo_download_file(
132
- repo_id=target_repo,
133
- path=metadata_filename,
134
- local_dir=".",
135
- local_dir_use_symlinks=False,
136
- token=HF_TOKEN
137
- )
138
-
139
- # ダウンロードしたメタデータファイルを読み込む
140
- with open(metadata_filename, "r", encoding="utf-8") as f:
141
- metadata = json.load(f)
142
- except Exception as e:
143
- # メタデータファイルが存在しない場合は新規作成
144
- print(f"メタデータファイルのダウンロードまたは読み込みに失敗しました: {e}")
145
- metadata = []
146
-
147
- # 通し番号の決定
148
- serial_number = len(metadata) + 1
149
-
150
- # 新しいメタデータエントリの作成
151
- new_entry = {
152
- "serial_number": serial_number,
153
- "filename": filename,
154
- "strength": strength,
155
- "trigger_words": trigger_words
156
- }
157
-
158
- metadata.append(new_entry)
159
-
160
- # メタデータファイルの保存
161
- try:
162
- with open(metadata_filename, "w", encoding="utf-8") as f:
163
- json.dump(metadata, f, ensure_ascii=False, indent=4)
164
- except Exception as e:
165
- return f"メタデータファイルの保存に失敗しました: {e}"
166
-
167
- try:
168
- # ファイルのアップロード
169
  api.upload_file(
170
  path_or_fileobj=filename,
171
  path_in_repo=filename,
@@ -174,22 +57,7 @@ def download_and_upload(url, repo_type):
174
  repo_type="dataset",
175
  commit_message=f"Add {filename} from {url}"
176
  )
177
-
178
- # メタデータファイルのアップロード
179
- api.upload_file(
180
- path_or_fileobj=metadata_filename,
181
- path_in_repo=metadata_filename,
182
- repo_id=target_repo,
183
- token=HF_TOKEN,
184
- repo_type="dataset",
185
- commit_message=f"Update metadata with {filename}"
186
- )
187
-
188
- # 不要ファイルの削除(オプション)
189
- os.remove(filename)
190
- os.remove(metadata_filename)
191
-
192
- return f"ファイル '{filename}' とメタデータを '{target_repo}' にアップロードしました。"
193
  except Exception as e:
194
  return f"アップロード中にエラーが発生しました: {e}"
195
 
@@ -197,11 +65,11 @@ def download_and_upload(url, repo_type):
197
  with gr.Blocks() as demo:
198
  gr.Markdown("## Civitai経由ファイルダウンロード&アップロードツール")
199
  gr.Markdown("Civitai APIのURLを指定して、'model'または'lora'リポジトリへアップロードします。")
200
-
201
  # ダウンロード&アップロード機能
202
  url_input = gr.Textbox(
203
  label="CivitaiモデルAPIのURL",
204
- placeholder="例: https://civitai.com/api/download/models/546416@685247?type=Model&format=SafeTensor"
205
  )
206
  repo_choice = gr.Radio(
207
  choices=["model", "lora"],
@@ -211,10 +79,11 @@ with gr.Blocks() as demo:
211
  run_button = gr.Button("実行")
212
  output = gr.Textbox(label="結果メッセージ", interactive=False)
213
 
 
214
  run_button.click(
215
  download_and_upload,
216
  inputs=[url_input, repo_choice],
217
  outputs=output
218
  )
219
 
220
- demo.launch()
 
11
  LORA_REPO = os.environ.get("LORA_REPO", None)
12
  CIVITAI_TOKEN = os.environ.get("CIVITAI_TOKEN", None) # Civitai用トークン
13
 
 
14
  api = HfApi()
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def download_and_upload(url, repo_type):
17
  if not url or not repo_type:
18
  return "URLまたはタイプが未指定です。"
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  headers = {}
21
  if CIVITAI_TOKEN:
22
  headers["Authorization"] = f"Bearer {CIVITAI_TOKEN}"
23
 
24
  try:
 
25
  response = requests.get(url, headers=headers)
26
  response.raise_for_status()
27
  except Exception as e:
28
  return f"ファイルのダウンロードに失敗しました: {e}"
29
 
 
30
  content_disp = response.headers.get("content-disposition", "")
31
  filename = None
32
  if content_disp:
 
36
 
37
  if not filename:
38
  filename = "downloaded_file.bin"
39
+
40
+ with open(filename, "wb") as f:
41
+ f.write(response.content)
42
 
43
+ if repo_type == "model":
44
+ target_repo = MODEL_REPO
45
+ else:
46
+ target_repo = LORA_REPO
 
 
 
 
 
 
 
 
 
 
47
 
48
  if not target_repo:
49
  return f"{repo_type}用リポジトリが環境変数で設定されていません。"
50
 
51
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  api.upload_file(
53
  path_or_fileobj=filename,
54
  path_in_repo=filename,
 
57
  repo_type="dataset",
58
  commit_message=f"Add {filename} from {url}"
59
  )
60
+ return f"ファイル '{filename}' を '{target_repo}' にアップロードしました。"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  except Exception as e:
62
  return f"アップロード中にエラーが発生しました: {e}"
63
 
 
65
  with gr.Blocks() as demo:
66
  gr.Markdown("## Civitai経由ファイルダウンロード&アップロードツール")
67
  gr.Markdown("Civitai APIのURLを指定して、'model'または'lora'リポジトリへアップロードします。")
68
+
69
  # ダウンロード&アップロード機能
70
  url_input = gr.Textbox(
71
  label="CivitaiモデルAPIのURL",
72
+ placeholder="例: https://civitai.com/api/download/models/xxxxx?type=Model&format=SafeTensor"
73
  )
74
  repo_choice = gr.Radio(
75
  choices=["model", "lora"],
 
79
  run_button = gr.Button("実行")
80
  output = gr.Textbox(label="結果メッセージ", interactive=False)
81
 
82
+ # 修正点: outputsにoutputを指定し、閉じ括弧を追加
83
  run_button.click(
84
  download_and_upload,
85
  inputs=[url_input, repo_choice],
86
  outputs=output
87
  )
88
 
89
+ demo.launch()