Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify
- from flask_sqlalchemy import SQLAlchemy
- from flask_migrate import Migrate
- from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
- from werkzeug.security import generate_password_hash, check_password_hash
- import requests
- from bs4 import BeautifulSoup
- import json
- import random
- app = Flask(__name__)
- app.secret_key = 'your_secret_key'
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- db = SQLAlchemy(app)
- migrate = Migrate(app, db)
- login_manager = LoginManager(app)
- login_manager.login_view = 'login'
- class User(UserMixin, db.Model):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(150), unique=True, nullable=False)
- password = db.Column(db.String(150), nullable=False)
- is_superuser = db.Column(db.Boolean, default=False)
- successful_translations = db.Column(db.Integer, default=0, nullable=False)
- class Translation(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- term = db.Column(db.String(150), nullable=False)
- direction = db.Column(db.String(50), nullable=False)
- translations = db.Column(db.JSON, nullable=False)
- user = db.relationship('User', backref=db.backref('translations', lazy=True))
- @login_manager.user_loader
- def load_user(user_id):
- return db.session.get(User, int(user_id))
- @app.route('/register', methods=['GET', 'POST'])
- def register():
- if request.method == 'POST':
- username = request.form.get('username')
- password = request.form.get('password')
- if User.query.filter_by(username=username).first():
- flash('Username already exists')
- else:
- hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
- new_user = User(username=username, password=hashed_password)
- db.session.add(new_user)
- db.session.commit()
- flash('Registration successful, please log in.')
- return redirect(url_for('login'))
- return render_template('register.html')
- @app.route('/login', methods=['GET', 'POST'])
- def login():
- if request.method == 'POST':
- username = request.form.get('username')
- password = request.form.get('password')
- user = User.query.filter_by(username=username).first()
- if user and check_password_hash(user.password, password):
- login_user(user)
- flash('Login successful.')
- next_page = request.args.get('next')
- return redirect(next_page or url_for('index'))
- else:
- flash('Invalid username or password.')
- return render_template('login.html')
- @app.route('/logout')
- @login_required
- def logout():
- logout_user()
- flash('Logged out successfully.')
- return redirect(url_for('login'))
- @app.route('/', methods=['GET', 'POST'])
- @login_required
- def index():
- en_cz_translations = Translation.query.filter_by(direction='en_cz', user_id=current_user.id).order_by(Translation.id.desc()).all()
- cz_en_translations = Translation.query.filter_by(direction='cz_en', user_id=current_user.id).order_by(Translation.id.desc()).all()
- if 'correct' not in session:
- session['correct'] = 0
- if 'total' not in session:
- session['total'] = 0
- if request.method == 'POST':
- term = request.form.get('term')
- direction = request.form.get('direction')
- if direction == 'en_cz':
- url = f'https://slovnik.seznam.cz/preklad/anglicky_cesky/{term}'
- elif direction == 'cz_en':
- url = f'https://slovnik.seznam.cz/preklad/cesky_anglicky/{term}'
- else:
- return render_template('index.html', user_authenticated=True, en_cz_translations=en_cz_translations, cz_en_translations=cz_en_translations, correct=session['correct'], total=session['total'], enumerate=enumerate)
- response = requests.get(url)
- if response.status_code == 200:
- soup = BeautifulSoup(response.content, 'lxml')
- script_tag = soup.find('script', {'id': '__NEXT_DATA__'})
- if script_tag:
- try:
- json_data = json.loads(script_tag.string)
- translations = json_data['props']['pageProps']['translations']
- term_data = []
- for translation in translations:
- sens_data = []
- for sens in translation['sens']:
- desc = sens.get('desc2', '')
- note = sens.get('note2', '')
- morf = sens.get('morf', translation.get('morf', 'Neznámý druh'))
- samples = [f"{samp['samp2s']} -> {samp['samp2t']}" for samp in sens.get('samp2', [])]
- trans = [''.join(t) for t in sens.get('trans', []) if t]
- coll2 = [f"{c['coll2s']} -> {c['coll2t']}" for c in sens.get('coll2', [])]
- sens_data.append({'morf': morf, 'desc': desc, 'note': note, 'samples': samples, 'trans': trans, 'coll2': coll2})
- term_data.append(sens_data)
- new_translation = Translation(user_id=current_user.id, term=term, direction=direction, translations=term_data)
- db.session.add(new_translation)
- db.session.commit()
- en_cz_translations = Translation.query.filter_by(direction='en_cz', user_id=current_user.id).order_by(Translation.id.desc()).all()
- cz_en_translations = Translation.query.filter_by(direction='cz_en', user_id=current_user.id).order_by(Translation.id.desc()).all()
- except json.JSONDecodeError as e:
- error = f'Error decoding JSON: {str(e)}'
- return render_template('index.html', user_authenticated=True, error=error, en_cz_translations=en_cz_translations, cz_en_translations=cz_en_translations, correct=session['correct'], total=session['total'], enumerate=enumerate)
- else:
- error = 'Error: Unable to find the JSON data script tag.'
- return render_template('index.html', user_authenticated=True, error=error, en_cz_translations=en_cz_translations, cz_en_translations=cz_en_translations, correct=session['correct'], total=session['total'], enumerate=enumerate)
- else:
- error = f'Error: Unable to fetch data for term "{term}".'
- return render_template('index.html', user_authenticated=True, error=error, en_cz_translations=en_cz_translations, cz_en_translations=cz_en_translations, correct=session['correct'], total=session['total'], enumerate=enumerate)
- return render_template('index.html', user_authenticated=True, en_cz_translations=en_cz_translations, cz_en_translations=cz_en_translations, correct=session['correct'], total=session['total'], enumerate=enumerate)
- @app.route('/reset_counter', methods=['POST'])
- @login_required
- def reset_counter():
- session['correct'] = 0
- session['total'] = 0
- return redirect(url_for('index'))
- @app.route('/quiz', methods=['GET', 'POST'])
- @login_required
- def quiz():
- if request.method == 'POST':
- selected_answer = request.form.get('answer')
- correct_answer = request.form.get('correct_answer')
- if selected_answer == correct_answer:
- session['correct'] = session.get('correct', 0) + 1
- if current_user.successful_translations is None:
- current_user.successful_translations = 0
- current_user.successful_translations += 1
- db.session.commit()
- session['total'] = session.get('total', 0) + 1
- return redirect(url_for('index'))
- translations = Translation.query.filter_by(user_id=current_user.id).all()
- if translations:
- translation = random.choice(translations)
- term = translation.term
- data = translation.translations
- if not data:
- flash('No translation data available for quiz.')
- return redirect(url_for('index'))
- question_data = random.choice(data)
- if not question_data or not question_data[0]['trans']:
- flash('No valid translation data available for quiz.')
- return redirect(url_for('index'))
- correct_answer = question_data[0]['trans'][0]
- options = [correct_answer]
- all_terms = [t.term for t in translations if t.term != term]
- if all_terms:
- incorrect_terms = random.sample(all_terms, min(3, len(all_terms)))
- for incorrect_term in incorrect_terms:
- incorrect_translation = Translation.query.filter_by(term=incorrect_term, user_id=current_user.id).first()
- if incorrect_translation and incorrect_translation.translations and incorrect_translation.translations[0] and incorrect_translation.translations[0][0]['trans']:
- options.append(incorrect_translation.translations[0][0]['trans'][0])
- random.shuffle(options)
- return render_template('quiz.html', question=term, options=options, correct_answer=correct_answer, question_data=question_data)
- flash('No translations available for quiz.')
- return redirect(url_for('index'))
- @app.route('/delete/<int:id>', methods=['POST'])
- @login_required
- def delete(id):
- translation = Translation.query.get(id)
- if translation and translation.user_id == current_user.id:
- db.session.delete(translation)
- db.session.commit()
- return redirect(url_for('index'))
- @app.route('/delete_all', methods=['POST'])
- @login_required
- def delete_all():
- Translation.query.filter_by(user_id=current_user.id).delete()
- db.session.commit()
- return redirect(url_for('index'))
- @app.route('/create_user')
- def create_user():
- username = 'ja3'
- password = 'ja3'
- if User.query.filter_by(username=username).first():
- return "User already exists."
- else:
- hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
- new_user = User(username=username, password=hashed_password)
- db.session.add(new_user)
- db.session.commit()
- return "User created successfully."
- @app.route('/progress')
- @login_required
- def progress():
- if not current_user.is_superuser:
- return redirect(url_for('index'))
- users = User.query.all()
- user_progress = []
- for user in users:
- translations_count = Translation.query.filter_by(user_id=user.id).count()
- user_progress.append({
- 'username': user.username,
- 'password': user.password, # This should not be displayed in a real application for security reasons
- 'successful_translations': user.successful_translations,
- 'translations_count': translations_count
- })
- return render_template('progress.html', user_progress=user_progress)
- @app.route('/get_translations', methods=['GET'])
- @login_required
- def get_translations():
- translations = Translation.query.filter_by(user_id=current_user.id).all()
- translations_data = [
- {
- 'term': translation.term,
- 'direction': translation.direction,
- 'translations': translation.translations
- }
- for translation in translations
- ]
- return jsonify({'translations': translations_data}), 200
- if __name__ == '__main__':
- with app.app_context():
- db.create_all()
- # Create superuser RUT with password 'all'
- if not User.query.filter_by(username='RUT').first():
- hashed_password = generate_password_hash('all', method='pbkdf2:sha256')
- superuser = User(username='RUT', password=hashed_password, is_superuser=True)
- db.session.add(superuser)
- db.session.commit()
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement