Utwóż plik html, który umożliwi zaimportowanie książki pdf, EPUB, MOBI, txt, DOC/DOCX do następującej struktury pliku json:
{
"texts":[
{
"uuid":"123e4567-e89b-12d3-a456-426614174000",
"name":"homeless",
"tag": "",
"sentences":[
{
"english":"Anyone who has lost their permanent accommodation is classified in the UK as homeless.",
"polish":"Każda osoba, która utraciła swoje stałe zakwaterowanie, jest w Wielkiej Brytanii klasyfikowana jako bezdomna.",
"missing_words":[
{
"word":"Anyone",
"position":1,
"translation":"Każda osoba"
}
]
},
{
"english":"Sometimes these may be people who have nowhere to live and are literally sleeping on the street, but in practice the majority will be people living in temporary accommodation.",
"polish":"Czasami mogą to być osoby, które nie mają gdzie mieszkać i dosłownie śpią na ulicy, ale w praktyce większość stanowić będą osoby mieszkające w tymczasowych miejscach zakwaterowania.",
"missing_words":[
{
"word":"Sometimes",
"position":1,
"translation":"Czasami"
},
{
"word":"nowhere",
"position":8,
"translation":"nigdzie"
},
{
"word":"in",
"position":19,
"translation":"w"
}
]
},
{
"english":"All of the bodies concerned with the homeless agree with the government on exact numbers of homeless people, mainly because each organization has its own way of defining who the homeless are.",
"polish":"Wszystkie organy zajmujące się bezdomnymi zgadzają się z rządem co do dokładnej liczby bezdomnych osób, głównie dlatego, że każda organizacja ma swój własny sposób definiowania, kim są bezdomni.",
"missing_words":[
{
"word":"All",
"position":1,
"translation":"Wszystkie"
},
{
"word":"each",
"position":11,
"translation":"każda"
}
]
} {...}
W tym celu utwóż szablon html oparty o bootstrap, którego zawartość będzie wchodzić w następujący schemat html:
{% extends "manage.html" %}
{% block title %}Edit list words{% endblock %}
{% block manage %}
{% block scripts %}
{% endblock %}
Skrypt javascript powinien dzielić text na zdania i umożliwiać wybór użytkownikowi słowa jakie powinno być wywalone ze zdania.
Pozycja tego słowa powinna być włąściwie policzona w tekście
Assistant
Certainly! Let's work through the steps to create an HTML interface that allows importing books in various formats and processing them into the specified JSON structure. We'll also ensure that users can select words to omit from sentences, and the positions of these words are correctly calculated.
Step 1: Create an HTML File to Import Books
Firstly, we'll create an HTML template that allows users to upload books in various formats (PDF, EPUB, MOBI, TXT, DOC/DOCX). Since handling multiple file formats requires different parsing techniques, we'll focus on handling plain text (.txt) files for simplicity. You can expand this to other formats using appropriate libraries.
HTML Template
Here's how you can set up your HTML file using Bootstrap:
html
<!-- extend the existing 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">
<label for="bookFile">Choose a book file to upload:</label>
<input type="file" class="form-control-file" id="bookFile" accept=".txt">
</div>
<button type="submit" class="btn btn-primary">Upload and Process</button>
</form>
<!-- Container to display sentences -->
<div id="sentenceContainer" class="mt-5">
<!-- Sentences will be dynamically added here -->
</div>
</div>
{% endblock %}
{% block scripts %}
<script src="{{ url_for('static', filename='project/js/manage/load_text.js') }}"></script>
{% endblock %}
This template sets up a file upload form and a container where we'll display the sentences after processing the text.
Step 2: Create the JavaScript to Process the Uploaded File
In your load_text.js file, we'll handle the file upload, read the content, split it into sentences, and allow the user to select words to omit.
JavaScript Code (load_text.js)
javascript
// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', function () {
const uploadForm = document.getElementById('uploadForm');
const bookFileInput = document.getElementById('bookFile');
const sentenceContainer = document.getElementById('sentenceContainer');
let sentencesData = [];
// Handle form submission
uploadForm.addEventListener('submit', function (event) {
event.preventDefault();
const file = bookFileInput.files[0];
if (file) {
// Read the file content
const reader = new FileReader();
reader.onload = function (e) {
const textContent = e.target.result;
processTextContent(textContent);
};
reader.readAsText(file);
} else {
alert('Please select a file.');
}
});
// Function to process the text content
function processTextContent(text) {
// Split the text into sentences using a simple regex
const sentences = text.match(/[^\.!\?]+[\.!\?]+/g);
if (sentences) {
sentenceContainer.innerHTML = ''; // Clear previous content
sentencesData = []; // Reset sentences data
sentences.forEach((sentenceText, index) => {
// Trim whitespace
const sentence = sentenceText.trim();
// Create a sentence object to hold data
const sentenceObj = {
english: sentence,
missing_words: []
};
// Display the sentence with clickable words
const sentenceDiv = document.createElement('div');
sentenceDiv.classList.add('sentence');
sentenceDiv.setAttribute('data-index', index);
// Split the sentence into words
const words = sentence.split(/\s+/);
words.forEach((word, wordIndex) => {
const wordSpan = document.createElement('span');
wordSpan.classList.add('word');
wordSpan.textContent = word;
wordSpan.setAttribute('data-word-index', wordIndex + 1); // Positions start at 1
// Add click event to select missing words
wordSpan.addEventListener('click', function () {
toggleMissingWord(sentenceObj, word, wordIndex + 1, wordSpan);
});
sentenceDiv.appendChild(wordSpan);
sentenceDiv.appendChild(document.createTextNode(' '));
});
sentenceContainer.appendChild(sentenceDiv);
sentencesData.push(sentenceObj);
});
// Add a button to export JSON
const exportButton = document.createElement('button');
exportButton.textContent = 'Export JSON';
exportButton.classList.add('btn', 'btn-success', 'mt-3');
exportButton.addEventListener('click', exportToJson);
sentenceContainer.appendChild(exportButton);
} else {
alert('Could not split text into sentences.');
}
}
// Function to toggle missing words
function toggleMissingWord(sentenceObj, word, position, wordElement) {
const missingWordIndex = sentenceObj.missing_words.findIndex(
(mw) => mw.word === word && mw.position === position
);
if (missingWordIndex >= 0) {
// Word is already marked as missing, remove it
sentenceObj.missing_words.splice(missingWordIndex, 1);
wordElement.classList.remove('missing-word');
} else {
// Mark the word as missing
sentenceObj.missing_words.push({
word: word,
position: position,
translation: '' // You can add functionality to input translations
});
wordElement.classList.add('missing-word');
}
}
// Function to export data to JSON
function exportToJson() {
// Construct the final JSON structure
const data = {
texts: [
{
uuid: generateUUID(),
name: 'Imported Book',
tag: '',
sentences: sentencesData
}
]
};
const jsonStr = JSON.stringify(data, null, 2);
downloadJson(jsonStr, 'book.json');
}
// Function to generate a UUID (simple version)
function generateUUID() {
// Use a simple method for generating a UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// Function to download JSON as a file
function downloadJson(content, fileName) {
const a = document.createElement('a');
const file = new Blob([content], { type: 'application/json' });
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
});
Explanation of the JavaScript Code
File Upload Handling: We use the FileReader API to read the contents of the uploaded file.
Sentence Splitting: We split the text into sentences using a regular expression that matches ending punctuation marks.
Word Splitting and Display: Each sentence is split into words, and each word is rendered as a clickable <span>.
Selecting Missing Words: When a word is clicked, we toggle its status as a missing word. The word's position (starting from 1) is calculated based on its order in the sentence.
Updating the Data Structure: We keep track of the selected missing words in the sentencesData array.
Exporting to JSON: We provide a button to export the data into the required JSON format. The JSON is downloaded as a file.
CSS Styling
You'll need to add some CSS to style the missing words. Add this to your CSS file or within a <style> tag:
In the code above, the word positions are calculated based on their order in the sentence array. The position starts from 1 as per your requirement.
javascript
words.forEach((word, wordIndex) => {
// Position is wordIndex + 1
});
Step 4: Processing Translations (Optional)
In your JSON structure, each sentence includes an English sentence and its Polish translation. To incorporate translations, you could extend the interface to allow users to input translations.
Adding Translation Input
After processing the sentences, you can add an input field for translations:
javascript
function processTextContent(text) {
// ... Existing code ...
sentences.forEach((sentenceText, index) => {
// ... Existing code to create sentenceDiv ...
// Add an input field for the Polish translation
const translationInput = document.createElement('textarea');
translationInput.classList.add('form-control', 'mt-2');
translationInput.setAttribute('placeholder', 'Enter Polish translation');
translationInput.addEventListener('input', function () {
sentenceObj.polish = translationInput.value;
});
sentenceDiv.appendChild(translationInput);
// ... Existing code ...
});
// ... Existing code ...
}
Handling Different File Formats
To handle PDFs, EPUBs, MOBI files, and Word documents (.doc/.docx), you'll need to use libraries that can read these formats in the browser.
EPUB: Libraries like epub.js can handle EPUB files.
MOBI: Handling MOBI files in the browser is challenging due to format restrictions.
DOC/DOCX: Libraries like Mammoth.js can convert .docx files to HTML.
Each library will have its own API for extracting text content, and you'll need to adapt the processTextContent function accordingly.
Example: Reading a PDF File with PDF.js
javascript
// Include PDF.js
// You can include it via script tag or import statement
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script>
// Modify your file upload handling code
if (file.type === 'application/pdf') {
const fileReader = new FileReader();
fileReader.onload = function () {
const typedarray = new Uint8Array(this.result);
pdfjsLib.getDocument(typedarray).promise.then(function (pdf) {
let textContent = '';
const numPages = pdf.numPages;
// Read text from all pages
const getPageText = async (pageNum) => {
const page = await pdf.getPage(pageNum);
const textContentObj = await page.getTextContent();
const pageText = textContentObj.items.map((item) => item.str).join(' ');
textContent += pageText + '\n';
if (pageNum < numPages) {
getPageText(pageNum + 1);
} else {
processTextContent(textContent);
}
};
getPageText(1);
});
};
fileReader.readAsArrayBuffer(file);
}
Conclusion
By following the steps above, you can create an interactive web page that:
Allows users to upload a book file.
Parses the file and splits it into sentences.
Displays each sentence with clickable words.
Lets users select words to omit (mark as missing).
Correctly records the position of each missing word.
Exports the resulting data into the required JSON format.
Note: The code provided is a starting point. You may need to adjust it to handle edge cases and integrate it seamlessly with your existing project structure.
Full HTML and JavaScript Code
Here’s the full code for your HTML template and JavaScript file for reference.