Skip to content

Commit

Permalink
Added Random Question from dataset on UI
Browse files Browse the repository at this point in the history
  • Loading branch information
Josemvg committed Feb 4, 2022
1 parent 28a551a commit fbc35d9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 11 deletions.
21 changes: 16 additions & 5 deletions ui/utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"""
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
spreadsheet = "MuHeQa_Validation"
spreadsheet_id = "1TY6Tj1OwITOW3o1nYRFFRY1bunvHNImUj-J0omRq4-I"
sheet = "Validation"
spreadsheetId = "1TY6Tj1OwITOW3o1nYRFFRY1bunvHNImUj-J0omRq4-I"
validationSheet = "Validation"

if os.path.exists('credentials.json'):
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
Expand All @@ -35,7 +35,7 @@ def connectToSheet():
service = build("sheets","v4",credentials=creds)
return service.spreadsheets()

def insertRow(sheet):
def insertRow():
"""
Funcion auxiliar que inserta una nueva fila en la Hoja de Validacion
"""
Expand All @@ -47,6 +47,17 @@ def getRecordsInSheet(sheet):
Sea esta hoja un dataset de EQA que sigue nuestro formato
"""
client = gspread.authorize(creds)
sheetClient = client.open("MuHeQa_Validation").worksheet(sheet)
sheetClient = client.open(spreadsheet).worksheet(sheet)
records = sheetClient.get_all_records()
return records
return records

def getDatasetsInSheet(sheet):
"""
Funcion auxiliar que devuelve una lista con
el nombre de las hojas que contienen un Dataset
"""
sheetMetadata = sheet.get(spreadsheetId=spreadsheetId).execute()
properties = sheetMetadata.get('sheets')
datasetList = []
[datasetList.append(i.get("properties").get('title')) for i in properties if "Dataset" in i.get("properties").get('title')]
return datasetList
51 changes: 45 additions & 6 deletions ui/webapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
from annotated_text import annotated_text
import operator
from utils import db
import random

def queryJSON(queryURL, question):
'''
"""
Funcion auxiliar que realiza las preguntas al servidor de EQA
'''
"""
files = {
'question': (None, question),
}
Expand All @@ -18,9 +19,9 @@ def main():

@st.cache(show_spinner=False, allow_output_mutation=True)
def getAnswers(data):
'''
"""
Funcion auxiliar que obtiene una lista con todas las respuestas sobre las distintas bases de conocimiento
'''
"""
answerList = [

]
Expand Down Expand Up @@ -57,7 +58,7 @@ def annotateContext(response, answer, context):
)

#Creamos la conexion para la base de datos de validacion
#conn = db.connect()
worksheet = db.connectToSheet()

#Titulo y subtitulo del cuerpo de la interfaz
st.title('MuHeQa UI')
Expand All @@ -68,8 +69,37 @@ def annotateContext(response, answer, context):
st.markdown("""
Streamlit Web Interface based on MuHeQa - Web Service that creates Natural Language answers from Natural Language questions using as Knowledge Base a combination of both Structured (Knowledge Graphs) and Unstructured (documents) Data.
""", unsafe_allow_html=True)
st.markdown("""
Write any question below or use a random one from a pre-loaded datasets!
""", unsafe_allow_html=True)

#Lista de Hojas de Calculo con Datasets en nuestro Libro
datasetList = db.getDatasetsInSheet(worksheet)

#Obtenemos el contenido de cada una de estas hojas
recordList = []
#Creamos una lista de listas para dicho contenido, donde cada lista sera un dataset (hoja)
for i in datasetList:
recordList.append(db.getRecordsInSheet(i))

#Buscador para realizar preguntas
question = st.text_input("")

question = st.text_input('')
#Creamos la lista para el selector
selectorList = ["All"]
#Quitamos "_Validation" del nombre de las hojas del Libro de Calculo
selectorList.extend([i.split("_")[0] for i in datasetList])

#Selector para el Dataset del que provendran las preguntas aleatorias
dataset = st.selectbox("Select a DataSet", selectorList)
#Boton que hace una pregunta aleatoria
randomQuestion = st.button("Random Question")

if randomQuestion:
randomDict = random.choice(random.choices(recordList, weights=map(len, recordList))[0])
print(randomDict)
question = randomDict["question"]
modelAnswer = randomDict["answer"]

data = {
'question': question,
Expand All @@ -85,6 +115,12 @@ def annotateContext(response, answer, context):
knowledgeBases = ["wikidata","dbpedia","cord19"]

if question:
st.write("**Question: **", question)
if modelAnswer:
#Mostramos la respuesta modelo
st.write("**Expected Answer: **", modelAnswer)
#Reseteamos el valor de la respuesta modelo
modelAnswer = None
#Mensaje de carga para las preguntas. Se muestra mientras que estas se obtienen.
with st.spinner(text=':hourglass: Looking for answers...'):
counter = 0
Expand All @@ -109,8 +145,11 @@ def annotateContext(response, answer, context):
with col2:
isWrong = st.button("👎", buttonKey + 1)
buttonKey += 2
#Si se pulsa el boton de correcto/incorrecto:
if isRight or isWrong:
#Mensaje de que el input del usuario ha sido registrado
st.success("✨ Thanks for your input!")
#Insertamos en la Spreadsheet de Google
#db.insert(conn, [[question,source,answer,isRight]])
#Reseteamos los valores de los botones
isRight = False
Expand Down

0 comments on commit fbc35d9

Please sign in to comment.