Passion Project Review
Overall I feel as though we ran into a lot of problems during our passion project it ended up working out in the end. Our team struggled with communication in the beggining but towards the end we ended up collaborating super well at the end and getting the work done in the nicke of time.
With that being said I want to share some of the key commits with you in this presentation
number 1
from __init__ import db
# Define the "book" model
class Book(db.Model):
# Define the table name in the database
__tablename__ = "Book"
# This defines all of the attributes of a book that we will display
id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.String, nullable=False)
year = db.Column(db.String, nullable=False)
price = db.Column(db.String, nullable=False)
genre = db.Column(db.String, nullable=False)
summary = db.Column(db.String, nullable=False)
# Constructor to initialize a new book object
def __init__(self, author, year, price, genre, summary):
self.author = author
self.year = year
self.price = price
self.genre = genre
self.summary = summary
def to_dict(self):
return {"author": self.author, "year": self.year, "price": self.price, "genre": self.genre, "summary": self.summary}
# Create method to let users add a song to the DB
def create(self):
try:
db.session.add(self) # add prepares to persist object to table
db.session.commit() # SQLAlchemy requires a manual commit
return self
except:
db.session.remove() # remove object from table if invalid
return None
# Method to return book details for API response
def read(self):
return {
"id": self.id,
"author": self.author,
"year": self.year,
"price": self.price,
"genre": self.genre,
"summary": self.summary
}
def initBooks():
TheGreatGatsby = Book(author="F. Scott Fitzgerald", year="1925", price="$2.36", genre="Realism", summary="'The Great Gatsby' is a classic novel written by F. Scott Fitzgerald. It is set in the 1920s and tells the story of Jay Gatsby, a mysterious and wealthy man who hosts extravagant parties in the hope of rekindling a past romance with Daisy Buchanan. The novel is narrated by Nick Carraway, who becomes Gatsby's neighbor and provides an outsider's perspective on the events. The story explores themes of the American Dream, wealth, love, and moral decay. Tragically, Gatsby's pursuit of the American Dream ends in his downfall and death, illustrating the hollowness of the Jazz Age's excesses."); db.session.add(TheGreatGatsby)
DreamsFromMyFather = Book(author="Barack Obama", year="1995", price="$10.73", genre="Biography", summary="'Dreams from My Father' is a memoir written by Barack Obama. In the book, Obama reflects on his early life and the complex journey of identity and belonging. He discusses his multicultural background, growing up as the son of a Kenyan father and a white American mother, and his search for a sense of self and purpose. The memoir delves into his experiences as a community organizer in Chicago and his travels to Kenya, where he reconnects with his African roots and grapples with the legacy of his absent father. Throughout the book, Obama explores the themes of race, identity, and the pursuit of a meaningful life, making it a compelling narrative that provides insight into his personal and political development."); db.session.add(DreamsFromMyFather)
TheGrapsofWrath = Book(author="John Steinbeck", year="1939", price="$12.29", genre="Historical Fiction", summary="'The Grapes of Wrath' is a novel by John Steinbeck that portrays the struggles of the Joad family during the Great Depression. Displaced from their Oklahoma farm due to the Dust Bowl, they embark on a journey to California in search of a better life. The novel explores themes of poverty, exploitation, and the resilience of the human spirit as they face adversity and discrimination as migrant workers. The Joads and other characters they encounter on their journey reveal the harsh realities of the time, illustrating the economic and social injustices faced by the working class. The novel concludes on a note of hope as the Joads, despite hardships, demonstrate the strength of family bonds and the enduring human quest for dignity and survival."); db.session.add(TheGrapsofWrath)
ToKillAMockingbird = Book(author="Harper Lee", year="1960", price="$8.89", genre="Southern Gothic Fiction", summary="'To Kill a Mockingbird' is a classic novel by Harper Lee set in the racially segregated American South during the 1930s. The story is narrated by Scout Finch, a young girl growing up in the small town of Maycomb, Alabama. Scout's father, Atticus Finch, is a lawyer who is tasked with defending Tom Robinson, a black man falsely accused of raping a white woman. The novel explores themes of racial injustice, moral growth, and empathy as Scout, her brother Jem, and their friend Dill, come of age in the face of prejudice and ignorance. Through the eyes of the children, the book exposes the deep-seated racism and social inequality prevalent in the community and challenges the reader to confront the harsh realities of the era."); db.session.add(ToKillAMockingbird)
Farenheit451 = Book(author="Ray Bradbury", year="1953", price="$8.45", genre="Dystopia/Sci-Fi", summary="'Fahrenheit 451' by Ray Bradbury is a dystopian novel set in a future society where books are banned, and the job of the firemen is to burn any books they find. The story follows Guy Montag, a fireman who begins to question the status quo and the suppression of knowledge. He meets a young woman named Clarisse, who inspires him to think critically about the world around him. Montag becomes involved with a group of rebels who seek to preserve and share knowledge through memorization. The novel explores themes of censorship, conformity, and the importance of critical thinking, highlighting the power of literature and the dangers of a society that suppresses intellectual freedom."); db.session.add(Farenheit451)
# HeartofDarkness = Book(author="Joseph Conrad", year="1899", price="$3.79", genre="Novella", summary="Heart of Darkness by Joseph Conrad is a novella that delves into the complexities of colonialism and human nature. The story follows Charles Marlow, a British sailor, as he travels up the Congo River in Africa to meet the enigmatic ivory trader Kurtz. Marlow's journey reveals the brutality and moral degradation that can occur in the heart of the African jungle, as European colonial powers exploit and subjugate the native population. The novella explores themes of darkness, both in the literal sense of the jungle and the metaphorical sense of the human soul. Kurtz, who has descended into madness and becomes a symbol of the corrupting influence of power, utters the famous line, "The horror! The horror!" The novella raises questions about the consequences of imperialism and the depths to which individuals can descend when isolated from the constraints of civilization."); db.session.add(HeartofDarkness)
# MobyDick = Book(author="Herman Melville", year="1851", price="$11.99", genre="Historical fiction, Adventure", summary="Moby-Dick by Herman Melville is an epic novel that follows the journey of Captain Ahab and his crew aboard the whaling ship Pequod. The central focus of the story is Ahab's relentless quest for revenge against a giant white whale named Moby-Dick, who had previously bitten off Ahab's leg. As the crew embarks on this perilous journey, they encounter various adventures and challenges, including other whaling ships, storms, and personal conflicts."); db.session.add(MobyDick)
# TheShining = Book(author="Stephen King", year="1977", price="$14.46", genre="Horror", summary="The Shining is a psychological horror novel written by Stephen King. The story revolves around the Torrance family, consisting of Jack, Wendy, and their young son Danny, who become the winter caretakers of the remote and haunted Overlook Hotel in Colorado. Jack, a struggling writer with a history of alcoholism and violence, is slowly consumed by the malevolent supernatural forces that haunt the hotel, while Danny possesses psychic abilities known as "the shining," which make him sensitive to the hotel's dark secrets. As the winter progresses, the family becomes increasingly isolated, and the hotel's sinister history and supernatural entities begin to exert their influence on Jack and Danny. The novel explores themes of isolation, addiction, and the destructive power of the human psyche, leading to a terrifying climax as the family confronts the hotel's evil spirits."); db.session.add(TheShining)
# AtlasShrugged = Book(author="Ayn Rand", year="1957", price="$15.29", genre="Sci-Fi", summary="Atlas Shrugged by Ayn Rand is a philosophical novel set in a dystopian future where the United States is on the brink of economic collapse. The story revolves around a group of industrialists, inventors, and thinkers who decide to go on strike, withdrawing their talents and innovations from a society they see as increasingly oppressive and collectivist. The novel explores the consequences of their actions on the world, including the government's attempts to control the economy and the decline of civilization. The central character, Dagny Taggart, works to understand the reasons behind the disappearance of these individuals and the collapse of their world. "Atlas Shrugged" is a work of Objectivist philosophy, promoting individualism, rational self-interest, and laissez-faire capitalism as core principles in Rand's philosophical and political ideology."); db.session.add(AtlasShrugged)
# # TheAdventuresofTomSawyer = Book(author="Mark Twain", year="1876", price="$3.95", genre="Sci-Fi", summary="The Adventures of Tom Sawyer by Mark Twain follows the escapades of a young, mischievous boy named Tom Sawyer in the fictional town of St. Petersburg, Missouri. Tom, often in trouble, convinces his friends to whitewash a fence for him, cunningly making it seem like a thrilling task. He experiences puppy love and becomes infatuated with his classmate, Becky Thatcher. Tom and his friend Huckleberry Finn witness a murder, and the real culprits, Injun Joe and Muff Potter, frame Muff for the crime. Tom's adventures lead him to a treasure hunt, which ultimately reveals the true nature of Injun Joe and brings him into the spotlight as a hero in the town. Twain's novel explores themes of youth, adventure, and societal norms while capturing the essence of boyhood in a 19th-century American setting."); db.session.add(TheAdventuresofTomSawyer)
# # AFarewellToArms = Book(author="Ernest Hemingway", year="1929", price="$10.39", genre="Historical fiction", summary="A Farewell to Arms by Ernest Hemingway is a novel set during World War I and follows the experiences of an American ambulance driver named Frederick Henry. Henry falls in love with a British nurse named Catherine Barkley while stationed in Italy. Their relationship deepens, and they decide to escape the war's chaos and elope to Switzerland. Tragedy strikes as Catherine dies during childbirth, leaving Henry devastated and alone. The novel explores the devastating impact of war on personal lives, the fleeting nature of happiness, and the harsh realities of loss and love."); db.session.add(AFarewellToArms)
# TheBellJar = Book(author="Sylvia Plath", year="1963", price="$11.51", genre="Autobiography", summary="The Bell Jar by Sylvia Plath is a semi-autobiographical novel that tells the story of Esther Greenwood, a young woman living in New York City in the 1950s. Esther is a talented writer who secures an internship at a prestigious magazine but finds herself struggling with mental health issues. As she grapples with the societal pressures and expectations placed upon women of her time, she descends into a deep depression and ultimately attempts suicide. Esther is then committed to a mental institution, where she undergoes electroconvulsive therapy. The novel provides a poignant and introspective exploration of mental illness, the constraints placed on women in the mid-20th century, and the search for identity and self-fulfillment. "The Bell Jar" is a powerful and semi-autobiographical work that delves into the author's own struggles with mental health and the societal norms of her era."); db.session.add(TheBellJar)
# Catch22 = Book(author="Joseph Heller", year="1961", price="$10.80", genre="Satire", summary="Catch-22 by Joseph Heller is a satirical novel set during World War II, focusing on the absurdity and bureaucracy of the military. The story follows Captain John Yossarian, a U.S. Army Air Forces bombardier, who is trying to maintain his sanity while navigating a surreal and illogical military system. The novel introduces the concept of a "catch-22," a paradoxical situation where airmen who claim insanity to avoid dangerous missions are considered sane, but wanting to avoid such missions demonstrates sanity, thus they are required to fly. The book explores the horrors of war, the dehumanizing effects of bureaucracy, and the absurdity of military logic. Through dark humor and absurdity, it offers a scathing critique of war and the institutions that perpetuate it."); db.session.add(Catch22)
# TheCatcherInTheRye = Book(author="J.D. Salinger", year="1951", price="$7.38", genre="Young Adult Fiction", summary="The Catcher in the Rye by J.D. Salinger is a classic novel narrated by Holden Caulfield, a disenchanted and alienated teenager. After getting expelled from an elite prep school, Holden decides to run away to New York City. He spends a few days wandering the city, meeting people, and contemplating his life. Throughout the novel, Holden expresses his deep disillusionment with the adult world, his fear of growing up, and his desire to protect the innocence of children, symbolized by his fantasy of being a "catcher in the rye" who saves children from falling into the complexities of adulthood. The novel explores themes of isolation, loss, and the authenticity of human connection, and it has become a coming-of-age classic in American literature."); db.session.add(TheCatcherInTheRye)
# OfMiceAndMen = Book(author="John Steinbeck", year="1937", price="$6.10", genre="Tragedy", summary="Of Mice and Men by John Steinbeck is a novella set during the Great Depression in California. It tells the story of two displaced ranch workers, George and Lennie, who have dreams of owning their own land. Lennie has a mental disability and is dependent on George for guidance and protection. They find work on a ranch, but their dream is constantly thwarted by the challenges they face and the harsh realities of the world. Ultimately, the story tragically concludes with a devastating event that forces George to make a difficult and heartbreaking decision."); db.session.add(OfMiceAndMen)
# OnTheRoad = Book(author="Jack Kerouac", year="1957", price="$7.97", genre="Roman à clef", summary="On the Road by Jack Kerouac is a novel that captures the Beat Generation's spirit in the 1950s. The story follows Sal Paradise, a young writer based on Kerouac himself, as he embarks on a series of road trips across the United States with his friend Dean Moriarty, a charismatic and reckless figure based on real-life Beat poet Neal Cassady. They travel in search of adventure, freedom, and self-discovery, often living a life of hedonism, substance abuse, and constant movement. The novel explores the themes of rebellion against societal norms, the pursuit of personal authenticity, and the transient nature of life. "On the Road" is considered a seminal work in American literature, reflecting the countercultural and bohemian ideals of the Beat Generation."); db.session.add(OnTheRoad)
# TheAgeofInnocence = Book(author="Edith Wharton", year="1920", price="$7.09", genre="Romance", summary="The Age of Innocence is a novel by Edith Wharton set in the high society of 1870s New York. The story revolves around Newland Archer, a young lawyer from a wealthy and privileged background, who becomes engaged to May Welland, a proper and conventional woman. However, their world is disrupted when May's cousin, Countess Ellen Olenska, returns to New York, having fled a troubled marriage in Europe. Newland finds himself torn between his growing infatuation with Ellen and his obligations to marry May. The novel explores themes of societal expectations, personal desire, and the constraints of upper-class society in the Gilded Age. Wharton's work offers a subtle critique of the rigid norms and expectations of the time, and it examines the sacrifices and compromises individuals make in the name of societal conformity."); db.session.add(TheAgeofInnocence)
# Walden = Book(author="Henry David Thoreau", year="1854", price="$9.99", genre="Autobiography", summary="Walden by Henry David Thoreau is a transcendentalist work that recounts the author's experiment in simple living at Walden Pond, near Concord, Massachusetts. Thoreau lived in a small cabin for two years, two months, and two days, seeking to simplify his life and find a deeper connection to nature and self. He reflects on the importance of self-reliance, individualism, and the value of a life of purposeful simplicity. Thoreau's narrative is also a critique of materialism and the loss of meaningful connection with nature in the face of industrialization and urbanization. "Walden" encourages readers to live deliberately, to question societal norms, and to pursue a life that is in harmony with the natural world."); db.session.add(Walden)
# InvisibleMan = Book(author="H. G. Wells", year="1897", price="$8.99", genre="Sci-Fi", summary="The Invisible Man is a novel written by H.G. Wells. It follows the story of a scientist named Griffin, who discovers a way to become invisible but struggles to reverse the process. As he becomes more invisible, he becomes increasingly unhinged and begins a reign of terror, using his newfound power for criminal activities. The novel explores themes of science and morality, as well as the consequences of unchecked power and the isolation of invisibility. In the end, Griffin's invisibility leads to his tragic demise, highlighting the dangers of scientific experimentation without ethical boundaries."); db.session.add(InvisibleMan)
# Lolita = Book(author="Vladimir Nabokov", year="1955", price="$14.28", genre="Erotic literature", summary="Lolita by Vladimir Nabokov is a controversial and complex novel narrated by Humbert Humbert, a highly intelligent and morally reprehensible man. The story revolves around Humbert's infatuation and obsession with a 12-year-old girl named Dolores Haze, whom he nicknames "Lolita." Humbert becomes her stepfather and embarks on a cross-country journey, engaging in a disturbing and illegal relationship with her. The novel explores themes of obsession, manipulation, and the dark depths of human desire. It is known for its lyrical prose and unreliable narrator, making it a provocative and thought-provoking work of literature that raises uncomfortable questions about morality and the human psyche."); db.session.add(Lolita)
# Leavesofgrass = Book(author="Walt Whitman", year="1855", price="$8.99", genre="Poetry", summary="Leaves of Grass is a collection of poetry by American poet Walt Whitman. It's notable for its celebration of the individual, nature, and the democratic spirit. The poems are characterized by their free verse, sensual language, and themes of optimism and transcendentalism. Whitman often sings the praises of the common people, celebrates the beauty of the human body, and seeks to capture the essence of the American experience. The work is a reflection of Whitman's belief in the unity of all things and his desire to convey the vastness and diversity of the American landscape and its people."); db.session.add(Leavesofgrass)
db.session.commit()
This was the Commit that stored the bulk of our information while also allowing our api to call for the code neccisarry
Number 2
import openai
from flask import Flask, request, jsonify
app = Flask(__name__)
# Replace with your OpenAI API key
api_key = 'API-Key'
# Configure OpenAI with your API key
openai.api_key = api_key
@app.route('/extend_text', methods=['POST'])
def extend_text():
input_text = request.json.get('text')
if not input_text:
return jsonify({"error": "Text input is required."}), 400
try:
response = openai.Completion.create(
engine="davinci",
prompt=input_text,
max_tokens=100, # Adjust this as per your requirement
stop=None,
)
extended_text = response.choices[0].text
return jsonify({"extended_text": extended_text})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run()
While this code didn’t get used in the final prject I still feel this is important to show the amount of work I put into this project as for this I had to spend hours wrestling with the chat gpt api and I am very proud of the work I did on this as it was the center point of our project for a long time.
Number 3
from flask import Blueprint, jsonify, request
from flask_restful import Api, Resource, reqparse
from __init__ import db
from model.books import Book # Import the book model
import requests
# Create a Blueprint for the book API
book_api = Blueprint('book_api', __name__, url_prefix='/api/book')
# Create the API instance
api = Api(book_api)
class BookAPI:
class _Create(Resource):
def post(self):
# Get request JSON data
body = request.get_json()
# Extract Book information
author = body.get('author')
year = body.get('year')
price = body.get('price')
genre = body.get('genre')
summary = body.get('summary')
# Create a new Book object
book_obj = Book(author=author, year=year, price=price, genre=genre, summary=summary)
#2: Key Code block to add Book to database
# create Book in database
book = book_obj.create()
# success returns json of book
if book:
return jsonify(book.read())
# failure returns error
return {'message': f'Invalid input, correct fields should be author, year, price, genre, and summary'}, 400
class _Read(Resource):
def get(self):
# Retrieve all Books from the database
Books = Book.query.all()
json_ready = [book.to_dict() for book in Books]
# Return the JSON response
return jsonify(json_ready)
# building RESTapi resources/interfaces, these routes are added to Web Server
api.add_resource(_Create, '/create')
api.add_resource(_Read, '/')
This is the code stored as our api which allows us to take the data from commit 1 and turn it into a book that can be pulled by the frontend. This works by identifying the different aspects of the data such as author name, year, genre, etc.
Overall I am proud of our passion project and my part in it.