Update app.py
Browse files3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081822 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111123 unmodified lines1161171181191201211221231241251261271281291301311321331341353 unmodified linesapp = Flask(__name__)# ==========================================# TWENTY IDE: CORE FOCUS (Direct Interface)# ==========================================HTML_TEMPLATE = """<!DOCTYPE html><html lang="az"><head><meta charset="UTF-8"><title>TWENTY IDE | IAHAI Core</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.0/ace.js"></script><style>:root {--bg: #0b0b0e;--accent: #00f2fe;--border: rgba(255, 255, 255, 0.1);--panel: #111116;}* { box-sizing: border-box; margin: 0; padding: 0; }body, html { height: 100%; background: var(--bg); color: #e0e0e0; font-family: 'Consolas', monospace; overflow: hidden; }.wrapper { display: grid; grid-template-columns: 50px 220px 1fr 280px; height: 100vh; }/* Sol Panellər */.activity-bar { background: #08080a; border-right: 1px solid var(--border); display: flex; flex-direction: column; align-items: center; padding: 20px 0; gap: 25px; }.sidebar { background: var(--panel); border-right: 1px solid var(--border); padding: 15px; }/* Redaktor Sahəsi */.main-content { display: flex; flex-direction: column; background: #141419; }.editor-header { height: 45px; background: rgba(0,0,0,0.2); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; padding: 0 15px; }#editor { flex: 1; font-size: 15px !important; }/* Terminal */.terminal { height: 220px; background: #000; border-top: 1px solid var(--border); padding: 15px; overflow-y: auto; color: #00ffaa; font-family: 'Courier New', monospace; }/* AI Paneli */.ai-panel { background: var(--panel); border-left: 1px solid var(--border); padding: 20px; }.run-btn { background: var(--accent); color: #000; border: none; padding: 6px 15px; border-radius: 3px; cursor: pointer; font-weight: bold; font-size: 12px; }.run-btn:hover { box-shadow: 0 0 10px var(--accent); opacity: 0.9; }</style></head><body><div class="wrapper"><div class="activity-bar"><i class="fa-solid fa-code" style="color:var(--accent)"></i><i class="fa-solid fa-robot" style="color:#555"></i><i class="fa-solid fa-gear" style="color:#555"></i></div><aside class="sidebar"><h4 style="font-size:11px; color:#555; letter-spacing:1px;">EXPLORER</h4><div style="margin-top:15px; font-size:13px; color:var(--accent);"><i class="fa-brands fa-python"></i> main.py</div></aside><main class="main-content"><div class="editor-header"><span style="font-size:11px; color:#888;">main.py</span><button class="run-btn" onclick="runCode()"><i class="fa-solid fa-play"></i> RUN</button></div><div id="editor"># TWENTY IDE | IAHAI# Python kodunu bura yazın və RUN düyməsini sıxın.def test():print("TWENTY 'Beyni' uğurla işə düşdü!")print(f"Nəticə: {10 + 10}")test()</div><div class="terminal" id="output">Terminal hazır...</div></main><aside class="ai-panel"><h4 style="font-size:11px; color:var(--accent); letter-spacing:1px;">EXYPOS AI</h4><div id="ai-status" style="margin-top:20px; font-size:12px; line-height:1.5; color:#888;">Sən yaz, mən burdayam. Kodunu yoxlamağa hazıram!</div></aside></div>2 unmodified linesvar editor = ace.edit("editor");editor.setTheme("ace/theme/tomorrow_night_eighties");editor.session.setMode("ace/mode/python");editor.setOptions({ showPrintMargin: false, fontSize: "15px", wrap: true });async function runCode() {const code = editor.getValue();const outputElement = document.getElementById('output');outputElement.innerText = "> Script işə düşür...\\n";outputElement.style.color = "#00ffaa";try {const response = await fetch('/run', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({code: code})});const data = await response.json();outputElement.innerText = data.output;if(data.error) outputElement.style.color = "#ff4444";} catch (err) {outputElement.innerText = "Xəta: Backend ilə əlaqə qurula bilmədi.";outputElement.style.color = "#ff4444";}}</script></body></html>3 unmodified linesdef index():return render_template_string(HTML_TEMPLATE)@app.route('/run', methods=['POST'])def run_code():code = request.json.get('code', '')try:# Kodun icrasıwith open('temp_run.py', 'w', encoding='utf-8') as f:f.write(code)result = subprocess.run(['python3', 'temp_run.py'], capture_output=True, text=True, timeout=10)output = result.stdout if not result.stderr else result.stderrreturn jsonify({'output': output, 'error': bool(result.stderr)})except Exception as e:return jsonify({'output': f"Sistem Xətası: {str(e)}", 'error': True})if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171182 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242253 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802813 unmodified linesapp = Flask(__name__)# --- WORKSPACE VƏ HƏQİQİ PYTHON MÜHİTİ ---WORKSPACE_DIR = os.path.join(os.getcwd(), 'workspace')os.makedirs(WORKSPACE_DIR, exist_ok=True)# IDE açılanda içində əsl sistem komandaları olan bir test faylı yaradaq:default_main = os.path.join(WORKSPACE_DIR, 'main.py')if not os.path.exists(default_main):with open(default_main, 'w', encoding='utf-8') as f:f.write("""# TWENTY IDE - Həqiqi Python Mühitiimport sysimport mathimport randomimport osprint("--- TWENTY SİSTEM MƏLUMATLARI ---")print(f"Python Versiyası: {sys.version.split()[0]}")print(f"İşçi Qovluq: {os.getcwd()}")print("-" * 32)# Həqiqi riyazi və məntiqi əməliyyatlarededlər = [random.randint(1, 100) for _ in range(5)]print(f"Təsadüfi yaradılan siyahı: {ededlər}")print(f"Ən böyük ədəd: {max(ededlər)}")print(f"Pi rəqəmi: {math.pi:.4f}")# Funksiyalardef hesabla(a, b):return a ** bprint(f"2-nin 10-cu dərəcəsi: {hesabla(2, 10)}")""")# ==========================================# TWENTY IDE: REAL EXECUTION ENGINE# ==========================================HTML_TEMPLATE = """<!DOCTYPE html><html lang="az"><head><meta charset="UTF-8"><title>TWENTY IDE | Pro Engine</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.0/ace.js"></script><style>:root { --bg: #0b0b0e; --accent: #00f2fe; --border: rgba(255, 255, 255, 0.1); --panel: #111116; }* { box-sizing: border-box; margin: 0; padding: 0; }body, html { height: 100%; background: var(--bg); color: #e0e0e0; font-family: 'Consolas', monospace; overflow: hidden; }.wrapper { display: grid; grid-template-columns: 50px 220px 1fr 280px; height: 100vh; }.activity-bar { background: #08080a; border-right: 1px solid var(--border); display: flex; flex-direction: column; align-items: center; padding: 20px 0; gap: 25px; }.sidebar { background: var(--panel); border-right: 1px solid var(--border); display: flex; flex-direction: column; }.sidebar-header { padding: 15px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }.sidebar-header h4 { font-size: 11px; color: #888; letter-spacing: 1px; }.sidebar-actions i { font-size: 13px; color: #aaa; cursor: pointer; margin-left: 8px; transition: 0.2s; }.sidebar-actions i:hover { color: var(--accent); }#file-list { flex: 1; overflow-y: auto; padding: 10px; }.file-item { font-size: 13px; padding: 8px 10px; cursor: pointer; border-radius: 4px; color: #bbb; display: flex; align-items: center; gap: 8px; }.file-item:hover { background: rgba(255,255,255,0.05); color: #fff; }.file-item.active { background: rgba(0, 242, 254, 0.1); color: var(--accent); border-left: 2px solid var(--accent); }.main-content { display: flex; flex-direction: column; background: #141419; }.editor-header { height: 45px; background: rgba(0,0,0,0.2); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; padding: 0 15px; }#editor { flex: 1; font-size: 15px !important; }.terminal { height: 250px; background: #000; border-top: 1px solid var(--border); padding: 15px; overflow-y: auto; color: #00ffaa; font-family: 'Courier New', monospace; line-height: 1.5; }.ai-panel { background: var(--panel); border-left: 1px solid var(--border); padding: 20px; }.btn { background: var(--accent); color: #000; border: none; padding: 6px 15px; border-radius: 3px; cursor: pointer; font-weight: bold; font-size: 12px; }.btn:hover { box-shadow: 0 0 10px var(--accent); opacity: 0.9; }.btn-save { background: transparent; color: var(--accent); border: 1px solid var(--accent); margin-right: 10px; }.btn-save:hover { background: rgba(0, 242, 254, 0.1); }</style></head><body><div class="wrapper"><div class="activity-bar"><i class="fa-solid fa-code" style="color:var(--accent)"></i><i class="fa-solid fa-folder-open" style="color:#555"></i><i class="fa-solid fa-server" style="color:#555"></i></div><aside class="sidebar"><div class="sidebar-header"><h4>WORKSPACE</h4><div class="sidebar-actions"><i class="fa-solid fa-file-circle-plus" onclick="createNewFile()" title="Yeni Fayl"></i><i class="fa-solid fa-file-arrow-up" onclick="uploadFile()" title="Fayl Yüklə"></i></div></div><div id="file-list"></div></aside><main class="main-content"><div class="editor-header"><span id="current-file-name" style="font-size:12px; color:#aaa; font-weight:bold;">main.py</span><div><button class="btn btn-save" onclick="saveCurrentFile()"><i class="fa-solid fa-floppy-disk"></i> SAVE</button><button class="btn" onclick="runCode()"><i class="fa-solid fa-play"></i> RUN</button></div></div><div id="editor"></div><div class="terminal" id="output"><span style="color:#888;">> TWENTY Terminal Hazırdır. Python 3.9 işləyir...</span><br></div></main><aside class="ai-panel"><h4 style="font-size:11px; color:var(--accent); letter-spacing:1px;">EXYPOS AI</h4><div style="margin-top:20px; font-size:12px; line-height:1.5; color:#888;">Real Python mühərriki aktivdir. Sən sys, os, math kimi kitabxanaları rahatlıqla istifadə edə bilərsən. Xəta olsa, terminal qırmızı rəngdə səni xəbərdar edəcək.</div></aside></div>2 unmodified linesvar editor = ace.edit("editor");editor.setTheme("ace/theme/tomorrow_night_eighties");editor.session.setMode("ace/mode/python");editor.setOptions({ showPrintMargin: false, fontSize: "15px" });let currentFile = "main.py";async function loadFiles() {const res = await fetch('/api/files');const files = await res.json();const listDiv = document.getElementById('file-list');listDiv.innerHTML = '';files.forEach(f => {let div = document.createElement('div');div.className = `file-item ${f === currentFile ? 'active' : ''}`;div.innerHTML = `<i class="fa-brands fa-python"></i> ${f}`;div.onclick = () => openFile(f);listDiv.appendChild(div);});}async function openFile(filename) {currentFile = filename;document.getElementById('current-file-name').innerText = filename;const res = await fetch(`/api/file?name=${filename}`);const content = await res.text();editor.setValue(content, -1);loadFiles();}async function saveCurrentFile() {const content = editor.getValue();await fetch('/api/file', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({filename: currentFile, content: content})});}async function createNewFile() {let name = prompt("Yeni faylın adı (m��sələn: test.py):");if(name) {await fetch('/api/file', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({filename: name, content: "# Yeni fayl\\n"})});openFile(name);}}function uploadFile() {let input = document.createElement('input');input.type = 'file';input.onchange = e => {let file = e.target.files[0];let reader = new FileReader();reader.onload = async event => {await fetch('/api/file', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({filename: file.name, content: event.target.result})});loadFiles();openFile(file.name);}reader.readAsText(file);}input.click();}async function runCode() {await saveCurrentFile();const out = document.getElementById('output');out.innerHTML += `<br><span style="color:#00f2fe;">> python3 ${currentFile}</span><br>`;try {const res = await fetch('/run', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({filename: currentFile})});const data = await res.json();// Xəta varsa qırmızı, yoxdursa yaşıl yazırif(data.error) {out.innerHTML += `<span style="color:#ff4444; white-space: pre-wrap;">${data.output}</span>`;} else {out.innerHTML += `<span style="color:#00ffaa; white-space: pre-wrap;">${data.output}</span>`;}} catch (err) {out.innerHTML += `<span style="color:#ff4444;">Sistem xətası baş verdi.</span>`;}// Terminalı həmişə ən aşağı sürüşdür (Scroll to bottom)out.scrollTop = out.scrollHeight;}window.onload = () => {loadFiles();openFile(currentFile);};</script></body></html>3 unmodified linesdef index():return render_template_string(HTML_TEMPLATE)@app.route('/api/files', methods=['GET'])def list_files():files = [f for f in os.listdir(WORKSPACE_DIR) if os.path.isfile(os.path.join(WORKSPACE_DIR, f))]return jsonify(files)@app.route('/api/file', methods=['GET'])def get_file():filename = request.args.get('name')filepath = os.path.join(WORKSPACE_DIR, filename)if os.path.exists(filepath):with open(filepath, 'r', encoding='utf-8') as f:return f.read()return "", 404@app.route('/api/file', methods=['POST'])def save_file():data = request.jsonfilename = data.get('filename')content = data.get('content', '')filepath = os.path.join(WORKSPACE_DIR, filename)with open(filepath, 'w', encoding='utf-8') as f:f.write(content)return jsonify({"status": "success"})@app.route('/run', methods=['POST'])def run_code():filename = request.json.get('filename', 'main.py')filepath = os.path.join(WORKSPACE_DIR, filename)try:# python3 -u : Unbuffered rejim, kodu real vaxtda və həqiqi sistem kimi işlədirresult = subprocess.run(['python3', '-u', filepath],capture_output=True,text=True,timeout=15 # Sonsuz dövrəyə girsə 15 saniyəyə dayandıracaq)# Həm standart çıxışı (stdout) həm də xətaları (stderr) birləşdirib qaytarırıqoutput = result.stdout + result.stderris_error = result.returncode != 0return jsonify({'output': output, 'error': is_error})except subprocess.TimeoutExpired:return jsonify({'output': 'XƏTA: Kod 15 saniyədən çox çəkdi. (Sonsuz dövrə ola bilər)', 'error': True})except Exception as e:return jsonify({'output': f'Sistem xətası: {str(e)}', 'error': True})if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)
app.py+202-56