Spaces:
Running
on
Zero
Running
on
Zero
File size: 1,798 Bytes
f43cbc3 559d1e9 f43cbc3 fc2d69e f43cbc3 fc2d69e 4da1980 f43cbc3 4da1980 f43cbc3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import os
import spaces
import urllib.parse
import requests
import gradio as gr
from transformers import pipeline
SEARCH_TEMPLATE = "https://en.wikipedia.org/w/api.php?action=opensearch&search=%s&limit=1&namespace=0&format=json"
CONTENT_TEMPLATE = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=%s"
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
@spaces.GPU
def search_wikipedia(query):
query = urllib.parse.quote_plus(query)
data = requests.get(SEARCH_TEMPLATE % query).json()
if data and data[1]:
page = urllib.parse.quote_plus(data[1][0])
content = requests.get(CONTENT_TEMPLATE % page).json()
content = list(content["query"]["pages"].values())[0]["extract"]
summary = summarizer(content, max_length=150, min_length=50, do_sample=False)[0]['summary_text']
source = data[3][0]
return summary, source
else:
return "No results found.", ""
def chatbot_response(message, history):
summary, source = search_wikipedia(message)
response = f"Here's a summary of the top Wikipedia result:\n\n{summary}"
if source:
response += f"\n\nSource: {source}"
history.append((message, response))
return history
demo = gr.Blocks()
with demo:
gr.Markdown("# Wikipedia Chatbot")
gr.Markdown("This chatbot queries the Wikipedia API and summarizes the top result.")
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Enter your query")
clear = gr.Button("Clear")
msg.submit(chatbot_response, [msg, chatbot], chatbot).then(
lambda: gr.update(value=""), None, [msg], queue=False
)
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch() |