Untitled conversation
- User
{% extends "manage.html" %} {% block title %}Import Book{% endblock %}
{% block manage %}
{ "english": "When talking about numbers, magnitude simply refers to the size of something, whereas in other contexts it indicates large size or importance.", "missing_words": [ { "word": "magnitude", "position": 5, }, { "word": "order of magnitude", "position": [28,29,30], } ] }, {...} # miejsce na pozostałę zdania # Opracowany plik json wraz z właściwie policzonymi pozycjami słów oraz ciągów słów missing_words zapisz do zmiennej globalnej i wyświetl w konsoli w celu sprawdzenia poprawnosci pliku json Uzupełnij logikę javascript -->{% endblock %}
{% block scripts %}
{% endblock %}
- Assistant
Certainly! Below is the JavaScript code that completes the functionality as per your requirements. This script handles the text input, splits it into sentences, displays words individually, allows word selection (including sequences of words), calculates word positions, and generates the desired JSON structure. The JSON is stored in a global variable and printed to the console.
HTML Adjustments:
First, we need to add a textarea for text input in the form:
<form id="uploadForm"> <div class="form-group"> <!-- Text input area --> <textarea id="textInput" class="form-control" rows="8" placeholder="Paste your text here..."></textarea> </div> <button type="submit" class="btn btn-primary">Upload and Process</button> </form>JavaScript Logic (
load_text.js):document.addEventListener('DOMContentLoaded', function() { const uploadForm = document.getElementById('uploadForm'); const textInput = document.getElementById('textInput'); const sentenceContainer = document.getElementById('sentenceContainer'); let resultData = []; // Global variable to store the result uploadForm.addEventListener('submit', function(e) { e.preventDefault(); const text = textInput.value.trim(); if (text) { processText(text); } }); function processText(text) { // Split text into sentences const sentences = splitTextIntoSentences(text); sentenceContainer.innerHTML = ''; sentences.forEach((sentence, sentenceIndex) => { // Create a div for each sentence const sentenceDiv = document.createElement('div'); sentenceDiv.classList.add('sentence'); sentenceDiv.dataset.index = sentenceIndex; sentenceDiv.style.marginBottom = '20px'; // Split sentence into words const words = sentence.split(/\s+/); words.forEach((word, wordIndex) => { const span = document.createElement('span'); span.classList.add('word'); span.textContent = word + ' '; span.dataset.wordIndex = wordIndex; // Add event listener to toggle selection span.addEventListener('click', function() { span.classList.toggle('missing-word'); updateResultData(); }); sentenceDiv.appendChild(span); }); sentenceContainer.appendChild(sentenceDiv); }); // Initialize result data initializeResultData(sentences); } function splitTextIntoSentences(text) { // Simple sentence splitting using regex return text.match(/[^\.!\?]+[\.!\?]+|[^\.!\?]+$/g) || [text]; } function initializeResultData(sentences) { resultData = sentences.map(sentence => ({ "english": sentence.trim(), "missing_words": [] })); } function updateResultData() { const sentenceDivs = document.querySelectorAll('#sentenceContainer .sentence'); sentenceDivs.forEach(sentenceDiv => { const sentenceIndex = sentenceDiv.dataset.index; const sentenceData = resultData[sentenceIndex]; const wordSpans = sentenceDiv.querySelectorAll('.word'); sentenceData.missing_words = []; let selectedIndices = []; wordSpans.forEach((span, wordIndex) => { if (span.classList.contains('missing-word')) { selectedIndices.push(parseInt(wordIndex)); } }); // Find consecutive sequences in selectedIndices const sequences = []; let tempSeq = []; for (let i = 0; i < selectedIndices.length; i++) { if (tempSeq.length === 0) { tempSeq.push(selectedIndices[i]); } else { if (selectedIndices[i] === tempSeq[tempSeq.length - 1] + 1) { tempSeq.push(selectedIndices[i]); } else { sequences.push(tempSeq.slice()); tempSeq = [selectedIndices[i]]; } } } if (tempSeq.length > 0) { sequences.push(tempSeq.slice()); } // For each sequence, get the words and positions sequences.forEach(seq => { const positions = seq; const words = positions.map(i => wordSpans[i].textContent.trim()); const wordText = words.join(' '); if (positions.length === 1) { sentenceData.missing_words.push({ "word": wordText, "position": positions[0] }); } else { sentenceData.missing_words.push({ "word": wordText, "position": positions }); } }); }); console.log(resultData); } });Explanation:
-
Text Input Handling: The script listens for the form submission, prevents the default action, and processes the input text.
-
Sentence Splitting: The
splitTextIntoSentencesfunction uses a regular expression to split the input text into sentences. -
Word Display and Selection:
- Each sentence is split into words.
- Words are displayed as clickable spans.
- Clicking on a word toggles the
missing-wordclass (highlighting it) and updates the result data.
-
Selection Tracking and JSON Generation:
- The
updateResultDatafunction tracks selected words and identifies consecutive sequences to handle multi-word selections. - It constructs the
missing_wordsarray with correct word positions. - The JSON structure is stored in the
resultDataglobal variable and printed to the console for verification.
- The
Integration into Your Template:
Make sure to include the updated JavaScript in your template or ensure that
load_text.jscontains the above script.
Final Template (
manage.html):{% extends "manage.html" %} {% block title %}Import Book{% endblock %} {% block manage %} <div class="container"> <h1 class="mt-5">Import Book</h1> <form id="uploadForm"> <div class="form-group"> <!-- Text input area --> <textarea id="textInput" class="form-control" rows="8" placeholder="Paste your text here..."></textarea> </div> <button type="submit" class="btn btn-primary">Upload and Process</button> </form> <!-- Container to display sentences --> <div id="sentenceContainer" class="mt-5"> <!-- The processed text will be displayed here with interactive word selection --> </div> </div> <style> .word { cursor: pointer; } .missing-word { background-color: yellow; text-decoration: underline; } </style> {% endblock %} {% block scripts %} <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script> <script src="{{ url_for('static', filename='project/js/manage/load_text.js') }}"></script> {% endblock %}With this setup, when the user pastes text and clicks "Upload and Process," the text is processed, and they can select words or phrases by clicking on them. The positions of these words are calculated, and the JSON structure is updated and printed to the console for verification.
Note: Adjustments may be necessary depending on the specifics of your environment or additional requirements. Make sure all elements have the correct IDs and classes, and that the script is properly linked.
-