Spaces:
Sleeping
Sleeping
commit
Browse files- app.py +116 -78
- requirements.txt +11 -8
app.py
CHANGED
@@ -6,61 +6,92 @@ import requests
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import re
|
8 |
import warnings
|
|
|
9 |
warnings.filterwarnings("ignore")
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
class TextSummarizer:
|
12 |
def __init__(self):
|
13 |
-
#
|
14 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
print(f"使用デバイス: {self.device}")
|
16 |
print(f"PyTorch バージョン: {torch.__version__}")
|
17 |
|
18 |
-
#
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
try:
|
27 |
print("モデルを読み込み中...")
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
except Exception as e:
|
38 |
print(f"❌ メインモデル読み込みエラー: {e}")
|
39 |
-
#
|
40 |
try:
|
41 |
-
print("
|
42 |
self.summarizer = pipeline(
|
43 |
"summarization",
|
44 |
-
model="sshleifer/distilbart-cnn-
|
45 |
-
device=0 if self.device == "cuda" else -1
|
46 |
-
use_safetensors=True,
|
47 |
-
trust_remote_code=False
|
48 |
)
|
49 |
-
print("✅
|
50 |
except Exception as e2:
|
51 |
-
print(f"❌
|
52 |
-
|
53 |
-
try:
|
54 |
-
print("最終フォールバック(レガシーモード)...")
|
55 |
-
self.summarizer = pipeline(
|
56 |
-
"summarization",
|
57 |
-
model="sshleifer/distilbart-cnn-12-6",
|
58 |
-
device=0 if self.device == "cuda" else -1
|
59 |
-
)
|
60 |
-
print("⚠️ レガシーモードで読み込み完了(safetensorsなし)")
|
61 |
-
except Exception as e3:
|
62 |
-
print(f"❌ 全てのモデル読み込みに失敗: {e3}")
|
63 |
-
raise Exception("モデルの読み込みに失敗しました。requirements.txtを確認し、依存関係を更新してください。")
|
64 |
|
65 |
def clean_text(self, text):
|
66 |
"""テキストの前処理"""
|
@@ -89,8 +120,9 @@ class TextSummarizer:
|
|
89 |
|
90 |
return chunks
|
91 |
|
|
|
92 |
def summarize_text(self, text, max_length=150, min_length=50):
|
93 |
-
"""
|
94 |
try:
|
95 |
cleaned_text = self.clean_text(text)
|
96 |
|
@@ -285,14 +317,14 @@ def process_url_input(url, max_length, min_length):
|
|
285 |
def create_interface():
|
286 |
with gr.Blocks(title="🤖 ローカルLLM テキスト要約ツール", theme=gr.themes.Soft()) as app:
|
287 |
gr.Markdown("""
|
288 |
-
# 🤖 ローカルLLM テキスト要約ツール (
|
289 |
|
290 |
このツールは、ローカルで動作するLLMを使用してテキストを要約し、構造化された形式で出力します。
|
291 |
|
292 |
-
##
|
293 |
-
- **
|
294 |
-
-
|
295 |
-
- **
|
296 |
|
297 |
## 📝 対応入力形式
|
298 |
- **テキスト直接入力**
|
@@ -383,51 +415,57 @@ def create_interface():
|
|
383 |
3. **実行**: 対応する実行ボタンをクリック
|
384 |
4. **結果確認**: 構造化された要約結果を確認
|
385 |
|
386 |
-
## ⚙️ 技術仕様 (
|
387 |
-
- **モデル**:
|
388 |
-
-
|
389 |
-
-
|
390 |
-
- **GPU加速**:
|
391 |
- **出力形式**: 構造化Markdown
|
392 |
|
393 |
-
##
|
394 |
-
-
|
395 |
-
-
|
396 |
-
-
|
397 |
""")
|
398 |
|
399 |
return app
|
400 |
|
401 |
if __name__ == "__main__":
|
402 |
-
#
|
403 |
-
print("""
|
404 |
-
|
405 |
|
406 |
-
|
|
|
407 |
|
408 |
-
pip install torch>=2.6.0 transformers>=4.40.0 safetensors>=0.4.0
|
409 |
-
|
410 |
-
または、requirements.txtを更新:
|
411 |
-
pip install -r requirements.txt
|
412 |
-
|
413 |
-
GPU使用の場合:
|
414 |
-
pip install torch>=2.6.0+cu121 --extra-index-url https://download.pytorch.org/whl/cu121
|
415 |
""")
|
416 |
|
417 |
-
|
418 |
-
|
419 |
-
major, minor = map(int, torch_version.split('.')[:2])
|
420 |
-
if major < 2 or (major == 2 and minor < 6):
|
421 |
-
print(f"⚠️ 現在のPyTorchバージョン: {torch.__version__}")
|
422 |
-
print("🚨 セキュリティリスクあり - アップグレードを強く推奨します")
|
423 |
else:
|
424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
425 |
|
426 |
# アプリケーション起動
|
427 |
app = create_interface()
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import re
|
8 |
import warnings
|
9 |
+
import os
|
10 |
warnings.filterwarnings("ignore")
|
11 |
|
12 |
+
# ZeroGPU環境の検出
|
13 |
+
IS_ZEROGPU = os.environ.get("SPACE_ID") is not None and "zero-gpu" in os.environ.get("SPACE_ID", "").lower()
|
14 |
+
|
15 |
+
# ZeroGPU用のデコレータ(利用可能な場合のみ)
|
16 |
+
try:
|
17 |
+
import spaces
|
18 |
+
if IS_ZEROGPU:
|
19 |
+
zerogpu_decorator = spaces.GPU
|
20 |
+
else:
|
21 |
+
zerogpu_decorator = lambda duration=None: lambda func: func
|
22 |
+
except ImportError:
|
23 |
+
zerogpu_decorator = lambda duration=None: lambda func: func
|
24 |
+
|
25 |
class TextSummarizer:
|
26 |
def __init__(self):
|
27 |
+
# 環境の検出
|
28 |
+
self.is_zerogpu = IS_ZEROGPU
|
29 |
+
print(f"実行環境: {'ZeroGPU' if self.is_zerogpu else 'Local/Standard'}")
|
30 |
+
|
31 |
+
# デバイス設定
|
32 |
+
if self.is_zerogpu:
|
33 |
+
self.device = "cuda" # ZeroGPUでは常にCUDA
|
34 |
+
else:
|
35 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
36 |
+
|
37 |
print(f"使用デバイス: {self.device}")
|
38 |
print(f"PyTorch バージョン: {torch.__version__}")
|
39 |
|
40 |
+
# ZeroGPU以外でのバージョンチェック
|
41 |
+
if not self.is_zerogpu:
|
42 |
+
torch_version = torch.__version__.split('+')[0]
|
43 |
+
try:
|
44 |
+
major, minor = map(int, torch_version.split('.')[:2])
|
45 |
+
if major < 2 or (major == 2 and minor < 6):
|
46 |
+
print("⚠️ 警告: PyTorch v2.6未満です。セキュリティ脆弱性(CVE-2025-32434)のため、アップグレードを推奨します。")
|
47 |
+
except ValueError:
|
48 |
+
print("⚠️ PyTorchバージョンの解析に失敗しました")
|
49 |
+
|
50 |
+
# モデル読み込み(ZeroGPU対応)
|
51 |
+
self._load_model()
|
52 |
+
|
53 |
+
def _load_model(self):
|
54 |
+
"""モデルの読み込み(環境に応じて最適化)"""
|
55 |
try:
|
56 |
print("モデルを読み込み中...")
|
57 |
+
|
58 |
+
# ZeroGPU環境では軽量モデルを優先
|
59 |
+
if self.is_zerogpu:
|
60 |
+
model_name = "sshleifer/distilbart-cnn-12-6" # より軽量
|
61 |
+
else:
|
62 |
+
model_name = "facebook/bart-large-cnn"
|
63 |
+
|
64 |
+
# モデル読み込み設定
|
65 |
+
pipeline_kwargs = {
|
66 |
+
"task": "summarization",
|
67 |
+
"model": model_name,
|
68 |
+
"device": 0 if self.device == "cuda" else -1,
|
69 |
+
"framework": "pt"
|
70 |
+
}
|
71 |
+
|
72 |
+
# safetensorsが利用可能な場合のみ使用
|
73 |
+
try:
|
74 |
+
self.summarizer = pipeline(**pipeline_kwargs, use_safetensors=True, trust_remote_code=False)
|
75 |
+
print(f"✅ {model_name} の読み込み完了 (safetensors使用)")
|
76 |
+
except Exception:
|
77 |
+
# safetensorsが使えない場合はフォールバック
|
78 |
+
self.summarizer = pipeline(**pipeline_kwargs)
|
79 |
+
print(f"✅ {model_name} の読み込み完了 (標準形式)")
|
80 |
+
|
81 |
except Exception as e:
|
82 |
print(f"❌ メインモデル読み込みエラー: {e}")
|
83 |
+
# 最軽量フォールバック
|
84 |
try:
|
85 |
+
print("最軽量フォールバックモデルを試行中...")
|
86 |
self.summarizer = pipeline(
|
87 |
"summarization",
|
88 |
+
model="sshleifer/distilbart-cnn-6-6", # 最軽量
|
89 |
+
device=0 if self.device == "cuda" else -1
|
|
|
|
|
90 |
)
|
91 |
+
print("✅ 最軽量モデルで読み込み完了")
|
92 |
except Exception as e2:
|
93 |
+
print(f"❌ 全てのモデル読み込みに失敗: {e2}")
|
94 |
+
raise Exception(f"モデルの読み込みに失敗しました: {e2}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
def clean_text(self, text):
|
97 |
"""テキストの前処理"""
|
|
|
120 |
|
121 |
return chunks
|
122 |
|
123 |
+
@zerogpu_decorator(duration=60)
|
124 |
def summarize_text(self, text, max_length=150, min_length=50):
|
125 |
+
"""テキストを要約(ZeroGPU対応)"""
|
126 |
try:
|
127 |
cleaned_text = self.clean_text(text)
|
128 |
|
|
|
317 |
def create_interface():
|
318 |
with gr.Blocks(title="🤖 ローカルLLM テキスト要約ツール", theme=gr.themes.Soft()) as app:
|
319 |
gr.Markdown("""
|
320 |
+
# 🤖 ローカルLLM テキスト要約ツール (ZeroGPU対応)
|
321 |
|
322 |
このツールは、ローカルで動作するLLMを使用してテキストを要約し、構造化された形式で出力します。
|
323 |
|
324 |
+
## 🚀 環境対応
|
325 |
+
- **ZeroGPU**: Hugging Face Spaces自動最適化
|
326 |
+
- **ローカル環境**: PyTorch v2.6+ セキュリティ対応
|
327 |
+
- **safetensors**: 利用可能時に自動使用
|
328 |
|
329 |
## 📝 対応入力形式
|
330 |
- **テキスト直接入力**
|
|
|
415 |
3. **実行**: 対応する実行ボタンをクリック
|
416 |
4. **結果確認**: 構造化された要約結果を確認
|
417 |
|
418 |
+
## ⚙️ 技術仕様 (ZeroGPU対応)
|
419 |
+
- **モデル**: DistilBART/BART (環境に応じて自動選択)
|
420 |
+
- **ZeroGPU**: Hugging Face Spaces最適化
|
421 |
+
- **セキュリティ**: safetensors自動対応
|
422 |
+
- **GPU加速**: 環境自動検出
|
423 |
- **出力形式**: 構造化Markdown
|
424 |
|
425 |
+
## 🔧 環境別最適化
|
426 |
+
- ZeroGPU: 軽量モデル自動選択
|
427 |
+
- ローカル: 高性能モデル利用可能
|
428 |
+
- セキュリティ: 環境に応じた安全設定
|
429 |
""")
|
430 |
|
431 |
return app
|
432 |
|
433 |
if __name__ == "__main__":
|
434 |
+
# 環境情報表示
|
435 |
+
print(f"""
|
436 |
+
🚀 テキスト要約ツール起動 🚀
|
437 |
|
438 |
+
実行環境: {'ZeroGPU (Hugging Face Spaces)' if IS_ZEROGPU else 'ローカル環境'}
|
439 |
+
PyTorchバージョン: {torch.__version__}
|
440 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
441 |
""")
|
442 |
|
443 |
+
if IS_ZEROGPU:
|
444 |
+
print("✅ ZeroGPU環境で最適化済み")
|
|
|
|
|
|
|
|
|
445 |
else:
|
446 |
+
# ローカル環境でのセキュリティチェック
|
447 |
+
try:
|
448 |
+
torch_version = torch.__version__.split('+')[0]
|
449 |
+
major, minor = map(int, torch_version.split('.')[:2])
|
450 |
+
if major < 2 or (major == 2 and minor < 6):
|
451 |
+
print("⚠️ セキュリティ警告: PyTorch v2.6未満")
|
452 |
+
print(" 推奨: pip install torch>=2.6.0")
|
453 |
+
else:
|
454 |
+
print("✅ PyTorchセキュリティ: OK")
|
455 |
+
except ValueError:
|
456 |
+
print("⚠️ PyTorchバージョン確認不能")
|
457 |
|
458 |
# アプリケーション起動
|
459 |
app = create_interface()
|
460 |
+
|
461 |
+
if IS_ZEROGPU:
|
462 |
+
# ZeroGPU環境用設定
|
463 |
+
app.launch()
|
464 |
+
else:
|
465 |
+
# ローカル環境用設定
|
466 |
+
app.launch(
|
467 |
+
server_name="0.0.0.0",
|
468 |
+
server_port=7860,
|
469 |
+
share=True,
|
470 |
+
debug=True
|
471 |
+
)
|
requirements.txt
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
-
# Core ML Libraries -
|
2 |
-
torch
|
3 |
-
transformers>=4.
|
4 |
tokenizers>=0.15.0
|
5 |
safetensors>=0.4.0
|
6 |
|
@@ -31,10 +31,10 @@ huggingface-hub>=0.20.0
|
|
31 |
# unidic-lite>=1.0.8
|
32 |
# mecab-python3>=1.0.6
|
33 |
|
34 |
-
#
|
35 |
-
# torch>=2.6.0
|
36 |
-
# torchvision>=0.18.0
|
37 |
-
# torchaudio>=2.6.0
|
38 |
|
39 |
# Development Tools (optional)
|
40 |
# jupyter>=1.0.0
|
@@ -43,4 +43,7 @@ huggingface-hub>=0.20.0
|
|
43 |
|
44 |
# Security
|
45 |
certifi>=2023.5.7
|
46 |
-
urllib3>=2.0.3
|
|
|
|
|
|
|
|
1 |
+
# Core ML Libraries - ZeroGPU Compatible
|
2 |
+
torch # ZeroGPUで自動管理
|
3 |
+
transformers>=4.35.0
|
4 |
tokenizers>=0.15.0
|
5 |
safetensors>=0.4.0
|
6 |
|
|
|
31 |
# unidic-lite>=1.0.8
|
32 |
# mecab-python3>=1.0.6
|
33 |
|
34 |
+
# For Local Environment (comment out for ZeroGPU)
|
35 |
+
# torch>=2.6.0
|
36 |
+
# torchvision>=0.18.0
|
37 |
+
# torchaudio>=2.6.0
|
38 |
|
39 |
# Development Tools (optional)
|
40 |
# jupyter>=1.0.0
|
|
|
43 |
|
44 |
# Security
|
45 |
certifi>=2023.5.7
|
46 |
+
urllib3>=2.0.3
|
47 |
+
|
48 |
+
# ZeroGPU specific (uncomment if needed)
|
49 |
+
# spaces>=0.19.0
|