"""RAG de l22 como grafo durable, recalculando recuperación y generación."""
import asyncio,collections,importlib.util,json,re,string,sys,time,uuid
from pathlib import Path
import hnswlib,numpy as np,torch
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForSequenceClassification
ROOT=Path('workflow-lab');ROOT.mkdir(parents=True,exist_ok=True)
def run(model,tok):
 spec=importlib.util.spec_from_file_location('rag_workflow_engine',Path('workflow_engine.py'))
 wf=importlib.util.module_from_spec(spec);sys.modules[spec.name]=wf;spec.loader.exec_module(wf)
 data=json.loads((Path('rag-lab/squad.json')).read_text(encoding='utf8'));docs=data['contexts']
 question=next(q for q in data['questions'] if q['answers'])
 texts=[d['title']+' '+d['text'] for d in docs];terms=[re.findall(r'\w+',t.lower()) for t in texts]
 counts=[collections.Counter(t) for t in terms];df=collections.Counter(w for c in counts for w in c)
 avg=float(np.mean([len(t) for t in terms]));n=len(docs)
 encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
 vectors=encoder.encode(['passage: '+x for x in texts],normalize_embeddings=True,batch_size=16,convert_to_numpy=True)
 qvec=encoder.encode(['query: '+question['question']],normalize_embeddings=True,convert_to_numpy=True)[0]
 index=hnswlib.Index(space='cosine',dim=vectors.shape[1]);index.init_index(max_elements=n,ef_construction=100,M=16,random_seed=22)
 index.add_items(vectors,np.arange(n),num_threads=1);index.set_ef(64)
 cross_name='cross-encoder/ms-marco-MiniLM-L6-v2';cross_rev='233902d25c440f23af6f7d6e94d2946bac0bee0a'
 cross_tok=AutoTokenizer.from_pretrained(cross_name,revision=cross_rev);cross=AutoModelForSequenceClassification.from_pretrained(cross_name,revision=cross_rev).eval()
 async def lexical(state):
  scores=np.zeros(n)
  for word in re.findall(r'\w+',state['question'].lower()):
   if word not in df:continue
   idf=np.log(1+(n-df[word]+.5)/(df[word]+.5))
   for i,c in enumerate(counts):
    f=c[word]
    if f:scores[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(terms[i])/avg))
  return {'lex':[int(i) for i in np.argsort(-scores,kind='stable')[:20]]}
 async def dense(state):
  labels,_=index.knn_query(qvec,k=20,num_threads=1);return {'dense':[int(i) for i in labels[0]]}
 async def fuse(state):
  scores=collections.defaultdict(float)
  for ranking in (state['lex'],state['dense']):
   for rank,i in enumerate(ranking,1):scores[i]+=1/(60+rank)
  return {'fused':sorted(scores,key=lambda i:(-scores[i],i))[:20]}
 async def rerank(state):
  candidates=state['fused'];scores=[]
  with torch.no_grad():
   for start in range(0,len(candidates),8):
    sub=candidates[start:start+8];batch=cross_tok([state['question']]*len(sub),[texts[i] for i in sub],padding=True,truncation=True,max_length=192,return_tensors='pt')
    scores.extend(cross(**batch).logits[:,0].tolist())
  ranking=sorted(range(len(candidates)),key=lambda i:(-scores[i],candidates[i]))
  return {'reranked':[candidates[i] for i in ranking]}
 async def answer(state):
  selected=[docs[i]['text'][:600] for i in state['reranked'][:5]]
  prompt=('Answer the question using only the numbered sources. Give a short answer followed by a source citation [n]; '
          'if the answer is not in the sources, say UNKNOWN.\nQuestion: '+state['question']+'\nSources:\n'+
          '\n'.join(f'[{i+1}] {text}' for i,text in enumerate(selected)))
  chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
  batch=tok(chat,return_tensors='pt').to('cpu');start=time.perf_counter()
  with torch.no_grad():out=model.generate(**batch,max_new_tokens=40,do_sample=False,pad_token_id=tok.eos_token_id)
  ni=int(batch['input_ids'].shape[1]);generated=out[0,ni:];text=tok.decode(generated,skip_special_tokens=True).strip()
  ni2=len(generated);return wf.StepResult({'answer':text,'sources':selected,'generation_seconds':time.perf_counter()-start},ni,ni2,(ni+ni2)/1_000_000)
 nodes=[wf.Node('lex',(),lexical),wf.Node('dense',(),dense),wf.Node('fuse',('lex','dense'),fuse),
        wf.Node('rerank',('fuse',),rerank),wf.Node('answer',('rerank',),answer)]
 store=wf.Store(str(ROOT/'rag_workflow.sqlite'));run_id='rag-'+uuid.uuid4().hex
 result=asyncio.run(wf.run_graph(nodes,run_id,store,{'question':question['question']}));state=result['state']
 cited=[int(x) for x in re.findall(r'\[(\d+)\]',state['answer'])];valid=bool(cited) and all(1<=i<=len(state['sources']) for i in cited)
 norm=lambda s:' '.join(w for w in re.sub(r'\[\d+\]','',s).lower().translate(str.maketrans('','',string.punctuation)).split() if w not in ('a','an','the'))
 metrics={'source_recall_at_5':int(question['context'] in state['reranked'][:5]),
          'exact':any(norm(state['answer'])==norm(a) for a in question['answers']),
          'valid_citations':valid,'answer_in_cited_source':valid and any(any(a.lower() in state['sources'][i-1].lower() for a in question['answers'] if a) for i in cited)}
 events=store.db.execute('SELECT node,event,data FROM events WHERE run_id=? ORDER BY seq',(run_id,)).fetchall()
 output={'question':question,'state':state,'metrics':metrics,'events':[{'node':n,'event':e,'data':json.loads(d)} for n,e,d in events],
         'model':'Qwen2.5-7B-Instruct-GGUF Q4_K_M CPU','note':'nodos recuperadores ejecutados en el proceso CPU; coste ficticio por millón de tokens'}
 (ROOT/'rag_workflow_real.json').write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf8')
 store.export_jsonl(run_id,str(ROOT/'rag_workflow_trace.jsonl'));store.db.close()
 print('RAG workflow real',metrics,flush=True)

if __name__=='__main__':
 import torch
 from huggingface_hub import hf_hub_download
 from transformers import AutoTokenizer
 from llama_cpp import Llama
 from cpu_adapter import ModelAdapter,TokenizerAdapter
 repo='Qwen/Qwen2.5-7B-Instruct-GGUF';rev='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
 names=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
 paths=[hf_hub_download(repo,name,revision=rev) for name in names]
 model=Llama(model_path=paths[0],n_ctx=2048,n_threads=8,n_batch=512,n_gpu_layers=0,verbose=False)
 tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-7B-Instruct',revision='a09a35458c702b33eeacc393d103063234e8bc28')
 torch.cuda.synchronize=lambda:None
 run(ModelAdapter(model),TokenizerAdapter(tok,model))
