// script.js modifications
var article_name = document.getElementById('article_name');
var question_body = document.getElementById('question_body');
var search = document.getElementById('article_name_input'); // Now takes a URL
var next_question_btn = document.getElementById('next_question_btn');
var answer_a = document.getElementById('answer_a');
var answer_b = document.getElementById('answer_b');
var answer_c = document.getElementById('answer_c');
var answer_response_label = document.getElementById('answer_response_label');
answer_response_label.style.display = "none";
answer_a.style.display = "none";
answer_b.style.display = "none";
answer_c.style.display = "none";
next_question_btn.style.display = "none";
var q_idx = 0;
var curQuery;
var correct_answer;
function new_article_query(_data) {
if (!_data) {
make_request(search.value, new_article_query); // Sends URL to backend
curQuery = search.value;
} else {
article_name.innerHTML = search.value;
gdata = _data;
load_question();
}
}
function make_request(query, _callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
_callback(JSON.parse(xmlHttp.responseText));
}
}
xmlHttp.open("GET", 'http://127.0.0.1:5000/quiz_url/?url=' + encodeURIComponent(query), true); // Modified endpoint
xmlHttp.send(null);
}
// ... (rest of the script.js remains the same)
python
# server.py modifications
import requests, json
from flask import Flask, request, Response
from Article import Article
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route('/quiz_url/', methods = ['GET']) # New endpoint
def get_quiz_from_url():
url = request.args.get('url')
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
soup = BeautifulSoup(response.content, 'html.parser')
# Extract text content, you might need to adjust this based on the website structure
page_content = soup.get_text()
a = Article(page_content=page_content) # Modified Article instantiation
_resp = []
for question in a.quiz.get_ten_random():
_resp.append((question.text, question.gaps))
data_send = json.dumps({
'sentences': _resp,
'propers': a.quiz.get_random_propers(),
})
resp = Response(data_send, status=200, mimetype='application/json')
resp.headers['Access-Control-Allow-Origin'] = "*"
return resp
except requests.exceptions.RequestException as e:
return Response(f"Error fetching URL: {e}", status=500, mimetype='application/json')
except Exception as e:
return Response(f"An error occurred: {e}", status=500, mimetype='application/json')
@app.route('/quiz/<article_name>/', methods = ['GET']) # Keep the old endpoint
def get_quiz(article_name):
# ... (Existing code for Wikipedia article)
if __name__ == '__main__':
app.debug = True
app.run()
python
# Article.py modifications
# ... (other imports)
from bs4 import BeautifulSoup
import requests
class Article():
def __init__ (self, name=None, page_content=None): # Modified constructor
if name: # For Wikipedia articles
self.name = name
self.page = wiki.page(name)
content = self.page.content.encode('ascii', 'ignore')
elif page_content: # For URL content
content = page_content.encode('ascii', 'ignore')
else:
raise ValueError("Either 'name' or 'page_content' must be provided.")
self.quiz = Quiz([])
self.generate_questions_for(content.decode("utf-8")) # Decode here
# ... (rest of the class remains largely the same)
Explanation of Changes:
server.py:
A new route /quiz_url/ is added to handle URL input. It retrieves the URL from the query parameters.
The requests library fetches the content of the URL. Error handling is included for invalid URLs or requests that fail.
BeautifulSoup parses the HTML content and extracts the text. Important: The way you extract text might need adjustments depending on the website's structure. It might be necessary to identify the specific elements containing the main text content.
The Article class is instantiated with the extracted page_content.
Article.py:
The Article constructor is modified to accept either a name (for Wikipedia titles) or page_content (for URL content). It now raises a ValueError if neither is provided.
The logic within the constructor now branches based on whether name or page_content is provided. The appropriate content is then used for question generation. The decoding of the content from bytes to string is moved to within the constructor after the conditional check.
script.js:
The make_request function is updated to send the URL to the new /quiz_url/ endpoint. The URL is URI-encoded using encodeURIComponent to handle special characters. The rest of the client-side logic remains mostly unchanged, as it receives the same JSON structure from the server.
Key Improvements & Considerations:
Error Handling: The server.py now includes error handling for invalid URLs and failed requests, returning appropriate error responses.
Flexibility: The Article class can now handle both Wikipedia articles and web URLs, making the application more versatile.
Website Structure: You'll likely need to adapt the BeautifulSoup parsing in server.py to correctly extract the main text content from different websites. Inspect the HTML structure of the target website to identify the relevant elements.
Robustness: Consider adding more robust error handling and input validation to handle various scenarios and prevent unexpected behavior. Consider sanitizing the extracted text to remove unwanted characters or formatting.
Security: When dealing with external URLs, be mindful of potential security risks. Sanitize input and avoid executing arbitrary code from the fetched content.
This revised approach provides a more flexible and robust solution for generating quizzes from web links. Remember to tailor the HTML parsing to the specific structure of the websites you intend to use.