diff --git a/Application_Folder/API_Backend/Backend_API.py b/Application_Folder/API_Backend/Backend_API.py deleted file mode 100644 index a338912..0000000 --- a/Application_Folder/API_Backend/Backend_API.py +++ /dev/null @@ -1,127 +0,0 @@ -from flask import Flask, render_template, request, redirect, url_for -from flask_wtf import FlaskForm -from wtforms import StringField, SubmitField, BooleanField, TextAreaField -from wtforms.validators import DataRequired, Email -from flask_sqlalchemy import SQLAlchemy -from textblob import TextBlob -from Quantum_Logistics_Solvers.Quantum_Genetic_Algorithm import QuantumTSP - -app = Flask (__name__) -app.config ['SECRET_KEY'] = 'your-secret-key' -app.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' -db = SQLAlchemy (app) - - -class User (db.Model): - id = db.Column (db.Integer, primary_key=True) - email = db.Column (db.String (120), unique=True, nullable=False) - category = db.Column (db.String (120), nullable=False) - - -class Feedback (db.Model): - id = db.Column (db.Integer, primary_key=True) - user_email = db.Column (db.String (120), unique=True, nullable=False) - feedback = db.Column (db.Text, nullable=False) - - -class RegistrationForm (FlaskForm): - email = StringField ('Email', validators=[DataRequired (), Email ()]) - user = BooleanField ('User') - business = BooleanField ('Business') - submit = SubmitField ('Register') - - -class FeedbackForm (FlaskForm): - email = StringField ('Email', validators=[DataRequired (), Email ()]) - feedback = TextAreaField ('Feedback', validators=[DataRequired ()]) - submit = SubmitField ('Submit') - - -@app.route ('/register', methods=['GET', 'POST']) -def register(): - form = RegistrationForm () - if form.validate_on_submit (): - user = User (email=form.email.data, category='user' if form.user.data else 'business') - db.session.add (user) - db.session.commit () - return redirect (url_for (user.category, email=user.email)) - return render_template ('register.html', form=form) - - -@app.route ('//', methods=['GET', 'POST']) -def user(category, email): - return render_template ('user.html', email=email) - - -@app.route ('/feedback', methods=['GET', 'POST']) -def feedback(): - form = FeedbackForm () - if form.validate_on_submit (): - feedback = Feedback (user_email=form.email.data, feedback=form.feedback.data) - db.session.add (feedback) - db.session.commit () - sentiment = TextBlob (feedback.feedback).sentiment - return {"message": "Feedback received", "sentiment": sentiment}, 201 - return render_template ('feedback.html', form=form) - - -@app.route ('/') -def index(): - return render_template ('index.html') - - -@app.route ('/run_algorithm', methods=['POST']) -def run_algorithm(): - # Check if the request is JSON - if not request.is_json: - return {"error": "Missing JSON in request"}, 400 - - # Extract the algorithm name and the number of cities from the request - algorithm_name = request.json.get ('algorithm') - num_cities = request.json.get ('num_cities') - - # Check if algorithm_name or num_cities is None - if algorithm_name is None: - return {"error": "The algorithm value is required"}, 400 - if num_cities is None: - return {"error": "The num_cities value is required"}, 400 - - # Convert num_cities to an integer - try: - num_cities = int(num_cities) - except ValueError: - return {"error": "The num_cities value must be an integer"}, 400 - - print (f"Running {algorithm_name} with {num_cities} cities") # Log the number of cities - - # Check if the algorithm is in the Algorithm dictionary - if algorithm_name in Algorithm: - # Get the algorithm class - algorithm_class = Algorithm [algorithm_name] - - # Create an instance of the algorithm - algorithm = algorithm_class (num_cities, pop_size=100, generations=500, mutation_rate=0.01, elite_size=20) - - # Run the algorithm with the provided number of cities - try: - result = algorithm.execute () # Call the execute method - except Exception as e: - return {"Internal server error occurred" - - # Print "Plot printed" in the console - print ("Plot printed") - - # Return the result and the plot as a base64 string - return {"result": result, "plot": result ['plot']}, 200 - else: - # Return an error message if the algorithm is not found - return {"error": "Algorithm not found"} - - -Algorithm = { - 'Quantum Genetic Algorithm': QuantumTSP -} - - -if __name__ == '__main__': - app.run (debug=False) diff --git a/Application_Folder/API_Backend/Backend_Test.py b/Application_Folder/API_Backend/Backend_Test.py deleted file mode 100644 index 2cf2664..0000000 --- a/Application_Folder/API_Backend/Backend_Test.py +++ /dev/null @@ -1,43 +0,0 @@ -import unittest -from Backend_API import app, db, User, Feedback - - -class FlaskTestCase (unittest.TestCase): - - def setUp(self): - self.app = app.test_client () - self.app_context = app.app_context () - self.app_context.push () - self.app.testing = True - db.create_all () - - def tearDown(self): - db.session.remove () - db.drop_all () - self.app_context.pop () - - def test_index(self): - response = self.app.get ('/') - self.assertEqual (response.status_code, 200) - - def test_register(self): - response = self.app.post ('/register', data=dict (email="test@test.com", user=True), follow_redirects=True) - user = User.query.filter_by (email="test@test.com").first () - self.assertIsNotNone (user) - self.assertEqual (response.status_code, 200) - - def test_feedback(self): - response = self.app.post ('/feedback', data=dict (email="test@test.com", feedback="This is a test feedback"), - follow_redirects=True) - feedback = Feedback.query.filter_by (user_email="test@test.com").first () - self.assertIsNotNone (feedback) - self.assertEqual (response.status_code, 200) - - def test_run_algorithm(self): - response = self.app.post ('/run_algorithm', json=dict (algorithm="Quantum Genetic Algorithm", num_cities=5), - follow_redirects=True) - self.assertEqual (response.status_code, 200) - - -if __name__ == '__main__': - unittest.main () diff --git a/Application_Folder/API_Backend/Flask_Test_Bed.py b/Application_Folder/API_Backend/Flask_Test_Bed.py deleted file mode 100644 index 49e4127..0000000 --- a/Application_Folder/API_Backend/Flask_Test_Bed.py +++ /dev/null @@ -1,63 +0,0 @@ -import unittest -from flask import Flask -from Flask_app import app, load_user, execute_algorithm -from unittest.mock import patch, MagicMock - - -class TestFlaskApp (unittest.TestCase): - def setUp(self): - self.app = app.test_client () - self.app.testing = True - - def test_successful_login(self): - with patch ('Flask_app.login_user') as mock_login: - response = self.app.post ('/login', data={'username': 'test_user'}) - mock_login.assert_called_once () - self.assertEqual (response.status_code, 302) - - def test_logout(self): - with patch ('Flask_app.logout_user') as mock_logout: - response = self.app.get ('/logout') - mock_logout.assert_called_once () - self.assertEqual (response.status_code, 302) - - def test_load_user(self): - user = load_user ('test_user') - self.assertEqual (user.id, 'test_user') - - def test_run_algorithm_with_invalid_algorithm(self): - response = self.app.post ('/run_algorithm', json={'algorithm': 'Invalid'}) - self.assertEqual (response.status_code, 400) - - def test_run_algorithm_with_valid_algorithm(self): - with patch ('Flask_app.execute_algorithm.delay') as mock_execute: - mock_execute.return_value = MagicMock (id='test_task_id') - response = self.app.post ('/run_algorithm', json={'algorithm': 'Quantum Genetic Algorithm'}) - mock_execute.assert_called_once () - self.assertEqual (response.status_code, 202) - self.assertEqual (response.get_json (), {'task_id': 'test_task_id'}) - - def test_check_task_with_pending_state(self): - with patch ('Flask_app.execute_algorithm.AsyncResult') as mock_result: - mock_result.return_value = MagicMock (state='PENDING') - response = self.app.get ('/check_task/test_task_id') - self.assertEqual (response.status_code, 200) - self.assertEqual (response.get_json (), {'state': 'PENDING', 'status': 'Pending...'}) - - def test_check_task_with_failure_state(self): - with patch ('Flask_app.execute_algorithm.AsyncResult') as mock_result: - mock_result.return_value = MagicMock (state='FAILURE', info='Test error') - response = self.app.get ('/check_task/test_task_id') - self.assertEqual (response.status_code, 200) - self.assertEqual (response.get_json (), {'state': 'FAILURE', 'status': 'Test error'}) - - def test_execute_algorithm(self): - with patch ('Flask_app.AmazonBraketClient') as mock_client: - mock_client.return_value.create_quantum_task.return_value = {'taskId': 'test_task_id'} - mock_client.return_value.get_quantum_task.return_value = {'status': 'COMPLETED'} - result = execute_algorithm (None, lambda: QuantumCircuit (2)) - self.assertEqual (result, {'status': 'COMPLETED'}) - - -if __name__ == '__main__': - unittest.main () diff --git a/Application_Folder/API_Backend/Flask_app.py b/Application_Folder/API_Backend/Flask_app.py deleted file mode 100644 index e23c689..0000000 --- a/Application_Folder/API_Backend/Flask_app.py +++ /dev/null @@ -1,65 +0,0 @@ -import logging -from flask import Flask, request, jsonify -import Quantum_Genetic_Algorithm -import base64 -from io import BytesIO - -app = Flask (__name__) - -# Set up logging -logging.basicConfig (level=logging.DEBUG) - - -@app.route ('/run_algorithm', methods=['POST']) -def run_algorithm_route(): - # Extract the algorithm name and the number of cities from the request - data = request.get_json () - logging.debug (f"Received data: {data}") # Log the request data - algorithm_name = data.get ('algorithm') - num_cities = data.get ('num_cities') - - if algorithm_name is None or num_cities is None: - logging.error(f"Missing data in request. Received: {data}") - return jsonify ({"error": f"Invalid request data. Received: {data}"}), 400 - - # Run the selected algorithm with the provided number of cities - try: - logging.debug(f"Running algorithm: {algorithm_name} with {num_cities} cities") - result = run_algorithm (algorithm_name, num_cities) - except ValueError as e: - logging.error(f"Error running algorithm: {e}") - return jsonify ({"error": "Invalid algorithm name"}), 400 - - # Process the results and prepare them for display - processed_results = process_results (result) - - # Log the processed results - logging.debug(f"Processed results: {processed_results}") - - # Return the processed results - return jsonify ({"result": processed_results}), 200 - - -def process_results(result): - # Convert the matplotlib figure to a PNG image - png_image = BytesIO () - result ['plot'].savefig (png_image, format='png') - - # Move to the beginning of the BytesIO object - png_image.seek (0) - - # Convert the PNG image to a base64 string - png_image_b64_string = base64.b64encode (png_image.read ()).decode ('utf-8') - - # Prepare the results for sending - processed_results = { - 'plot': png_image_b64_string, - 'counts': result ['counts'], - 'circuit': result ['circuit'], - } - - return processed_results - - -if __name__ == '__main__': - app.run (debug=False) diff --git a/Application_Folder/API_Backend/Stripe_API.py b/Application_Folder/API_Backend/Stripe_API.py deleted file mode 100644 index 080f31b..0000000 --- a/Application_Folder/API_Backend/Stripe_API.py +++ /dev/null @@ -1,27 +0,0 @@ -from flask import Flask, request, redirect, url_for -import stripe - -app = Flask (__name__) -stripe.api_key = 'API-KEY' - - -def create_customer(email, card): - return stripe.Customer.create (email=email, source=stripe.Token.create (card=card)) - - -def charge_customer(customer_id, amount, currency, description): - return stripe.Charge.create (customer=customer_id, amount=amount, currency=currency, description=description) - - -@app.route ('/pay/', methods=['POST']) -def pay(email): - card = { - 'number': request.form.get ('cardNumber'), - 'exp_month': request.form.get ('expiryDate').split ('/') [0], - 'exp_year': request.form.get ('expiryDate').split ('/') [1], - 'cvc': request.form.get ('cvv'), - 'name': request.form.get ('cardHolderName'), - } - customer = create_customer (email, card) - charge_customer (customer.id, 3000, 'usd', 'Service Fee') - return redirect (url_for ('index'))