#!/usr/bin/env python3 """Bounded shadow trial. No file/mail scanning, network, routing or daemon.""" import argparse, collections, datetime as dt, fcntl, json, os, re, statistics, subprocess, sys, time, uuid from pathlib import Path TZ=dt.timezone(dt.timedelta(hours=3)) END=dt.datetime(2026,10,11,19,tzinfo=TZ) # set your own trial end date HOME=Path.home() STORE=HOME/'.hermes/laya-trial' CHOICES={ 'route':{'main':'Kısa soru, dosya iletme veya basit kontrol','code':'Yazılım geliştirme, hata düzeltme, test','visual':'Afiş, illüstrasyon veya görsel tasarım','video':'Video kurgu, animasyon, render','research':'Web araştırması, kaynak karşılaştırma','uncertain':'Belirsiz veya birden fazla uzmanlık'}, 'note':{'idea':'Henüz kararlaştırılmamış fikir veya öneri','decision':'Kesinleşmiş karar veya seçilen yaklaşım','task':'Yapılacak somut iş','reference':'Kaynak veya açıklayıcı başvuru bilgisi','uncertain':'Yetersiz veya karışık bilgi'} } def append(row): STORE.mkdir(parents=True,exist_ok=True,mode=0o700) row.update(id=uuid.uuid4().hex,time=dt.datetime.now(TZ).isoformat()) with (STORE/'results.jsonl').open('a') as f: fcntl.flock(f,fcntl.LOCK_EX); f.write(json.dumps(row,ensure_ascii=False)+'\n') return row def classify(task,text,expected,source,reverse=False): if dt.datetime.now(TZ)>=END: raise RuntimeError('Trial expired; no model started') if not text.strip() or len(text)>1200: raise ValueError('Nonempty sanitized summary, max 1200 characters') if expected not in CHOICES[task]: raise ValueError('Reviewer label must be specified before inference') STORE.mkdir(parents=True,exist_ok=True,mode=0o700) with (STORE/'run.lock').open('a') as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) mem=subprocess.run(['memory_pressure','-Q'],capture_output=True,text=True,check=True,timeout=10).stdout free=re.search(r'free percentage:\s*(\d+)%',mem) if not free or int(free[1])<35: raise RuntimeError('RAM guard: insufficient available memory') # User-authorized bounded LAYA trial ignores stale swap; not an Ollama policy change. criteria=CHOICES[task] if reverse: criteria=dict(reversed(list(criteria.items()))) question={'category':{'type':'choice','prompt':'Verilen metin için en uygun kategoriyi seç.','criteria':criteria}} cmd=[str(HOME/'.local/bin/laya'),'decide',str(HOME/'.ollama/models/laya_multilingual_q8_0.gguf'),'--device','metal','--questions',json.dumps(question,ensure_ascii=False),'--json'] # Input goes through inherited stdin, not a persistent text file or argv. cmd+=['--state-file','/dev/stdin'] started=time.perf_counter() p=subprocess.run(cmd,input=json.dumps({'text':text},ensure_ascii=False),capture_output=True,text=True,timeout=30) elapsed=time.perf_counter()-started if p.returncode: raise RuntimeError('LAYA nonzero exit '+str(p.returncode)) raw=json.loads(p.stdout); answer=raw['answers']['category']; choice=answer['choice'] if choice not in CHOICES[task]: raise RuntimeError('Invalid answer') row={'task':task,'source':source,'review_label':expected,'choice':choice,'agrees_with_review':choice==expected,'reverse':reverse,'wall_seconds':round(elapsed,3),'usage':raw.get('usage'),'scores':answer.get('probabilities'),'confidence':answer.get('confidence'),'shadow_only':True} return append(row) def report(): rows=[json.loads(x) for x in (STORE/'results.jsonl').read_text().splitlines()] if (STORE/'results.jsonl').exists() else [] print('LAYA deneme raporu — yalnız öneri; hiçbir otomatik işlem yok.') print('Dönem sonu: '+END.isoformat()) for source in ('synthetic','live'): subset=[r for r in rows if r['source']==source] primary=[r for r in subset if not r['reverse']] ok=sum(r['agrees_with_review'] for r in primary) print(f'{source}: {len(primary)} örnek, inceleyen etiketiyle uyum {ok}/{len(primary)}; ters sıralı ek koşu {sum(r["reverse"] for r in subset)}') for task in CHOICES: part=[r for r in primary if r['task']==task] if part: print(f' {task}: {sum(r["agrees_with_review"] for r in part)}/{len(part)}') if rows: print(f'Medyan komut süresi: {statistics.median(r["wall_seconds"] for r in rows):.3f} s') print('Uyum, doğruluk kanıtı değildir. Synthetic örnekler gerçek kullanım başarısı değildir; puanlar kalibre güven yüzdesi değildir.') if not any(r['source']=='live' for r in rows): print('Henüz gerçek görev örneği yok. Otomasyona geçiş için kanıt yok.') print('Ham girdi veya özel içerik kaydedilmedi. Kayıt: '+str(STORE/'results.jsonl')) def main(): a=argparse.ArgumentParser(); a.add_argument('mode',choices=['classify','report']); a.add_argument('--task',choices=list(CHOICES)); a.add_argument('--expected'); a.add_argument('--source',choices=['synthetic','live'],default='live'); a.add_argument('--non-sensitive',action='store_true'); a.add_argument('--reverse',action='store_true'); args=a.parse_args() if args.mode=='report': report(); return if not args.non_sensitive: a.error('Explicit non-sensitive summary required; no health, secrets, backup content or whole chat') if not args.task: a.error('--task required') print(json.dumps(classify(args.task,sys.stdin.read(4801),args.expected,args.source,args.reverse),ensure_ascii=False)) if __name__=='__main__': try: main() except Exception as e: print(type(e).__name__+': '+str(e),file=sys.stderr); sys.exit(1)