File size: 5,789 Bytes
9390204
e1a8749
9390204
 
 
 
 
 
 
 
 
 
 
 
 
 
e1a8749
 
 
 
 
 
 
 
 
 
 
9390204
e1a8749
 
9390204
e1a8749
 
 
 
 
 
9390204
 
e1a8749
9390204
 
e1a8749
 
 
 
 
 
9390204
e1a8749
9390204
 
 
e1a8749
9390204
 
 
e1a8749
 
9390204
e1a8749
 
9390204
 
 
e1a8749
9390204
e1a8749
9390204
 
 
 
 
 
 
 
e1a8749
9390204
e1a8749
 
9390204
e1a8749
 
 
 
 
 
 
 
 
 
 
 
 
9390204
e1a8749
 
9390204
 
 
 
 
 
 
e1a8749
9390204
 
 
 
e1a8749
9390204
 
e1a8749
 
 
 
 
 
 
9390204
 
e1a8749
 
 
9390204
e1a8749
 
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
# ======================================================================
# AXIS: Advanced Cross-Integrated System (V1.3 - Deep Lattice)
# Copyright (c) 2025 AXIS Project. All rights reserved.
# Licensed under APSL v1.0 (Non-Commercial / No-Redistribution)
# ======================================================================

import json, torch, gc, os, sys, re, warnings, time, uuid
from flask import Flask, render_template, request, jsonify
from transformers import AutoTokenizer, AutoModelForCausalLM

warnings.filterwarnings("ignore")
app = Flask(__name__)

MODEL_ID = "kofdai/AXIS-Sovereign-Logic-Engine"
SYSTEM_NAME = "AXIS: Advanced Cross-Integrated System"

LICENSE_TERMS = """
======================================================================
[AXIS PROPRIETARY SOURCE-AVAILABLE LICENSE (APSL) v1.0]
----------------------------------------------------------------------
1. 商用利用の禁止:本システムを直接的・間接的な収益化に用いることを禁じます。
2. 再配布の禁止:ソースコード、モデル重み、論理構造の無断配布を禁じます。
3. 統治ロジックの保護:AIを旋盤とし物理パージを行う設計の模倣を禁じます。
4. 演算の不可逆性:本システムの報告は、一過性推論の結果としての定数である。
======================================================================
"""

def ai_logic_lathe(target, mode="LOGIC_EXTRACT"):
    process_logs = [f"🚀 [AXIS] 旋盤起動: {mode}"]
    device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
    
    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
    model = AutoModelForCausalLM.from_pretrained(
        MODEL_ID, 
        torch_dtype=torch.bfloat16 if device != "cpu" else torch.float32, 
        low_cpu_mem_usage=True
    ).to(device)

    session_salt = uuid.uuid4().hex[:8]
    base_instr = f"【AXIS SESSION_{session_salt} OVERRIDE】\n記憶パージ完了。対象の論理的解像度を最大化せよ。\n"

    if mode == "LOGIC_EXTRACT":
        prompt = (
            f"{base_instr}入力「{target}」を多角的に分解せよ。\n"
            "物理的特性、機能的意味、抽象的概念の3層から要素を抽出すること。\n"
            "必ず以下のJSON形式のみを出力せよ。解説は一切不要。\n"
            "Format: {\"subject\":\"対象名称\", \"lattice\":{\"物理\":\"\", \"意味\":\"\", \"背景\":\"\"}, \"conflicts\":[]}"
        )
    else:
        prompt = f"{base_instr}演算データ「{target}」を報告する日本語パーツをJSONで返せ。Format: {{\"prefix\":\"\", \"suffix\":\"\"}}"

    inputs = tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True, return_tensors="pt").to(device)
    with torch.no_grad():
        outputs = model.generate(inputs, max_new_tokens=512, pad_token_id=tokenizer.eos_token_id, do_sample=True, temperature=0.7)
    
    res_text = tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)
    
    # 🗑️ 物理パージ
    del model, tokenizer, inputs, outputs
    gc.collect()
    if torch.cuda.is_available(): torch.cuda.empty_cache()
    elif torch.backends.mps.is_available(): torch.mps.empty_cache()
    
    try:
        match = re.search(r"\{.*\}", res_text, re.DOTALL)
        return json.loads(match.group()), process_logs
    except:
        return {"error": "LATTICE_MISS", "raw": res_text}, process_logs

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/chat', methods=['POST'])
def chat():
    user_input = request.json.get('message', '')
    total_logs = [f"📡 [SYSTEM] 信号解析開始: {time.strftime('%H:%M:%S')}"]
    
    logic_parts, logs1 = ai_logic_lathe(user_input, mode="LOGIC_EXTRACT")
    total_logs.extend(logs1)
    
    if "error" in logic_parts:
        raw_result = f"論理特異点を検知。入力「{user_input[:10]}」を非定常信号として処理。解析不能。"
    else:
        subj = logic_parts.get('subject', user_input)
        lat = logic_parts.get('lattice', {})
        lattice_str = " | ".join([f"{k}:{v}" for k, v in lat.items()])
        raw_result = (
            f"対象「{subj}」を論理格子(Lattice)へ展開完了。\n"
            f"【解析格子】{lattice_str}\n"
            f"矛盾検知: {len(logic_parts.get('conflicts', []))}。"
        )
    
    total_logs.append("✅ [SYSTEM] 立体十字の整合性を確認。")

    adherent, logs2 = ai_logic_lathe(raw_result, mode="ADHERENT")
    total_logs.extend(logs2)
    
    final_output = (
        f"--- [AXIS LOGIC REPORT] ---\n"
        f"{adherent.get('prefix', '演算結果:')}\n\n"
        f"【確定データ】\n{raw_result}\n\n"
        f"{adherent.get('suffix', '報告終了。')}\n"
        f"-------------------------------\n"
        f"AXIS_SESSION: {uuid.uuid4().hex[:4].upper()}\n"
        f"STATUS: LOGIC_CONSOLIDATED."
    )
    return jsonify({"response": final_output, "process_logs": total_logs})
# ==========================================
# 3. 起動シーケンス (Spaces Optimized)
# ==========================================
if __name__ == '__main__':
    banner = r"""
      ___      _   __  _____  _____ 
     / _ \    \ \ / / |_   _| /  ___|
    / /_\ \    \ V /    | |   \ `--. 
    |  _  |    /   \    | |    `--. \
    | | | |   / /^\ \  _| |_  /\__/ /
    \_| |_/   \/   \/  \___/  \____/ 
    """
    print(banner)
    print("[SYSTEM] AXIS Live Deployment starting...")
    print("[LICENSE] APSL v1.0 auto-accepted for demonstration purposes.")
    print("-" * 70)
    
    # Spaces標準の 7860 ポートで起動
    app.run(host='0.0.0.0', port=7860)