0% found this document useful (0 votes)
13 views

CS Project

Uploaded by

Shinchu Gamerz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CS Project

Uploaded by

Shinchu Gamerz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction

In today’s world, technology simplifies our daily tasks by providing


tools that enhance productivity and convenience. This project,
developed by Geetansh Jangid, is a multifunctional program
designed to cater to diverse user needs, from generating images and
analyzing weather data to editing CSV files and plotting graphs.

The primary goal of this project is to integrate multiple functionalities


into a single platform, allowing users to interact with tools like a
chatbot, unit converter, graph plotter, and more, without needing
separate applications. The project highlights modular programming,
where each feature is encapsulated within its own module for ease of
maintenance and scalability.

Whether you are a student looking for a chatbot for quick


programming help, a researcher analyzing data trends, or an
everyday user managing files and passwords, this program offers a
solution tailored to your requirements. With a user-friendly interface
and an intuitive dashboard, it ensures that users of all skill levels can
navigate and utilize its features effortlessly.

#SnakesInCode
Code and Features
The project is modular and consists of multiple scripts, each
responsible for specific functionalities. The main script acts as the
entry point, orchestrating the interaction between these modules.
Below is a detailed explanation of each part of the code:

1. Main Script
File Name: main.py

The main script serves as the dashboard for the program, providing
users with a menu to select the desired feature.
Each menu option calls a specific function from its respective
module.

Code:
import sys
import unit_converter
import chatbot
import image_generator
import graph_plotter
import csv_editor
import file_organiser
import password_generator
import file_organiser
import weather

def dashboard():
print("\n=== Dashboard ===")
print("1. Image Generator")
print("2. Chatbot")

#SnakesInCode
print("3. Unit Converter")
print("4. Graph Plotter")
print("5. CSV Editor")
print("6. File Organizer")
print("7. Password Generator")
print("8. Weather")
print("9. Exit")

def image_generator_o():
image_generator.image_generator()

def chatbot_menu():
print("\n[Chatbot] - Type 'exit' to quit the
chatbot.")
while True:
user_input = input("\nYou: ")
if user_input.lower() == "exit":
print("Exiting chatbot.")
break
response = chatbot.start_chatbot(user_input)
print(f"Chatbot: {response}")

def unit_converter_menu():
unit_converter.unit_converter()

def graph_plotter_menu():
graph_plotter.graph_plotter()

def csv_editor_menu():
csv_editor.csv_editor()

def file_organizer_menu():
file_organiser.file_organizer()

def password_generator_menu():

#SnakesInCode
password_generator.password_generator()

def weather_menu():
weather.weather()

def main():
while True:
dashboard()
choice = input("\nEnter your choice: ")

if choice == '1':
image_generator_o()
elif choice == '2':
chatbot_menu()
elif choice == '3':
unit_converter_menu()
elif choice == '4':
graph_plotter_menu()
elif choice == '5':
csv_editor_menu()
sys.exit()
elif choice == '7':
password_generator.password_generator()
elif choice == '6':
file_organizer.file_organizer()
elif choice == '8':
weather.weather_checker()
elif choice == '9':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

#SnakesInCode
2. Chatbot
File Name: chatbot.py

Implements a chatbot using Google Generative AI to assist with


programming-related queries.
Configures the API key and allows interactive conversations.

Code:
import os
from dotenv import load_dotenv, dotenv_values
load_dotenv()
import google.generativeai as genai

genai.configure(api_key="AIzaSyCbJjktthW0CB2kgneplbJ75EhO
OobZEUw")

def start_chatbot(user_input):
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
system_instruction="You are a chatbot created by
Geetansh Jangid to assist Computer Science students.
Provide helpful and accurate information on programming
concepts, languages (specify languages here, e.g.,

#SnakesInCode
Python, Java, C++), theoretical computer science topics,
and debugging, but avoid writing full programs or
providing answers that violate academic integrity.
Respond in a clear, concise manner, using diagrams or
code as requested, and always cite sources where
appropriate. Your knowledge is limited, so accept
feedback gracefully and learn from user corrections.
Focus on explaining concepts and providing code snippets
to aid understanding, not completing assignments.",
)

chat_session = model.start_chat(
history=[
{"role": "user", "parts": ["Hello"]},
{"role": "model", "parts": ["Hello! How can I
help you today? I'm here to assist with your Computer
Science questions."]},
]
)

response = chat_session.send_message(user_input)

return response.text

#SnakesInCode
3. Image Generator
File Name: image_generator.py

Uses the Pollinations AI API to generate images based on user


prompts.
Provides an option to display and download the generated image.

Code:
import requests
from PIL import Image, ImageTk
import io
import tkinter as tk
from urllib.parse import quote

def generate_image(prompt, width=1280, height=720,


seed=42, model="flux"):
encoded_prompt = quote(prompt)

image_url =
f"https://pollinations.ai/p/{encoded_prompt}?width={width
}&height={height}&seed={seed}&model={model}"

return image_url

def display_image_from_url(image_url):
response = requests.get(image_url)
if response.status_code == 200:
image = Image.open(io.BytesIO(response.content))

root = tk.Tk()
root.title("Generated Image")

#SnakesInCode
tk_image = ImageTk.PhotoImage(image)

label = tk.Label(root, image=tk_image)


label.image = tk_image
label.pack()
def download_image():
with open("downloaded_image.jpg", "wb") as
file:
file.write(response.content)
print("Image downloaded successfully.")
root.quit()

download_button = tk.Button(root, text="Download


Image", command=download_image)
download_button.pack()

root.mainloop()
else:
print(f"Failed to fetch image. Status code:
{response.status_code}")

def image_generator():
print("\n[Image Generator]")
prompt = input("What do you want to generate: ")
print("Generating image...")

try:
image_url = generate_image(prompt)
display_image_from_url(image_url)
except Exception as e:
print(f"Error during image generation: {e}")

if __name__ == "__main__":

#SnakesInCode
image_generator()

4. CSV Editor
File Name: csv_editor.py

Handles the creation, viewing, editing, and modification of CSV files.

Code:
import csv
import os

def csv_editor():
def display_menu():
print("\n=== CSV Editor ===")
print("1. Create a New CSV File")
print("2. View an Existing CSV File")
print("3. Add Rows to an Existing CSV File")
print("4. Modify Data in an Existing CSV File")
print("5. Exit")

def create_csv():
file_name = input("Enter the name of the new CSV
file (e.g., data.csv): ")
headers = input("Enter column headers
(comma-separated): ").split(",")
with open(file_name, mode="w", newline="") as
file:
writer = csv.writer(file)
writer.writerow(headers)
print(f"{file_name} created successfully.")

def view_csv():

#SnakesInCode
file_name = input("Enter the name of the CSV file
to view: ")
if not os.path.exists(file_name):
print("File not found.")
return
with open(file_name, mode="r") as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))

def add_rows():
file_name = input("Enter the name of the CSV file
to add rows to: ")
if not os.path.exists(file_name):
print("File not found.")
return
rows = []
while True:
row = input("Enter row data (comma-separated,
type 'done' to stop): ")
if row.lower() == "done":
break
rows.append(row.split(","))
with open(file_name, mode="a", newline="") as
file:
writer = csv.writer(file)
writer.writerows(rows)
print("Rows added successfully.")

def modify_csv():
file_name = input("Enter the name of the CSV file
to modify: ")
if not os.path.exists(file_name):
print("File not found.")

#SnakesInCode
return
with open(file_name, mode="r") as file:
rows = list(csv.reader(file))

print("Current Data:")
for i, row in enumerate(rows):
print(f"{i}: {', '.join(row)}")

row_index = int(input("Enter the row number to


modify: "))
col_index = int(input("Enter the column number to
modify: "))
new_value = input("Enter the new value: ")

if 0 <= row_index < len(rows) and 0 <= col_index


< len(rows[row_index]):
rows[row_index][col_index] = new_value
with open(file_name, mode="w", newline="") as
file:
writer = csv.writer(file)
writer.writerows(rows)
print("Data modified successfully.")
else:
print("Invalid row or column index.")

while True:
display_menu()
choice = input("\nEnter your choice: ")

if choice == '1':
create_csv()
elif choice == '2':
view_csv()

#SnakesInCode
elif choice == '3':
add_rows()
elif choice == '4':
modify_csv()
elif choice == '5':
print("Exiting CSV Editor.")
break
else:
print("Invalid choice. Please try again!")

#SnakesInCode
5. Unit Converter
File Name: unit_converter.py

Converts values between various units (length, weight, and


temperature).

Code:
def unit_converter():
def display_menu():
print("\n=== Unit Converter ===")
print("1. Length Conversion (meters <->
kilometers, inches <-> centimeters)")
print("2. Weight Conversion (kilograms <->
pounds)")
print("3. Temperature Conversion (Celsius <->
Fahrenheit)")
print("4. Exit")

def length_conversion():
print("\n[Length Conversion]")
print("1. Meters to Kilometers")
print("2. Kilometers to Meters")
print("3. Inches to Centimeters")
print("4. Centimeters to Inches")
choice = input("Enter your choice: ")
value = float(input("Enter the value to convert:
"))

if choice == '1':
print(f"{value} meters = {value / 1000}
kilometers")

#SnakesInCode
elif choice == '2':
print(f"{value} kilometers = {value * 1000}
meters")
elif choice == '3':
print(f"{value} inches = {value * 2.54}
centimeters")
elif choice == '4':
print(f"{value} centimeters = {value / 2.54}
inches")
else:
print("Invalid choice!")

def weight_conversion():
print("\n[Weight Conversion]")
print("1. Kilograms to Pounds")
print("2. Pounds to Kilograms")
choice = input("Enter your choice: ")
value = float(input("Enter the value to convert:
"))

if choice == '1':
print(f"{value} kilograms = {value * 2.20462}
pounds")
elif choice == '2':
print(f"{value} pounds = {value / 2.20462}
kilograms")
else:
print("Invalid choice!")

def temperature_conversion():
print("\n[Temperature Conversion]")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = input("Enter your choice: ")

#SnakesInCode
value = float(input("Enter the temperature to
convert: "))

if choice == '1':
print(f"{value}°C = {(value * 9/5) + 32}°F")
elif choice == '2':
print(f"{value}°F = {(value - 32) * 5/9}°C")
else:
print("Invalid choice!")
while True:
display_menu()
choice = input("\nEnter your choice: ")

if choice == '1':
length_conversion()
elif choice == '2':
weight_conversion()
elif choice == '3':
temperature_conversion()
elif choice == '4':
print("Exiting Unit Converter.")
break
else:
print("Invalid choice. Please try again!")

#SnakesInCode
6. Graph Plotter
File Name: graph_plotter.py

Visualizes data using Matplotlib.

Code:
import matplotlib.pyplot as plt
import numpy as np

def graph_plotter():
def display_menu():
print("\n=== Graph Plotter ===")
print("1. Line Plot")
print("2. Bar Plot")
print("3. Scatter Plot")
print("4. Exit")

def line_plot():
x = list(map(float, input("Enter x values
(comma-separated): ").split(",")))
y = list(map(float, input("Enter y values
(comma-separated): ").split(",")))
plt.plot(x, y, marker="o")
plt.title("Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid()
plt.show()

def bar_plot():
x = list(map(str, input("Enter categories
(comma-separated): ").split(",")))

#SnakesInCode
y = list(map(float, input("Enter values
(comma-separated): ").split(",")))
plt.bar(x, y, color="skyblue")
plt.title("Bar Plot")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.grid(axis="y")
plt.show()
def scatter_plot():
x = list(map(float, input("Enter x values
(comma-separated): ").split(",")))
y = list(map(float, input("Enter y values
(comma-separated): ").split(",")))
plt.scatter(x, y, color="red")
plt.title("Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid()
plt.show()

while True:
display_menu()
choice = input("\nEnter your choice: ")
if choice == '1':
line_plot()
elif choice == '2':
bar_plot()
elif choice == '3':
scatter_plot()
elif choice == '4':
print("Exiting Graph Plotter.")
break
else:
print("Invalid choice. Please try again!")

#SnakesInCode
7. File Organizer
File Name: file_organizer.py

Organizes files in a directory into categorized folders (e.g., Images,


Videos).

Code:
import os
import shutil
def file_organizer():
print("\n=== File Organizer ===")
directory = input("Enter the directory to organize:
")
if not os.path.exists(directory):
print("Directory not found.")
return
file_types = {
"Images": [".jpg", ".jpeg", ".png", ".gif"],
"Videos": [".mp4", ".mkv", ".flv", ".avi"],
"Documents": [".pdf", ".docx", ".xlsx", ".txt"],
"Archives": [".zip", ".rar", ".7z"],
}
for folder, extensions in file_types.items():
folder_path = os.path.join(directory, folder)
os.makedirs(folder_path, exist_ok=True)
for file in os.listdir(directory):
if any(file.lower().endswith(ext) for ext in
extensions):
shutil.move(os.path.join(directory,
file), folder_path)
print("Files organized successfully.")

#SnakesInCode
8. Password Generator
File Name: password_generator.py

Generates random passwords based on user preferences.

Code:
import random
import string

def password_generator():
print("\n=== Password Generator ===")
length = int(input("Enter the desired password
length: "))
include_special = input("Include special characters?
(y/n): ").lower() == 'y'

characters = string.ascii_letters + string.digits


if include_special:
characters += string.punctuation

password = ''.join(random.choice(characters) for _ in


range(length))
print(f"Generated Password: {password}")

#SnakesInCode
9. Weather Checker
File Name: weather.py

Fetches real-time weather information using OpenWeatherMap's API.

Code:
import requests
import os

def weather_checker():
print("\n=== Weather Checker ===")
city = input("Enter the city name: ")
api_key=”48733f7654aeed178c014c5290e33db0”
url =
f"http://api.openweathermap.org/data/2.5/weather?q={city}
&appid={api_key}&units=metric"

try:
response = requests.get(url)
data = response.json()
if data["cod"] == 200:
print(f"Weather in {city}:")
print(f"Temperature:
{data['main']['temp']}°C")
print(f"Condition:
{data['weather'][0]['description']}")
else:
print(f"Error: {data['message']}")
except Exception as e:
print("Failed to retrieve weather data. Please
check your internet connection.")

#SnakesInCode
Usage
Step 1: Clone the repository
Clone this repository to your local machine using Git:
git clone https://github.com/Geetansh-Jangid/CS-Project/

For linux(or mac os) :-


cd CS-Project

For windows :-
chdir CS-Project

Optional (But Recommended)


Create a Virtual Environment
Create a virtual environment inside the project directory:
$ python3 -m venv venv

This creates a venv directory.

Activate the virtual environment:

On Linux/Mac:
$ source venv/bin/activate

On Windows:
$ .\venv\Scripts\activate
You should see (venv) at the beginning of your terminal prompt,
indicating the virtual environment is active.

#SnakesInCode
Step 2: Install dependencies
You can install the required dependencies listed in the
requirements.txt file using pip:
$ pip install -r requirements.txt

This will install the following dependencies:-


● requests - for making HTTP requests to fetch the generated
image.
● Pillow - for working with images in Python.
● pollinations - for interacting with the Pollinations API to
generate images.
● tkinter - for creating the GUI to display images and other tools.
● dotenv - used for accessing the api keys

Step 3: Run the Application


To run the application, execute the following command:
$ python main.py

This will launch the tool suite with a text-based menu, allowing you to
choose which tool you'd like to use.

#SnakesInCode
#SnakesInCode

You might also like