PYTHON

Building My First Python Web App with ChatGPT

After waiting for a long time, I finally used ChatGPT to help me create a webpage that asks for user inputs and creates a waste hierarchy

Sourabh Jain
Nerd For Tech

--

Photo by Emiliano Vittoriosi on Unsplash

It had been a few weeks since I coded anything in Python since I was busy with my research work. I know it is wrong to have any gaps in your coding habits but still, I didn’t need anything to code until that day. I was working on my circular economy research and I needed to customize the waste hierarchy. However, I couldn’t find any online generator, and drawing it in a PowerPoint or other drawing tool (such as this one) seemed tedious and boring. I had an epiphany: why not create my own generator? Encouraged by a suggestion from my friend, I began to harness the capabilities of ChatGPT for Python coding.

At first, I tried the free version, but I encountered numerous errors and inefficiencies. My friend then recommended the premium version, ChatGPT4. The difference in response quality was immediate. ChatGPT4 proved to be more accurate in generating codes. Although the subscription comes at a higher price, it’s comparable to what I currently pay for my gym membership. I’m optimistic that both investments will prove worthwhile in the long run.

Did I create a website or a web app?

A website and web apps have become so common that they have been used interchangeably. In fact, I also used them interchangeably. But I didn’t realize there was a difference between the two until I wanted to create my own web app, which I initially thought was a website. While the line between the two has been blurred over the years, there are still some fundamental differences.

Both differ in purpose & interaction, design & responsiveness, development complexity, and updates & maintenance. A website’s purpose is to mainly present information with some styles, so a website is often static (or updated less frequently), so the design focus is more on aesthetics and requires less complexity to develop. It has limited interaction with users, who mainly browse the information. Typical examples are corporate or government websites and blogs. A web app, on the other hand, focuses on providing specific functions through user interaction, so its design is more complex. It requires user authentication and dynamic database integration, which means its design is more complex and requires frequent updates for upkeep.

Since my goal was to create an image based on user inputs rather than presenting some information as explained below, I would categorize my project as a web app.

My objective

My primary goal was to generate a waste hierarchy tailored to the waste management options relevant to my research. While the core concept of the waste hierarchy remains consistent, its structure is customizable and open to interpretation. Individuals can design and present a waste hierarchy based on their specific requirements. For instance, while some hierarchies might feature just four levels — such as prevention, reuse, composting, and landfilling — others might span 10–12 levels or more. Hence, I was in pursuit of a tool that would allow me to craft various iterations of the hierarchy as needed.

Code and output

With ChatGPT’s assistance, I crafted several scripts. One script contains Flask app code that assembles the webpage, inclusive of the user interface. Below is a snippet of the Python code. The second script, which I haven’t displayed here, renders a standard waste recovery hierarchy either in 2D or 3D pyramid shape based on user inputs. Users can submit a list of waste hierarchy levels (arranged from the highest to the lowest priority), and the script will generate the corresponding hierarchy. Additional customizable features available for users include the orientation of the hierarchy (whether it’s an upright or inverted pyramid) and the choice between a colored or without colors display.

from flask import Flask, render_template, request, send_file
from io import BytesIO
from waste_hierarchy_pyramid import plot_hierarchy_pyramid_2d, plot_hierarchy_pyramid_3d

app = Flask(__name__)


@app.route('/')
def landing_page():
return render_template('landing.html')


@app.route('/waste-hierarchy', methods=['GET', 'POST'])
def waste_hierarhcy():

if request.method == 'POST':

# Receive data from the form
levels_text = request.form.get('levels') # Get the string from textarea
levels = [level.strip() for level in levels_text.split(',') if level] # Split by comma and remove any whitespace


# customization inputs for hierarchy
display = request.form.get('display', 'true')
with_colors = request.form.get('color', 'true')
mode = request.form.get('mode', '2d')

title = request.form.get('title').strip()

if mode=='2d':
fig = plot_hierarchy_pyramid_2d(levels = levels, display = display, with_colors = with_colors,
title = title)
else:
fig = plot_hierarchy_pyramid_3d(levels = levels, display = display, with_colors = with_colors,
title = title)

img = BytesIO()

# Check desired file format (assuming you have an input field named "format" with options "jpg" and "pdf")
file_format = request.form.get('format', 'jpg')

if file_format == 'jpg':
fig.savefig(img, format='jpg', bbox_inches='tight')
img.seek(0)
return send_file(img, mimetype='image/jpeg', download_name='hierarchy.jpg', as_attachment=True)

elif file_format == 'pdf':
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages(img)
pp.savefig(fig, bbox_inches='tight')
pp.close()
img.seek(0)
return send_file(img, mimetype='application/pdf', download_name='hierarchy.pdf', as_attachment=True)


return render_template('waste_hierarchy.html') # This is your main page where users input properties



@app.route('/lca-system-boundary')
def lca_system_boundary():
# Placeholder for now. Later, you'll fill this with the actual logic and rendering.
return "Coming Soon!"


@app.route('/esg-score')
def esg_score():
# Placeholder for now. Later, you'll fill this with the actual logic and rendering.
return "Coming Soon!"

@app.route('/lca-terminology')
def lca_terminology():
# Placeholder for now. Later, you'll fill this with the actual logic and rendering.
return "Coming Soon!"


@app.route('/financial-stats')
def financial_stats():
# Placeholder for now. Later, you'll fill this with the actual logic and rendering.
return "Coming Soon!"



if __name__ == '__main__':
app.run()

Results

Welcome to the landing webpage of my website, currently hosted on Pythonanywhere.com. While it is still under development stages and the the hierarchy generator is the only active feature. Here is a sample hierarchy it generates. Wonderful (at least to me)!

A sample waste hierarchy

The tool largely meets my initial expectations, but it’s not without its shortcomings. The 3D version misses out on certain features, such as the inverse display, and aesthetic elements. Moreover, inputting fewer levels (like 2–3) can skew the visualization, primarily because font sizes and certain features are hard-coded rather than adjusted based on the overall size and shape of the hierarchy. Nonetheless, I’m committed to refining the code and enhancing its capabilities. The pursuit of continuous and consistent improvement is paramount and my life’s mantra — just look at Toyota’s consistent production of reliable vehicles.

The pursuit of continuous and consistent improvement is paramount and my life’s mantra

Some lessons

ChatGPT is definitely a useful tool to greatly improves productivity. However, it requires some caution.

  1. Be specific with instructions: I often struggle to give clear instructions. Using ChatGPT, I hope to practice and hone this skill. That said, I’ve come to realize the importance of being precise when directing ChatGPT. In numerous instances, if instructions were not explicit enough, ChatGPT produced unexpected results. There were moments it generated multiple variations of code, or even something entirely different from what was initially requested. It was quite frustrating. In fact, sometimes, I felt that I could have coded something myself, which would have been easier and faster than asking ChatGPT’s help multiple times (e.g., generating 3-D version of waste hierarchy). Maybe, given the inherent challenges of conveying visual ideas through text, it’s tougher to be specific. If only there was an option to upload a PDF or an image to better guide ChatGPT.
  2. Knowledge of programming is necessary. A foundational understanding of programming is essential. This might sound obvious, but it holds true when working with ChatGPT. While anyone can use it to generate code and code anything they want, proficiency in that programming language can greatly improve trouble shooting skills and hence productivity. Otherwise, as happened in my case, unfamiliarity with certain aspects of Python and other languages led to numerous iterations for even minor tweaks, especially in the HTML/CSS aspects. Sometimes ChatGPT gave something to fix my concern and I didn’t know what or why that didn’t work, and I would ask again multiple times. Sometimes, ChatGPT offered solutions to my queries. But due to my lack of understanding about what worked and why something didn’t work, I would ask again multiple times. Had I understood the code better, I would have fixed it myself without wasting too much time. Anyway, everything is part of a learning process.

Nevertheless, I admire ChatGPT’s unwavering patience and politeness LOL .If ChatGPT was a real person, they would definitely have said “Oh you stupid f**k. Why can’t you do such a silly thing in one go? Why can’t you write one or two lines of codes yourself if you call yourself programmer. Do dumb lazy f**k.”

I admire ChatGPT’s patience and politeness LOL .If ChatGPT was a real person, they would definitely have said “Oh you stupid f**k. Why can’t you do such a silly thing in one go? Why can’t you write one or two lines yourself if you call yourself programmer. Do dumb lazy f**k.”

Future

While my initial objective was simply to create a waste hierarchy, I later realized that I shouldn’t stop there. There’s so much more I can do to create different tools for both myself and others. Thus, I see this as just a small part of a much larger project I have in mind. In the future, I plan to incorporate simulation tools to help users understand ecosystem functioning and concepts related to sustainability.

Stay tuned for more updates.

--

--

Sourabh Jain
Nerd For Tech

Postdoctoral scholar who applies systems thinking to model circular economy running on 100% renewable energy systems and zero waste.