# Project export: BrainTumor-Segmentation_Model

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 10.0
- Tagline: hello
- Devpost: https://devpost.com/software/braintumor-segmentation_model
- GitHub: https://github.com/kyleluo518/CalHacks2023
- Team: 3 GitHub contributor(s) — dsharma136 (6 commits), Sarayu Mummidi (4 commits), kyleluo518 (1 commits)

## Devpost submission (written by the team)

### Inspiration

As a group, we came together with an idea that we wanted to make a product that could potentially have genuine effects in the real world. After researching various different ai model topics through databases such as Kaggle, we came across the topic of image segmentation specifically corresponding with brain tumors. This idea of autonomous image segmentation sounded like an incredibly interesting project to explore as an AI model for this would be able to minimize the labor-intensive process of instead doing manual segmentation. Besides the aspect of labor, we also believe the model we’ve created could yield other benefits from an educational and even emotional aspect which will be discussed later.

### What it does

The goal of the AI model is to simply perform the process of brain tumor segmentation as accurately as possible which would then be connected to a website to help match people.

### How we built it

This project was built using datasets provided by Kaggle in order to perform the process of segmentation. The reflex website was built using the reflex workshop's given information.

### Challenges we ran into

Some challenges we ran into for this project were that we had trouble finding larger datasets in order to train the model efficiently. Along with that, understanding the syntax for the reflex website was also a struggle for us as this was brand new.

### Accomplishments we're proud of

Accomplishments that we're incredibly proud of is that we were able to get the website up and running along with the fact that our model achieved a 0.8509 dice score which is very high for a model we built from scratch.

### What we learned

From this project, we learned a great deal about the efforts that go into training an AI model, brief information about the frontend and backend of fullstack development, and even what it was like to work in a group to build all of this effectively.

### What's next

I believe the next step for this model would be to increase the model's prediction by providing the model with a larger dataset. Along with this, I believe incorporating the AI aspect in to the website would also be something to work on in the future.

## README (from the GitHub repository)

# CalHacks2023
CalHacks 2023 Project: Kyle Luo, Dhruv Sharma, Varshini Gurushankar, Sarayu Mummidi

link to the dataset: 

https://www.kaggle.com/datasets/mateuszbuda/lgg-mri-segmentation


Note: The dice score representation provided in the text files is inaccurate as the 0 values actually represent 1's. 
This is due to an error as a portion of the images aren't present with any annotation ultimately resulting in a 0 dice score 
which is actually correct.


## Detected evidence (automated analysis)

Indexed codebase: 28 recognized source files, 38 KB.
- Python (language) — detected in the code

## Codebase structure (from repository index)

### Files (41 of 41)

```
.DS_Store
.gitignore
data.txt
dicescore_5000.txt
dicescoreaverage.py
dicescorenozero.py
dicescores_9500.txt
generatingimages.py
LICENSE
losschart.py
lossvalues.py
model.py
PatientEmpowerment/.DS_Store
PatientEmpowerment/.gitignore
PatientEmpowerment/alembic.ini
PatientEmpowerment/alembic/env.py
PatientEmpowerment/alembic/README
PatientEmpowerment/alembic/script.py.mako
PatientEmpowerment/alembic/versions/19b5fee0d01f_.py
PatientEmpowerment/PatientEmpowerment/__init__.py
PatientEmpowerment/PatientEmpowerment/components/__init__.py
PatientEmpowerment/PatientEmpowerment/components/sidebar.py
PatientEmpowerment/PatientEmpowerment/pages/__init__.py
PatientEmpowerment/PatientEmpowerment/pages/index.py
PatientEmpowerment/PatientEmpowerment/pages/matches.py
PatientEmpowerment/PatientEmpowerment/pages/register.py
PatientEmpowerment/PatientEmpowerment/PatientEmpowerment.py
PatientEmpowerment/PatientEmpowerment/state.py
PatientEmpowerment/PatientEmpowerment/styles.py
PatientEmpowerment/PatientEmpowerment/templates/__init__.py
PatientEmpowerment/PatientEmpowerment/templates/template.py
PatientEmpowerment/README.md
PatientEmpowerment/requirements.txt
PatientEmpowerment/rxconfig.py
README.md
requirements.txt
segmentationcount.py
similaritycomp.py
test.py
testingaimodel.py
tumorsimilarity.py
```

### Dependencies

- PatientEmpowerment/requirements.txt: reflex@==0.3.1
- requirements.txt: reflex@==0.3.1

### Recent commits (newest first)

- ready
- Update README.md
- Update README.md
- Add files via upload
- Create README.md
- Add files via upload
- Add files via upload
- fix and front end working
- new reflex
- Delete aisc.code-workspace
- Delete ai_project_sample.js
- updated_ai_sample
- adding ai
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### requirements.txt

```

reflex==0.3.1

```

### PatientEmpowerment/requirements.txt

```

reflex==0.3.1

```

### PatientEmpowerment/PatientEmpowerment/pages/index.py

```python
"""The home page of the app."""

from PatientEmpowerment import styles
from PatientEmpowerment.templates import template

import reflex as rx


@template(route="/", title="Home", image="/github.svg")
def index() -> rx.Component:
    """The home page.

    Returns:
        The UI for the home page.
    """
    return rx.box(
        rx.heading("Hi, we are Patient Empowerment!"),
        rx.text("Metrics:"),
        rx.image(src="/segmodel_explanation.png", height="30em")
    )

```

### dicescoreaverage.py

```python
# %%
dice_scores = []

# Read Dice Scores from the text file
with open("C:\calhacks_hackathon\AI_Model\dicescores_9500.txt", "r") as file:
    for line in file:
        if line.startswith("Dice Score:"):
            dice_score = float(line.split(":")[1].strip())
            dice_scores.append(dice_score)

total_score = sum(dice_scores)
count = len(dice_scores)

average_dice_score = total_score / count if count > 0 else 0.0

print(f"Average Dice Score: {average_dice_score:.4f}")




# %%

```

### dicescorenozero.py

```python
# %%
# Read Dice Scores from the text file
dice_scores = []

with open("C:\calhacks_hackathon\AI_Model\dicescores_9500.txt", "r") as file:
    for line in file:
        if line.startswith("Dice Score:"):
            parts = line.split()
            dice_score = float(parts[-1])
            # Replace 0 scores with 1
            if dice_score == 0:
                dice_score = 1
            dice_scores.append(dice_score)

# Calculate the average
total_score = sum(dice_scores)
average_dice_score = total_score / len(dice_scores)

print(f"Average Dice Score: {average_dice_score:.4f}")


# %%
```

### losschart.py

```python
# %%
import matplotlib.pyplot as plt

# Define the path to the loss file
loss_file_path = r'C:\calhacks_hackathon\ImageSegmentation\loss.txt'

# Read loss values from the text file, skipping the first line (header)
with open(loss_file_path, "r") as file:
    next(file)  # Skip the first line (header)
    loss_values = [float(line.strip()) for line in file]

# Create a list of iteration numbers (0, 1, 2, ...)
iterations = list(range(len(loss_values)))

# Create a line plot
plt.plot(iterations, loss_values, marker='o', linestyle='-')

# Set labels and title
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.title('Loss Over Iterations')

# Show the plot
plt.show()




# %%
```

### lossvalues.py

```python
# %%
# Open the data.txt file for reading
with open("C:\calhacks_hackathon\DataExtraction\data.txt", "r") as file:
    # Initialize an empty list to store the loss values
    loss_values = []

    # Iterate through each line in the file
    for line in file:
        # Check if the line contains "Loss=" to identify lines with loss information
        if "Loss=" in line:
            # Extract the loss value (assuming it's after "Loss=")
            loss_str = line.split("Loss=")[1].strip()
            # Convert the loss value to a float and append it to the list
            loss_values.append(float(loss_str))

# Print the extracted loss values
for idx, loss in enumerate(loss_values):
    print(f" {loss:.8f}")


# %%
```

### segmentationcount.py

```python
# %%
import os
import cv2

# Define the folder path
folder_path = r'C:\calhacks_hackathon\ImageSegmentation\archive\masks\masks_tests'

# Initialize a counter for images with white pixels
white_pixel_count = 0

# Loop through each file in the folder
for filename in os.listdir(folder_path):
    # Check if the file is an image (e.g., with a ".png" extension)
    if filename.endswith('.tif'):
        # Read the image using OpenCV
        image_path = os.path.join(folder_path, filename)
        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

        # Check if there are white pixels (pixel value of 255) in the image
        if 255 in image:
            white_pixel_count += 1

# Print the count of images with white pixels
print(f"Number of images with white pixels: {white_pixel_count}")



# %%
```

### test.py

```python
# %%
import os
import random
import shutil

# Source directory containing the images
source_directory = r'C:\calhacks_hackathon\ImageSegmentation\archive\images\images'

# Destination directory where you want to copy the 80% of the images
destination_directory = r'C:\calhacks_hackathon\ImageSegmentation\archive\images\80_percent_of_images'

# Create the destination directory if it doesn't exist
os.makedirs(destination_directory, exist_ok=True)

# List all files in the source directory
image_files = os.listdir(source_directory)

# Calculate the number of images to select (80%)
num_images_to_select = int(0.8 * len(image_files))

# Randomly shuffle the list of image files
random.shuffle(image_files)

# Select the first 'num_images_to_select' files
selected_images = image_files[:num_images_to_select]

# Copy the selected images to the destination directory
for image_file in selected_images:
    source_path = os.path.join(source_directory, image_file)
    destination_path = os.path.join(destination_directory, image_file)
    shutil.copy(source_path, destination_path)

print(f"Extracted {num_images_to_select} images to the destination directory.")


# %%
```

### similaritycomp.py

```python
# %%
import os
import cv2
import numpy as np

# Function to calculate Dice Similarity Coefficient
# Function to calculate Dice Similarity Coefficient
def dice_coefficient(mask1, mask2):
    intersection = np.logical_and(mask1, mask2)
    mask1_sum = mask1.sum()
    mask2_sum = mask2.sum()
    
    if mask1_sum == 0 and mask2_sum == 0:
        return 1.0  # Both masks are empty, consider them identical
    
    return 2.0 * intersection.sum() / (mask1_sum + mask2_sum)

# Folder containing mask images
mask_folder = r'C:\calhacks_hackathon\ImageSegmentation\archive\masks\masks_trains'

# Get a list of mask file paths
mask_files = [os.path.join(mask_folder, file) for file in os.listdir(mask_folder)]

# Initialize a similarity matrix
num_masks = len(mask_files)
similarity_matrix = np.zeros((num_masks, num_masks))

# Load and calculate Dice Similarity Coefficients
for i in range(num_masks):
    for j in range(i, num_masks):
        mask1 = cv2.imread(mask_files[i], cv2.IMREAD_GRAYSCALE)
        mask2 = cv2.imread(mask_files[j], cv2.IMREAD_GRAYSCALE)
        mask1 = mask1 > 0  # Convert to binary mask
        mask2 = mask2 > 0  # Convert to binary mask
        dsc = dice_coefficient(mask1, mask2)
        similarity_matrix[i][j] = dsc
        similarity_matrix[j][i] = dsc  # Similarity matrix is symmetric

# Print the similarity matrix
print("Similarity Matrix:")
print(similarity_matrix)

# %%
```

[17 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]