Skip to content

Commit

Permalink
add .exe test
Browse files Browse the repository at this point in the history
  • Loading branch information
edouardbruelhart committed Apr 12, 2024
1 parent 7935a8f commit 1b9536e
Show file tree
Hide file tree
Showing 7 changed files with 306 additions and 19 deletions.
127 changes: 122 additions & 5 deletions ms_sample_list_creator/csv_batch.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import csv
import os
import tkinter as tk
from datetime import datetime
from tkinter import filedialog

import pandas as pd
import requests


class csvBatch(tk.Frame):
def __init__(self, csv_batch_window: tk.Toplevel, root: tk.Tk):
Expand Down Expand Up @@ -32,7 +36,7 @@ def __init__(self, csv_batch_window: tk.Toplevel, root: tk.Tk):
self.pre_blk = int(str(os.environ.get("PRE_BLK")))
self.post_blk = int(str(os.environ.get("POST_BLK")))
self.blk_name = str(os.environ.get("BLK_NAME"))
self.blk_pos = str(os.environ.get("LK_POS"))
self.blk_pos = str(os.environ.get("BLK_POS"))
self.inj_volume = int(str(os.environ.get("INJ_VOLUME")))
self.access_token = str(os.environ.get("ACCESS_TOKEN"))
self.method_file = str(os.environ.get("METHOD_FILE"))
Expand All @@ -41,14 +45,14 @@ def __init__(self, csv_batch_window: tk.Toplevel, root: tk.Tk):
self.file = str(os.environ.get("FILE"))
self.current_position = 1
self.current_row = 1
self.timestamp = datetime.now().strftime("%Y%m%d%H%M")
self.timestamp = "202404101527"#datetime.now().strftime("%Y%m%d%H%M")
self.csv_path = f"{self.output_folder}/{datetime.now().strftime('%Y%m%d')}_{self.operator}_dbgi_{self.file}.csv"

warning_label = tk.Label(
self.warning_label = tk.Label(
self.csv_batch_window,
text="Warning, this mode is exclusively made to submit sample lists that have already been made using this tool.",
)
warning_label.pack()
self.warning_label.pack()

label = tk.Label(self.csv_batch_window, text="Search for your CSV:", pady=10)
label.pack()
Expand Down Expand Up @@ -99,4 +103,117 @@ def submit_result(self) -> None:
Returns:
None
"""
print("correctly written")
# Retrieves file path and method name given by the user
file_path = os.environ.get("FILE_PATH")
self.file = str(os.environ.get("FILE"))

# Converts the CSV to a dataframe
df = pd.read_csv(str(file_path), skiprows=1)

# Delete standby row
df = df.drop(df.index[-1])

# Remove blanks
patterns = ["pre", "post"]
combined_patterns = "|".join(patterns)
filtered_df = df[~df["File Name"].str.contains(combined_patterns, regex=True)]

# Update data path, instrument method and injection volume
path = self.data_path.replace("/", "\\")
instrument_method = self.method_file.replace("/", "\\")
filtered_df["Path"] = path
filtered_df["Instrument Method"] = instrument_method
filtered_df["Inj Vol"] = self.inj_volume

# Change timestamp and operator initials
filtered_df["File Name"] = df["File Name"].apply(
lambda x: "_".join([self.timestamp, self.operator] + x.split("_")[2:])
)

# Prepare data for directus
directus_df = filtered_df
directus_df = directus_df.drop(columns=["Path", "Position"])
directus_df["aliquot_id"] = ""
directus_df["ms_id"] = self.ms_id
directus_df = directus_df.rename(columns={"File Name": "mass_spec_id"})
directus_df = directus_df.rename(columns={"Inj Vol": "injection_volume"})
directus_df = directus_df.rename(columns={"Instrument Method": "injection_method"})
directus_df["injection_method"] = self.file
for index, row in directus_df.iterrows(): # Iterate over rows using iterrows()
parts = row["mass_spec_id"].split("_") # Split the "File Name" column by underscores
aliquot_id = "_".join(parts[2:]) # Extract the desired parts of the split string
directus_df.at[index, "aliquot_id"] = aliquot_id

# Send data to directus
records = directus_df.to_json(orient="records")
base_url = "http://directus.dbgi.org"
collection_url = base_url + "/items/Mass_Spectrometry_Analysis"
session = requests.Session()
headers = {"Content-Type": "application/json"}
session.headers.update({"Authorization": f"Bearer {self.access_token}"})
response = session.post(url=collection_url, headers=headers, data=records)

# Check if correctly added to directus
if response.status_code == 200:
self.warning_label.config(text="Success!! Writing CSV...", foreground="green")
# Write data to the CSV file
with open(self.csv_path, "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
# Write headers
csv_writer.writerow(["Bracket Type=4", "", "", "", ""])
csv_writer.writerow(["File Name", "Path", "Instrument Method", "Position", "Inj Vol"])

# Write pre blanks
if self.pre_blk > 0:
for i in range(1, self.pre_blk + 1):
padded_number = str(i).zfill(2)
filename = (
self.timestamp + "_" + self.operator + "_dbgi_" + self.blk_name + "_blk_pre" + padded_number
)
path = self.data_path.replace("/", "\\")
instrument_method = self.method_file.replace("/", "\\")
position = self.blk_pos
inj_volume = self.inj_volume
csv_writer.writerow([filename, path, instrument_method, position, inj_volume])
else:
print("no pre blanks")

# Write data
csv_writer.writerows(filtered_df.values)

# Write post blanks
if self.post_blk > 0:
for i in range(1, self.post_blk + 1):
padded_number = str(i).zfill(2)
filename = (
self.timestamp
+ "_"
+ self.operator
+ "_dbgi_"
+ self.blk_name
+ "_blk_post"
+ padded_number
)
path = self.data_path.replace("/", "\\")
instrument_method = self.method_file.replace("/", "\\")
position = self.blk_pos
inj_volume = self.inj_volume
csv_writer.writerow([filename, path, instrument_method, position, inj_volume])
else:
print("no post blanks")

# Write standby line
parts = self.standby_file.split("/")
file = parts[-1]
filename = self.timestamp + "_" + self.operator + "_" + file
path = self.data_path.replace("/", "\\")
standby = self.standby_file.replace("/", "\\")
position = self.blk_pos
inj_volume = self.inj_volume
csv_writer.writerow([filename, path, standby, position, inj_volume])

# Close the Tkinter window
self.csv_batch_window.destroy()
self.root.destroy()
else:
self.warning_label.config(text="Directus error, please check your CSV.", foreground="red")
4 changes: 4 additions & 0 deletions ms_sample_list_creator/home_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ def __init__(self, parent: tk.Tk, *args: Any, **kwargs: Any):
frame_entries_up.pack(fill="x", pady=5)

entry_username = tk.Entry(frame_entries_up, textvariable=self.username)
self.username.set("edouard.bruelhart@unifr.ch")
entry_username.pack(side="left", anchor="center")
entry_password = tk.Entry(frame_entries_up, textvariable=self.password, show="*")
self.password.set("861510Eb.98")
entry_password.pack(side="right", anchor="center")

frame_labels_om = tk.Frame(self)
Expand All @@ -67,9 +69,11 @@ def __init__(self, parent: tk.Tk, *args: Any, **kwargs: Any):
frame_entries_om.pack(fill="x", pady=(5, 0))

entry_operator = tk.Entry(frame_entries_om, textvariable=self.operator)
self.operator.set("EB")
entry_operator.pack(side="left", anchor="center")

entry_ms = tk.Entry(frame_entries_om, textvariable=self.ms_id)
self.ms_id.set("ms_000001")
entry_ms.pack(side="right", anchor="center")

frame_label_rack = tk.Frame(self)
Expand Down
14 changes: 3 additions & 11 deletions ms_sample_list_creator/ms_sample_list_creator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# To generate binaries for this script, install pyinstaller (pip install pyinstaller) and run "pyinstaller --onefile main.py"
# To generate binaries for this script, install pyinstaller (pip install pyinstaller) and run "pyinstaller --onefile ms_sample_list_creator.py"
# Generated binaries are made for the native system where the pyinstaller command is run.

# You can generate windows executable from linux using wine, by previously installing wine, python 3.8.19, pyinstaller and
# other non-built-in packages (here requests) inside wine. Then run: wine pyinstaller --onefile main.py
# other non-built-in packages (here requests and pandas) inside wine. Then run: wine pyinstaller --onefile ms_sample_list_creator.py

import tkinter as tk

Expand All @@ -29,6 +29,7 @@ def submit_results(clicked_button: str) -> None:
def handle_user_choice() -> None:
"""
Collect user choice and transmits it to de function that shows the correct window.
;C:\users\edouard\Local Settings\Application Data\Programs\Python\Python38\Scripts
Args:
None
Expand All @@ -43,15 +44,6 @@ def handle_user_choice() -> None:


def show_selected_window(choice: str) -> None:
"""
Accepts user choice and launches the correct window.
Args:
choice (str): Retrieves the user choice.
Returns:
None
"""
if choice == "new":
# Create a new Toplevel window for the new batch
new_batch_window = tk.Toplevel(root)
Expand Down
Binary file added ms_sample_list_creator/ms_test.exe
Binary file not shown.
4 changes: 2 additions & 2 deletions ms_sample_list_creator/new_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, new_batch_window: tk.Toplevel, root: tk.Tk):
self.pre_blk = int(str(os.environ.get("PRE_BLK")))
self.post_blk = int(str(os.environ.get("POST_BLK")))
self.blk_name = str(os.environ.get("BLK_NAME"))
self.blk_pos = str(os.environ.get("LK_POS"))
self.blk_pos = str(os.environ.get("BLK_POS"))
self.inj_volume = int(str(os.environ.get("INJ_VOLUME")))
self.access_token = str(os.environ.get("ACCESS_TOKEN"))
self.method_file = str(os.environ.get("METHOD_FILE"))
Expand Down Expand Up @@ -165,7 +165,7 @@ def add_row(self, event: Optional[tk.Event] = None) -> None:

self.label.config(text="")

if response.status_code == 200:
if response.status_code != 200:
# Check if it is the first run or not the first position in the rack
if (self.current_position > self.col_rack_size and self.current_position > self.col_rack_size) or (
self.current_position == 1 and self.current_row == 1
Expand Down
Loading

0 comments on commit 1b9536e

Please sign in to comment.