File size: 7,072 Bytes
691f8f6
 
 
 
 
 
 
 
 
d54d01e
691f8f6
 
 
 
 
454355d
c1c357e
 
 
 
 
 
691f8f6
454355d
aad3727
691f8f6
c1c357e
 
 
 
 
 
d54d01e
 
c1c357e
d54d01e
 
c1c357e
 
691f8f6
 
 
454355d
 
691f8f6
6deb948
 
 
 
 
 
 
b86d216
 
 
 
16f8b8c
 
fd78d16
 
6deb948
 
 
 
78a758b
6deb948
 
 
 
691f8f6
6deb948
 
 
33d5b7b
 
 
 
f21b31c
691f8f6
 
 
 
 
 
 
3a0872a
 
 
 
 
 
95e0edf
691f8f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeaad1a
3b420fc
 
a14ec14
 
 
 
 
 
 
 
eeaad1a
3b420fc
 
eeaad1a
3b420fc
 
eeaad1a
 
 
 
 
3b420fc
 
eeaad1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b420fc
eeaad1a
 
a14ec14
 
 
 
 
 
 
 
d020207
 
 
 
690e71d
a14ec14
 
3b420fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import gradio as gr
import pandas as pd
import umap
import matplotlib.pyplot as plt
import os
import tempfile
import scanpy as sc
import argparse
import subprocess
import sys
from io import BytesIO
from huggingface_hub import hf_hub_download


def main(input_file_path, species):

    # Get the current working directory
    current_working_directory = os.getcwd()
    
    # Print the current working directory
    print("Current Working Directory:", current_working_directory)

    # clone and cd into UCE repo
    os.system('git clone https://github.com/minwoosun/UCE.git')
    os.chdir('/home/user/app/UCE')

    # Get the current working directory
    current_working_directory = os.getcwd()
    
    # Print the current working directory
    print("Current Working Directory:", current_working_directory)

    # Specify the path to the directory you want to add
    new_directory = "/home/user/app/UCE"
    
    # Add the directory to the Python path
    sys.path.append(new_directory)


    ##############
    #     UCE    #
    ##############
    from evaluate import AnndataProcessor
    from accelerate import Accelerator

    # #  python eval_single_anndata.py --adata_path "./data/10k_pbmcs_proc.h5ad" --dir "./" --model_loc "minwoosun/uce-100m"
    # script_name = "/home/user/app/UCE/eval_single_anndata.py"
    # args = ["--adata_path", input_file_path, "--dir", "/home/user/app/UCE/", "--model_loc", "minwoosun/uce-100m"]
    # command = ["python", script_name] + args

    dir_path = '/home/user/app/UCE/'
    model_loc = 'minwoosun/uce-100m'

    print(input_file_path)
    print(dir_path)
    print(model_loc)

    # Verify adata_path is not None
    if input_file_path is None or not os.path.exists(input_file_path):
        raise ValueError(f"Invalid adata_path: {input_file_path}. Please check if the file exists.")
    
    # Construct the command
    command = [
        'python', 
        '/home/user/app/UCE/eval_single_anndata.py', 
        '--adata_path', input_file_path, 
        '--dir', dir_path, 
        '--model_loc', model_loc
    ]
    
    # Print the command for debugging
    print("Running command:", command)

    print("---> RUNNING UCE")
    result = subprocess.run(command, capture_output=True, text=True, check=True)
    print(result.stdout)
    print(result.stderr)
    print("---> FINSIH UCE")

    ##############
    #    UMAP    #
    ##############
    UMAP = True

    if (UMAP):

        # Set output file path
        file_name_with_ext = os.path.basename(input_file_path)
        file_name = os.path.splitext(file_name_with_ext)[0]
        output_file = "/home/user/app/UCE/" + f"{file_name}_uce_adata.h5ad"
        
        adata = sc.read_h5ad(output_file)

        labels = pd.Categorical(adata.obs["cell_type"])

        reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, random_state=42)
        embedding = reducer.fit_transform(adata.obsm["X_uce"])

        plt.figure(figsize=(10, 8))

        # Create the scatter plot
        scatter = plt.scatter(embedding[:, 0], embedding[:, 1], c=labels.codes, cmap='Set1', s=50, alpha=0.6)

        # Create a legend
        handles = []
        for i, cell_type in enumerate(labels.categories):
            handles.append(plt.Line2D([0], [0], marker='o', color='w', label=cell_type,
                                      markerfacecolor=plt.cm.Set1(i / len(labels.categories)), markersize=10))

        plt.legend(handles=handles, title='Cell Type')
        plt.title('UMAP projection of the data')
        plt.xlabel('UMAP1')
        plt.ylabel('UMAP2')
        
        # Save plot to a BytesIO object
        buf = BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        
        # Read the image from BytesIO object
        img = plt.imread(buf, format='png')
    else:
        img = None
        print("no image")
    
    return img, output_file



if __name__ == "__main__":   

    css = """
    body {background-color: black; color: white;}
    .gradio-container {background-color: black; color: white;}
    input, button, select, textarea {background-color: #333; color: white;}
    """

    with gr.Blocks(css=css) as demo:
        gr.Markdown(
            '''
            <div style="text-align:center; margin-bottom:20px;">
                <span style="font-size:3em; font-weight:bold; color: white;">UCE 100M Demo</span>
            </div>
            <div style="text-align:center; margin-bottom:10px;">
                <span style="font-size:1.5em; font-weight:bold; color: white;">Universal Cell Embeddings: Explore Single Cell Data</span>
            </div>
            <div style="text-align:center; margin-bottom:20px;">
                <a href="https://github.com/minwoosun/UCE">
                    <img src="https://badges.aleen42.com/src/github.svg" alt="GitHub" style="display:inline-block; margin-right:10px;">
                </a>
                <a href="https://www.biorxiv.org/content/10.1101/2023.11.28.568918v1">
                    <img src="https://img.shields.io/badge/bioRxiv-2023.11.28.568918-green?style=plastic" alt="Paper" style="display:inline-block; margin-right:10px;">
                </a>
            </div>
            <div style="text-align:left; margin-bottom:20px; color: white;">
                Upload a `.h5ad` single cell gene expression file and select the species (Human/Mouse). 
                The demo will generate UMAP projections of the embeddings and allow you to download the embeddings for further analysis.
            </div>
            <div style="margin-bottom:20px; color: white;">
                <ol style="list-style:none; padding-left:0;">
                    <li>1. Upload your `.h5ad` file</li>
                    <li>2. Select the species</li>
                    <li>3. View the UMAP scatter plot</li>
                    <li>4. Download the UMAP coordinates</li>
                </ol>
            </div>
            <div style="text-align:left; line-height:1.8; color: white;">
                Please consider citing the following paper if you use this tool in your research:
            </div>
            <div style="text-align:left; line-height:1.8; color: white;">
                Rosen, Y., Roohani, Y., Agarwal, A., Samotorčan, L., Tabula Sapiens Consortium, Quake, S. R., & Leskovec, J. Universal Cell Embeddings: A Foundation Model for Cell Biology. bioRxiv. https://doi.org/10.1101/2023.11.28.568918
            </div>
            '''
        )

        # Define Gradio inputs and outputs
        file_input = gr.File(label="Upload a .h5ad single cell gene expression file")
        species_input = gr.Dropdown(choices=["human", "mouse"], label="Select species")
        image_output = gr.Image(type="numpy", label="UMAP of UCE Embeddings")
        file_output = gr.File(label="Download embeddings")
    
        # Add the components and link to the function
        gr.Button("Run").click(
            fn=main, 
            inputs=[file_input, species_input], 
            outputs=[image_output, file_output]
        )
    
    demo.launch()