Advertisement
max2201111

app.py bez GT

Jun 16th, 2024
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.99 KB | Science | 0 0
  1. from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify
  2. from flask_sqlalchemy import SQLAlchemy
  3. from flask_migrate import Migrate
  4. from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
  5. from werkzeug.security import generate_password_hash, check_password_hash
  6. import requests
  7. from bs4 import BeautifulSoup
  8. import json
  9. import random
  10.  
  11. app = Flask(__name__)
  12. app.secret_key = 'your_secret_key'
  13. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
  14. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  15.  
  16. db = SQLAlchemy(app)
  17. migrate = Migrate(app, db)
  18. login_manager = LoginManager(app)
  19. login_manager.login_view = 'login'
  20.  
  21. class User(UserMixin, db.Model):
  22.     id = db.Column(db.Integer, primary_key=True)
  23.     username = db.Column(db.String(150), unique=True, nullable=False)
  24.     password = db.Column(db.String(150), nullable=False)
  25.     is_superuser = db.Column(db.Boolean, default=False)
  26.     successful_translations = db.Column(db.Integer, default=0, nullable=False)
  27.  
  28. class Translation(db.Model):
  29.     id = db.Column(db.Integer, primary_key=True)
  30.     user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
  31.     term = db.Column(db.String(150), nullable=False)
  32.     direction = db.Column(db.String(50), nullable=False)
  33.     translations = db.Column(db.JSON, nullable=False)
  34.     user = db.relationship('User', backref=db.backref('translations', lazy=True))
  35.  
  36. @login_manager.user_loader
  37. def load_user(user_id):
  38.     return db.session.get(User, int(user_id))
  39.  
  40. @app.route('/register', methods=['GET', 'POST'])
  41. def register():
  42.     if request.method == 'POST':
  43.         username = request.form.get('username')
  44.         password = request.form.get('password')
  45.  
  46.         if User.query.filter_by(username=username).first():
  47.             flash('Username already exists')
  48.         else:
  49.             hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
  50.             new_user = User(username=username, password=hashed_password)
  51.             db.session.add(new_user)
  52.             db.session.commit()
  53.             flash('Registration successful, please log in.')
  54.             return redirect(url_for('login'))
  55.     return render_template('register.html')
  56.  
  57. @app.route('/login', methods=['GET', 'POST'])
  58. def login():
  59.     if request.method == 'POST':
  60.         username = request.form.get('username')
  61.         password = request.form.get('password')
  62.         user = User.query.filter_by(username=username).first()
  63.  
  64.         if user and check_password_hash(user.password, password):
  65.             login_user(user)
  66.             flash('Login successful.')
  67.             next_page = request.args.get('next')
  68.             return redirect(next_page or url_for('index'))
  69.         else:
  70.             flash('Invalid username or password.')
  71.     return render_template('login.html')
  72.  
  73. @app.route('/logout')
  74. @login_required
  75. def logout():
  76.     logout_user()
  77.     flash('Logged out successfully.')
  78.     return redirect(url_for('login'))
  79.  
  80. @app.route('/', methods=['GET', 'POST'])
  81. @login_required
  82. def index():
  83.     en_cz_translations = Translation.query.filter_by(direction='en_cz', user_id=current_user.id).order_by(Translation.id.desc()).all()
  84.     cz_en_translations = Translation.query.filter_by(direction='cz_en', user_id=current_user.id).order_by(Translation.id.desc()).all()
  85.  
  86.     if 'correct' not in session:
  87.         session['correct'] = 0
  88.     if 'total' not in session:
  89.         session['total'] = 0
  90.  
  91.     if request.method == 'POST':
  92.         term = request.form.get('term')
  93.         direction = request.form.get('direction')
  94.  
  95.         if direction == 'en_cz':
  96.             url = f'https://slovnik.seznam.cz/preklad/anglicky_cesky/{term}'
  97.         elif direction == 'cz_en':
  98.             url = f'https://slovnik.seznam.cz/preklad/cesky_anglicky/{term}'
  99.         else:
  100.             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)
  101.  
  102.         response = requests.get(url)
  103.  
  104.         if response.status_code == 200:
  105.             soup = BeautifulSoup(response.content, 'lxml')
  106.  
  107.             script_tag = soup.find('script', {'id': '__NEXT_DATA__'})
  108.  
  109.             if script_tag:
  110.                 try:
  111.                     json_data = json.loads(script_tag.string)
  112.                     translations = json_data['props']['pageProps']['translations']
  113.                     term_data = []
  114.                     for translation in translations:
  115.                         sens_data = []
  116.                         for sens in translation['sens']:
  117.                             desc = sens.get('desc2', '')
  118.                             note = sens.get('note2', '')
  119.                             morf = sens.get('morf', translation.get('morf', 'Neznámý druh'))
  120.                             samples = [f"{samp['samp2s']} -> {samp['samp2t']}" for samp in sens.get('samp2', [])]
  121.                             trans = [''.join(t) for t in sens.get('trans', []) if t]
  122.                             coll2 = [f"{c['coll2s']} -> {c['coll2t']}" for c in sens.get('coll2', [])]
  123.                             sens_data.append({'morf': morf, 'desc': desc, 'note': note, 'samples': samples, 'trans': trans, 'coll2': coll2})
  124.                         term_data.append(sens_data)
  125.  
  126.                     new_translation = Translation(user_id=current_user.id, term=term, direction=direction, translations=term_data)
  127.                     db.session.add(new_translation)
  128.                     db.session.commit()
  129.  
  130.                     en_cz_translations = Translation.query.filter_by(direction='en_cz', user_id=current_user.id).order_by(Translation.id.desc()).all()
  131.                     cz_en_translations = Translation.query.filter_by(direction='cz_en', user_id=current_user.id).order_by(Translation.id.desc()).all()
  132.  
  133.                 except json.JSONDecodeError as e:
  134.                     error = f'Error decoding JSON: {str(e)}'
  135.                     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)
  136.             else:
  137.                 error = 'Error: Unable to find the JSON data script tag.'
  138.                 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)
  139.         else:
  140.             error = f'Error: Unable to fetch data for term "{term}".'
  141.             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)
  142.  
  143.     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)
  144.  
  145. @app.route('/reset_counter', methods=['POST'])
  146. @login_required
  147. def reset_counter():
  148.     session['correct'] = 0
  149.     session['total'] = 0
  150.     return redirect(url_for('index'))
  151.  
  152. @app.route('/quiz', methods=['GET', 'POST'])
  153. @login_required
  154. def quiz():
  155.     if request.method == 'POST':
  156.         selected_answer = request.form.get('answer')
  157.         correct_answer = request.form.get('correct_answer')
  158.  
  159.         if selected_answer == correct_answer:
  160.             session['correct'] = session.get('correct', 0) + 1
  161.             if current_user.successful_translations is None:
  162.                 current_user.successful_translations = 0
  163.             current_user.successful_translations += 1
  164.             db.session.commit()
  165.         session['total'] = session.get('total', 0) + 1
  166.  
  167.         return redirect(url_for('index'))
  168.  
  169.     translations = Translation.query.filter_by(user_id=current_user.id).all()
  170.     if translations:
  171.         translation = random.choice(translations)
  172.         term = translation.term
  173.         data = translation.translations
  174.         if not data:
  175.             flash('No translation data available for quiz.')
  176.             return redirect(url_for('index'))
  177.  
  178.         question_data = random.choice(data)
  179.         if not question_data or not question_data[0]['trans']:
  180.             flash('No valid translation data available for quiz.')
  181.             return redirect(url_for('index'))
  182.  
  183.         correct_answer = question_data[0]['trans'][0]
  184.         options = [correct_answer]
  185.  
  186.         all_terms = [t.term for t in translations if t.term != term]
  187.         if all_terms:
  188.             incorrect_terms = random.sample(all_terms, min(3, len(all_terms)))
  189.             for incorrect_term in incorrect_terms:
  190.                 incorrect_translation = Translation.query.filter_by(term=incorrect_term, user_id=current_user.id).first()
  191.                 if incorrect_translation and incorrect_translation.translations and incorrect_translation.translations[0] and incorrect_translation.translations[0][0]['trans']:
  192.                     options.append(incorrect_translation.translations[0][0]['trans'][0])
  193.  
  194.         random.shuffle(options)
  195.  
  196.         return render_template('quiz.html', question=term, options=options, correct_answer=correct_answer, question_data=question_data)
  197.  
  198.     flash('No translations available for quiz.')
  199.     return redirect(url_for('index'))
  200.  
  201. @app.route('/delete/<int:id>', methods=['POST'])
  202. @login_required
  203. def delete(id):
  204.     translation = Translation.query.get(id)
  205.     if translation and translation.user_id == current_user.id:
  206.         db.session.delete(translation)
  207.         db.session.commit()
  208.     return redirect(url_for('index'))
  209.  
  210. @app.route('/delete_all', methods=['POST'])
  211. @login_required
  212. def delete_all():
  213.     Translation.query.filter_by(user_id=current_user.id).delete()
  214.     db.session.commit()
  215.     return redirect(url_for('index'))
  216.  
  217. @app.route('/create_user')
  218. def create_user():
  219.     username = 'ja3'
  220.     password = 'ja3'
  221.  
  222.     if User.query.filter_by(username=username).first():
  223.         return "User already exists."
  224.     else:
  225.         hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
  226.         new_user = User(username=username, password=hashed_password)
  227.         db.session.add(new_user)
  228.         db.session.commit()
  229.         return "User created successfully."
  230.  
  231. @app.route('/progress')
  232. @login_required
  233. def progress():
  234.     if not current_user.is_superuser:
  235.         return redirect(url_for('index'))
  236.  
  237.     users = User.query.all()
  238.     user_progress = []
  239.     for user in users:
  240.         translations_count = Translation.query.filter_by(user_id=user.id).count()
  241.         user_progress.append({
  242.             'username': user.username,
  243.             'password': user.password,  # This should not be displayed in a real application for security reasons
  244.             'successful_translations': user.successful_translations,
  245.             'translations_count': translations_count
  246.         })
  247.  
  248.     return render_template('progress.html', user_progress=user_progress)
  249.  
  250. @app.route('/get_translations', methods=['GET'])
  251. @login_required
  252. def get_translations():
  253.     translations = Translation.query.filter_by(user_id=current_user.id).all()
  254.     translations_data = [
  255.         {
  256.             'term': translation.term,
  257.             'direction': translation.direction,
  258.             'translations': translation.translations
  259.         }
  260.         for translation in translations
  261.     ]
  262.     return jsonify({'translations': translations_data}), 200
  263.  
  264. if __name__ == '__main__':
  265.     with app.app_context():
  266.         db.create_all()
  267.         # Create superuser RUT with password 'all'
  268.         if not User.query.filter_by(username='RUT').first():
  269.             hashed_password = generate_password_hash('all', method='pbkdf2:sha256')
  270.             superuser = User(username='RUT', password=hashed_password, is_superuser=True)
  271.             db.session.add(superuser)
  272.             db.session.commit()
  273.     app.run(debug=True)
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement