featt: database complete
This commit is contained in:
parent
a1858f5106
commit
522d8cad8c
|
@ -0,0 +1,20 @@
|
|||
from pydal import DAL, Field
|
||||
db = DAL(uri="sqlite://storage.db",
|
||||
pool_size=0,
|
||||
folder="databases",
|
||||
migrate_enabled=True,
|
||||
migrate=True)
|
||||
db.define_table(
|
||||
"datacoll",
|
||||
Field("user"),
|
||||
Field("collection"),
|
||||
Field("totalchr",type="integer",default=0),
|
||||
Field('last_modified', 'datetime'),
|
||||
Field("summary",type="text"),
|
||||
Field("tematic",type="text"),
|
||||
Field("issues",type="text"),
|
||||
Field("question",type="text")
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
215
main.py
215
main.py
|
@ -25,6 +25,10 @@ from groq import Groq
|
|||
from fastapi import File as FileFast
|
||||
from fastapi import UploadFile as UploadFileFast
|
||||
from fastapi import Form as FormFast
|
||||
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
|
||||
from databases import db
|
||||
maxletters=30000
|
||||
maxtokens=int(maxletters/4)
|
||||
#import shutil
|
||||
pwd = os.getcwd()
|
||||
def extractConfig(nameModel="SystemData",relPath=os.path.join(pwd,"conf/experiment_config.json"),dataOut="keyantrophics"):
|
||||
|
@ -33,7 +37,7 @@ def extractConfig(nameModel="SystemData",relPath=os.path.join(pwd,"conf/experime
|
|||
config = json.load(file)[nameModel]
|
||||
Output= config[dataOut]
|
||||
return Output
|
||||
|
||||
keyanthropic=extractConfig(nameModel="SystemData",dataOut="keyantrophics")
|
||||
keygroq=extractConfig(nameModel="SystemData",dataOut="keygroq")
|
||||
client = Groq(api_key=keygroq)
|
||||
|
||||
|
@ -161,6 +165,8 @@ def listmodelactives():
|
|||
@app.post("/loadCollection")
|
||||
def loadCollection(data:str):
|
||||
global index
|
||||
global collectionloaded
|
||||
collectionloaded=data
|
||||
index=create_or_load_db(path="static/"+userdata+"/chroma_db",collection=data,modelT=model_emb)
|
||||
return P("El usuario %s colleccion %s"%(userdata,data))
|
||||
|
||||
|
@ -323,6 +329,183 @@ def SummaryMake(data:str,query:str):
|
|||
print("p4")
|
||||
return P(response)
|
||||
|
||||
def getTextCustom(system="",content="",max_tokens=maxtokens,model="claude-3-5-sonnet-20240620"):
|
||||
t=time.time()
|
||||
client = Anthropic(api_key=keyanthropic)
|
||||
message=[{"role": "user", "content":content},{"role": "assistant", "content":""} ]
|
||||
if system!="":
|
||||
completionv2 = client.messages.create(
|
||||
model=model,
|
||||
system=system,
|
||||
max_tokens=max_tokens,
|
||||
messages=message,
|
||||
)
|
||||
else:
|
||||
completionv2 = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
messages=message,
|
||||
)
|
||||
return {"content":completionv2.content[0].text,"time":time.time()-t}
|
||||
|
||||
|
||||
|
||||
|
||||
def processAllDocs(docs,type="summary"):
|
||||
summary_prompt = """Por favor, genera un resumen completo y detallado del material dado.
|
||||
Incluye los principales temas, argumentos y conclusiones.
|
||||
Estructura el resumen de manera coherente y organizada.
|
||||
Texto a resumir:
|
||||
%s
|
||||
"""
|
||||
tematic_prompt =""" Por favor, genera un texto donde se menciones la tematica que trata el material dado.
|
||||
Incluye una tematica general y un indice por temas tratados
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Texto a usar:
|
||||
%s
|
||||
"""
|
||||
issues_prompt ="""Por favor, genera un texto donde se menciones tomando en cuenta el material y el contenido de manera detallada que mejoras podrias realizar al material incluyendo nuevos datos o corrigiendo la informacion proporcionada
|
||||
Esta mejora hazla pensado paso a paso y de manera muy cuidadosa, tienes que dar ejemplos del materiar o referenciar directamante el texto a mejorar mencioando la causa de la mejora
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Texto a usar:
|
||||
%s
|
||||
"""
|
||||
|
||||
|
||||
question_prompt ="""Por favor, genera un texto donde indiques preguntas sobre el material que cuando sean respondidas capturen el punto central y puntos importantes del texto
|
||||
Estas preguntas hazla pensado paso a paso y de manera muy cuidadosa.
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Texto a usar:
|
||||
%s
|
||||
"""
|
||||
temp=""
|
||||
AllChunks=[]
|
||||
AllOut=[]
|
||||
for doc in docs:
|
||||
temp=temp+doc.get_text()
|
||||
if len(temp)>maxtokens:
|
||||
AllChunks.append(temp)
|
||||
if type=="summary":
|
||||
procesedInfo=getTextCustom(content= summary_prompt%temp)
|
||||
elif type=="tematic":
|
||||
procesedInfo=getTextCustom(content= tematic_prompt%temp)
|
||||
elif type=="issues":
|
||||
procesedInfo=getTextCustom(content= issues_prompt%temp)
|
||||
elif type=="question":
|
||||
procesedInfo=getTextCustom(content= question_prompt%temp)
|
||||
AllOut.append(procesedInfo)
|
||||
temp=""
|
||||
if temp!="":
|
||||
AllChunks.append(temp)
|
||||
if type=="summary":
|
||||
procesedInfo=getTextCustom(content= summary_prompt%temp)
|
||||
elif type=="tematic":
|
||||
procesedInfo=getTextCustom(content= tematic_prompt%temp)
|
||||
elif type=="issues":
|
||||
procesedInfo=getTextCustom(content= issues_prompt%temp)
|
||||
elif type=="question":
|
||||
procesedInfo=getTextCustom(content= question_prompt%temp)
|
||||
AllOut.append(procesedInfo)
|
||||
temp=""
|
||||
|
||||
|
||||
|
||||
return AllOut
|
||||
|
||||
def reduceDocs(AllOut,type="summary"):
|
||||
if len(AllOut)==1:
|
||||
return AllOut[0]["content"]
|
||||
if len(AllOut)==0:
|
||||
return "Hay un problema en este campo"
|
||||
summary_prompt = """Por favor, de los siguientes resumenes genera un resumen general
|
||||
Incluye los principales temas, argumentos y conclusiones.
|
||||
Estructura el resumen de manera coherente y organizada.
|
||||
Textos a resumir:
|
||||
%s
|
||||
"""
|
||||
tematic_prompt =""" Por favor, de los siguientes textos genera un texto general sobre la tematica.
|
||||
Incluye una tematica general y un indice por temas tratados
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Textos a usar:
|
||||
%s
|
||||
"""
|
||||
issues_prompt ="""Por favor, genera un texto donde se incluyan todas las mejoras o correcciones presentadas
|
||||
Estas mejoras hazla pensado paso a paso y de manera muy cuidadosasi hay ejemplos incluyelos o referenciar directamante el texto a mejorar mencioando la causa de la mejora
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Textos a usar:
|
||||
%s
|
||||
"""
|
||||
|
||||
|
||||
question_prompt ="""Por favor, genera un texto donde indiques preguntas sobre el material que cuando sean respondidas capturen el punto central y puntos importantes del texto
|
||||
Estas preguntas hazla pensado paso a paso y de manera muy cuidadosa.
|
||||
Estructura el texto de manera coherente y organizada.
|
||||
Texto a usar:
|
||||
%s
|
||||
"""
|
||||
sep="""________________________________________________
|
||||
"""
|
||||
temp=""
|
||||
Allreduce=[]
|
||||
if len(AllOut)>1:
|
||||
for reduce in AllOut:
|
||||
temp=temp+reduce+sep
|
||||
if len(temp)>maxtokens:
|
||||
|
||||
if type=="summary":
|
||||
procesedInfo=getTextCustom(content= summary_prompt%temp)
|
||||
elif type=="tematic":
|
||||
procesedInfo=getTextCustom(content= tematic_prompt%temp)
|
||||
elif type=="issues":
|
||||
procesedInfo=getTextCustom(content= issues_prompt%temp)
|
||||
elif type=="question":
|
||||
procesedInfo=getTextCustom(content= question_prompt%temp)
|
||||
Allreduce.append(procesedInfo)
|
||||
temp=""
|
||||
if temp!="":
|
||||
|
||||
if type=="summary":
|
||||
procesedInfo=getTextCustom(content= summary_prompt%temp)
|
||||
elif type=="tematic":
|
||||
procesedInfo=getTextCustom(content= tematic_prompt%temp)
|
||||
elif type=="issues":
|
||||
procesedInfo=getTextCustom(content= issues_prompt%temp)
|
||||
elif type=="question":
|
||||
procesedInfo=getTextCustom(content= question_prompt%temp)
|
||||
Allreduce.append(procesedInfo)
|
||||
temp=""
|
||||
print(Allreduce)
|
||||
# while len(Allreduce)>1:
|
||||
# print(Allreduce)
|
||||
# Allreduce=reduceDocs(Allreduce)
|
||||
# print("P2",Allreduce)
|
||||
# if len(Allreduce)==1:
|
||||
# return Allreduce
|
||||
|
||||
def savedb(docs,userdata,collection):
|
||||
Output={}
|
||||
for procs in ["summary","tematic","issues","question"]:
|
||||
AllOut=processAllDocs(docs,type=procs)
|
||||
Allreduce=reduceDocs(AllOut,type=procs)
|
||||
Output[procs]=Allreduce
|
||||
if db((db.datacoll.user == userdata)&(db.datacoll.collection == collection)).count()==0:
|
||||
Output["user"] = userdata
|
||||
Output["collection"] = collection
|
||||
db.datacoll.insert(**Output)
|
||||
db.commit()
|
||||
else:
|
||||
db((db.datacoll.user == userdata)&(db.datacoll.collection == collection)).update(**Output)
|
||||
db.commit()
|
||||
|
||||
@app.get("/showdata")
|
||||
def showData():
|
||||
userdata,collectionloaded
|
||||
rows=db((db.datacoll.user == userdata)&(db.datacoll.collection == collectionloaded)).select()
|
||||
first_row = rows.first()
|
||||
return P(first_row.summary),P(first_row.tematic),P(first_row.issues),P(first_row.question)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@app.post("/createCollection")
|
||||
|
@ -332,19 +515,22 @@ def createCollection(data:str,collection:str):
|
|||
input_dir=data
|
||||
).load_data()
|
||||
print("Process Documents")
|
||||
savedb(docs,userdata,collection)
|
||||
|
||||
Nodes=post_process_documents(docs)
|
||||
print("create DB")
|
||||
class MyThread(threading.Thread):
|
||||
def run(self):
|
||||
print("Hilo")
|
||||
create_or_load_db(path="static/"+data.split("/")[1]+"/chroma_db",collection=collection,Nodes=Nodes,modelT=model_emb)
|
||||
|
||||
# create and start the thread
|
||||
global t
|
||||
t = MyThread()
|
||||
t.start()
|
||||
global t_time
|
||||
t_time=time.time()
|
||||
# class MyThread(threading.Thread):
|
||||
# def run(self):
|
||||
# print("Hilo")
|
||||
# create_or_load_db(path="static/"+data.split("/")[1]+"/chroma_db",collection=collection,Nodes=Nodes,modelT=model_emb)
|
||||
|
||||
# # create and start the thread
|
||||
# global t
|
||||
# t = MyThread()
|
||||
# t.start()
|
||||
# global t_time
|
||||
# t_time=time.time()
|
||||
return Div("Iniciando carga de datos")
|
||||
|
||||
@app.get("/is_busy")
|
||||
|
@ -384,12 +570,7 @@ def home():
|
|||
,id="questions"),
|
||||
cls="col-xs-6"),
|
||||
Div(H3("Este genera información general del material, pero es intensivo en uso del api, aunque ahora esta restingido a solo 5 solicitudes el objeitvo original era enviar todo el material."),
|
||||
Div(
|
||||
Form(
|
||||
Input(id="query", name="question", placeholder="Dar una pregunta"),
|
||||
Button("Submit",type="submit"), hx_post="/queryprompt",hx_swap="innerHTML",hx_target="#queryR" ),
|
||||
Div(id="queryR"),
|
||||
id="query"),
|
||||
Div(hx_target="this",hx_swap="innerHTML",hx_get="/showdata",hx_trigger="every 60000ms",id="query"),
|
||||
id="chatbot",cls="col-xs-6"),
|
||||
cls="row", style="color: #fff;")
|
||||
))
|
||||
|
|
Loading…
Reference in New Issue