import gradio as gr
import rdflib

# Load the Turtle file and initialize the graph
g = rdflib.Graph()
g.parse('huggingface.ttl')

# Define the function to execute the SPARQL query
def run_sparql(query):
    try:
        qres = g.query(query)
        results = []
        for row in qres:
            # Concatenate each row's results into a readable string
            result = " | ".join(str(cell) for cell in row)
            results.append(result)
        return "\n".join(results) if results else "No results found."
    except Exception as e:
        return f"Error: {e}"

# Gradio interface
query_input = gr.Textbox(label="SPARQL Query", lines=5, placeholder="Enter SPARQL query here", value="SELECT DISTINCT ?b WHERE {?a ?b ?c}")
output_text = gr.Textbox(label="Query Results", lines=10)

# Launch the app
demo = gr.Interface(
    fn=run_sparql,
    inputs=query_input,
    outputs=output_text,
    title="Hugging Face Datasets SPARQL Query Interface",
    description="Enter a SPARQL query to retrieve data from the Turtle file. Generated by [huggingface-rdf](https://github.com/david4096/huggingface-rdf). [Download the turtle file locally](https://github.com/david4096/huggingface-rdf/releases/download/data-release/huggingface.ttl) and load it into your [favorite triple store](https://github.com/david4096/huggingface-rdf/tree/main/qlever_scripts)!",
)

if __name__ == "__main__":
    demo.launch()



if __name__ == "__main__":
    demo.launch()