Skip to content

Easy level Task #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions Sanjana-Easy/Task 1/Task1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import requests
from bs4 import BeautifulSoup
import csv
import json

# URL to fetch
url = "https://www.techadvisor.com/article/724318/best-smartphone.html"

# Perform the HTTP GET request
response = requests.get(url)

# Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(response.content, 'html.parser')

# Extract the phone names
phones = soup.find_all(class_='product-chart-item__title-wrapper--title')
phone_names = [h2.get_text(strip=True) for h2 in phones]

# Initialize lists for pros and cons
all_pros = []
all_cons = []

# Extract the pros and cons lists
pros_divs = soup.find_all('div', class_='product-chart-column')
for div in pros_divs:
title = div.find('p', class_='product-chart-subTitle').get_text(strip=True)
ul = div.find('ul', class_='product-pros-cons-list')
if title == 'Pros':
pros = [li.get_text(strip=True) for li in ul.find_all('li')]
all_pros.append(pros)
elif title == 'Cons':
cons = [li.get_text(strip=True) for li in ul.find_all('li')]
all_cons.append(cons)

# Combine the phone names, pros, and cons into a structured format
phones_data = []
for i in range(len(phone_names)):
phone_data = {
"phone": phone_names[i],
"pros": all_pros[i] if i < len(all_pros) else [],
"cons": all_cons[i] if i < len(all_cons) else []
}
phones_data.append(phone_data)

# Print the combined data
for phone in phones_data:
print(f"Phone: {phone['phone']}")
print("Pros:")
for pro in phone['pros']:
print(f" - {pro}")
print("Cons:")
for con in phone['cons']:
print(f" - {con}")
print('-------------------')

# Save the structured data to JSON
with open('phones_data.json', 'w', encoding='utf-8') as jsonfile:
json.dump(phones_data, jsonfile, indent=4)

print("Extracted data saved to phones_data.json")

# Save the structured data to CSV
with open('phones_data.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Phone", "Pros", "Cons"])
for phone in phones_data:
pros = "; ".join(phone["pros"])
cons = "; ".join(phone["cons"])
writer.writerow([phone["phone"], pros, cons])

print("Extracted data saved to phones_data.csv")
2 changes: 2 additions & 0 deletions Sanjana-Easy/Task 1/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
beautifulsoup4==4.12.3
Requests==2.32.3
44 changes: 44 additions & 0 deletions Sanjana-Easy/Task 2/Task2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import nltk
from nltk.chat.util import Chat, reflections
nltk.download('punkt')
#creating questions and answers
s=[
[
r"Hello|Hi|Hey",
["Hello,How are you?"]
],
[
r"I'm fine",
["Glad to hear that,how can i help you?"]
],
[
r"What is your name?",
["well they haven't kept me a name but they call me as a chatbot ,if you wish u can give me a name"]
],
[
r"Actually I'm feeling a bit lonely|sad|angry|irritated today",
["sorry to hear about that.I'm here for you! Would you like to share about what's on your mind?"]
],
[
r"Yeah well that was a big problem, i can't get rid off it",
["I'm really sorry to hear about that you are going through a tough time.It's okay to feel overwhelmed by problems sometimes but dont worry that you are not at all alone!"]
],
[
r"Can you try to say something lie a joke or entertain me?",
["Sure,I can definitely change your mood!So,how about this:Why maths book look sad?Because it had any problems!I hope that this brought a little smile to your face!"]
],
[
r"Thanks a lot for helping me",
["You're Welcome!I'm always here for you at anytime,if you need a chat or joke or anything,feel free to ask me"]
],
[
r"Exit",
["It was my pleasure to help you.Please,come again!"]
]
]
#default message for starting chat
print("Please,write anything to start the chat")
#create a chat instance
chatbot=Chat(s)
#start conversation
chatbot.converse()
1 change: 1 addition & 0 deletions Sanjana-Easy/Task 2/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nltk==3.8.1
1 change: 1 addition & 0 deletions Sanjana-Easy/Task 3/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web:gunicorn app:app
189 changes: 189 additions & 0 deletions Sanjana-Easy/Task 3/Task3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@

# app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager , UserMixin
from flask_migrate import Migrate
from datetime import datetime






app = Flask(__name__)
app.app_context().push()
app.config['SECRET_KEY'] = 'your_secret_key_here' # Change this to a random secret key
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db' # Database file will be created in the project folder
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'


migrate = Migrate(app, db)


class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=True)
due_date = db.Column(db.DateTime, default=datetime.utcnow)
completed = db.Column(db.Boolean, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', name='fk_task_user'), nullable=False)

class User(UserMixin , db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(100), nullable=False)


from flask import redirect, url_for, request, flash
from flask_login import login_user, login_required, logout_user, current_user

from flask import render_template, redirect, url_for, request, flash
from flask_login import login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash



# Implement the Logic

@app.route('/', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

existing_user = User.query.filter_by(username=username).first()
if existing_user:
flash('Username already exists. Please choose a different username.', 'danger')
return redirect(url_for('register'))

new_user = User(username=username, password=generate_password_hash(password, method='pbkdf2:sha256'))
db.session.add(new_user)
db.session.commit()

flash('Registration successful. You can now log in.', 'success')
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['username']
password = request.form['password']

user = User.query.filter_by(username=username).first()

if user and check_password_hash(user.password, password):
login_user(user)
flash('Logged in successfully!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password. Please try again.', 'danger')

return render_template('login.html')


@app.route('/dashboard')
@login_required
def dashboard():
tasks = Task.query.filter_by(user_id=current_user.id).all()
return render_template('dashboard.html', tasks=tasks)


@app.route('/add_task', methods=['GET', 'POST'])
@login_required
def add_task():
if request.method == 'POST':
title = request.form['title']
description = request.form['description']
due_date_str = request.form['due_date']

due_date = datetime.strptime(due_date_str, '%Y-%m-%d')

new_task = Task(title=title, description=description, due_date=due_date, user_id=current_user.id)
db.session.add(new_task)
db.session.commit()

flash('Task added successfully!', 'success')
return redirect(url_for('dashboard'))

return render_template('add_task.html')


@app.route('/edit_task/<int:task_id>', methods=['GET', 'POST'])
@login_required
def edit_task(task_id):
task = Task.query.get_or_404(task_id)

if task.user_id != current_user.id:
flash('You are not authorized to edit this task.', 'danger')
return redirect(url_for('dashboard'))

if request.method == 'POST':
task.title = request.form['title']
task.description = request.form['description']
task.due_date_str = request.form['due_date']
task.due_date = datetime.strptime(task.due_date_str, '%Y-%m-%d')




db.session.commit()

flash('Task updated successfully!', 'success')
return redirect(url_for('dashboard'))

return render_template('edit_task.html', task=task)


@app.route('/delete_task/<int:task_id>', methods=['POST'])
@login_required
def delete_task(task_id):
task = Task.query.get_or_404(task_id)

if task.user_id != current_user.id:
flash('You are not authorized to delete this task.', 'danger')
return redirect(url_for('dashboard'))

db.session.delete(task)
db.session.commit()

flash('Task deleted successfully!', 'success')
return redirect(url_for('dashboard'))



from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

#Implement Authentication and Authorization

# Create a user loader function required by flask_login
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))





@login_manager.unauthorized_handler
def unauthorized():
flash('You must be logged in to access that page.', 'danger')
return redirect(url_for('login'))

@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged out successfully.', 'success')
return redirect(url_for('login'))


if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Binary file not shown.
Binary file added Sanjana-Easy/Task 3/instance/tasks.db
Binary file not shown.
1 change: 1 addition & 0 deletions Sanjana-Easy/Task 3/migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
Binary file not shown.
50 changes: 50 additions & 0 deletions Sanjana-Easy/Task 3/migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Loading