File size: 7,756 Bytes
88cd70c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a1752
 
 
 
 
88cd70c
d9a1752
 
88cd70c
d9a1752
 
 
 
 
 
 
 
 
 
88cd70c
6d0dd24
88cd70c
 
 
 
 
 
 
 
 
 
 
722f094
 
 
 
 
 
88cd70c
 
 
 
 
 
 
 
 
e265f59
88cd70c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b02ccbc
 
 
 
 
 
d9a1752
88cd70c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743b1a3
 
 
88cd70c
 
 
 
 
 
 
 
 
 
 
743b1a3
88cd70c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743b1a3
 
 
 
55989a6
743b1a3
 
6d0dd24
 
743b1a3
 
c264484
 
6d0dd24
 
 
b3d0c37
88cd70c
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import gradio as gr
import torch
import os
import numpy as np
import SimpleITK as sitk
from scipy.ndimage import zoom
from  resnet_gn import resnet50
import pickle
def load_from_pkl(load_path):
    data_input = open(load_path, 'rb')
    read_data = pickle.load(data_input)
    data_input.close()
    return read_data

Image_3D = None
Current_name = None
ALL_message = load_from_pkl(r'./label0601.pkl')

Model_Paht = r'./model_epoch62.pth.tar'
checkpoint = torch.load(Model_Paht,map_location='cpu')

classnet = resnet50(
                num_classes=1,
                sample_size=128,
                sample_duration=8)
classnet.load_state_dict(checkpoint['model_dict'])


def resize3D(img, aimsize, order = 3):
    """
    :param img: 3D array
    :param aimsize: list, one or three elements, like [256], or [256,56,56]
    :return:
    """
    _shape =img.shape
    if len(aimsize)==1:
        aimsize = [aimsize[0] for _ in range(3)]
    if aimsize[0] is None:
        return zoom(img, (1, aimsize[1] / _shape[1], aimsize[2] / _shape[2]),order=order)  # resample for cube_size
    if aimsize[1] is None:
        return zoom(img, (aimsize[0] / _shape[0], 1, aimsize[2] / _shape[2]),order=order)  # resample for cube_size
    if aimsize[2] is None:
        return zoom(img, (aimsize[0] / _shape[0], aimsize[1] / _shape[1], 1),order=order)  # resample for cube_size
    return zoom(img, (aimsize[0] / _shape[0], aimsize[1] / _shape[1], aimsize[2] / _shape[2]), order=order)  # resample for cube_size

def inference():
    model = classnet
    data = Image_3D

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.eval()
    all_loss = 0
    length = 0
    try:
        with torch.no_grad():
            data = torch.from_numpy(data)
            image = torch.unsqueeze(data, 0)
            patch_data = torch.unsqueeze(image, 0).to(device).float()  # (N, C_{in}, D_{in}, H_{in}, W_{in})

            # Pre : Prediction Result
            pre_probs = model(patch_data)

            # pre_probs = F.sigmoid(pre_probs)#todo
            pre_flat = pre_probs.view(-1)
            np.round(pre_flat.numpy()[0], decimals=2)
            #(1-pre_flat.numpy()[0]).astype(np.float32)
            #pre_flat.numpy()[0].astype(np.float32)
            p = float(np.round(pre_flat.numpy()[0], decimals=2))
            n = float(np.round(1-p, decimals=2))
            return {'急性期': n, '亚急性期': p}
    except:
        return {'': ''}



import gradio as gr
import numpy as np
import nibabel as nib
import os
import tempfile

def get_Image_reslice(input_file):
    '''得到图像 返回随即层'''
    global Image_3D
    global Current_name
    if isinstance(input_file, str):
        input_file=input_file
    else:
        input_file=input_file.name
    Image_3D = sitk.GetArrayFromImage(sitk.ReadImage(input_file))
    Current_name = input_file.split(os.sep)[-1].split('.')[0].rsplit('_',1)[0]
    Image_3D = (np.max(Image_3D)-Image_3D)/(np.max(Image_3D)-np.min(Image_3D))
    random_z = np.random.randint(0, Image_3D.shape[0])
    image_slice_z = Image_3D[random_z,:,:]

    random_y = np.random.randint(0, Image_3D.shape[1])
    image_slice_y = Image_3D[:, random_y, :]

    random_x = np.random.randint(0, Image_3D.shape[2])
    image_slice_x = Image_3D[:, :, random_x]
    print(random_x)
    # return  zoom(image_slice_z, (10 / image_slice_z.shape[0], 10 / image_slice_z.shape[1]), order=3) , \
    #         zoom(image_slice_y, (10 / image_slice_y.shape[0], 10 / image_slice_y.shape[1]), order=3), \
    #         zoom(image_slice_x, (10 / image_slice_x.shape[0], 10 / image_slice_x.shape[1]), order=3)
    return image_slice_z, \
           image_slice_y, \
           image_slice_x, random_z,random_y,random_x


def change_image_slice_x(slice):

    image_slice = Image_3D[:, :, slice-1]
    return image_slice

def change_image_slice_y(slice):
    image_slice = Image_3D[:, slice-1, :]
    return image_slice

def change_image_slice_z(slice):
    image_slice = Image_3D[slice-1,:,:]
    return image_slice

def get_medical_message():
    global Current_name
    if Current_name==None:
        return '请先加载数据',' '
    else:
        past = ALL_message[Current_name]['past']
        now = ALL_message[Current_name]['now']
        return past, now
        
def clear_all():
    global Image_3D
    global Current_name
    Current_name = None
    Image_3D = None
    return np.ones((10,10)),np.ones((10,10)),np.ones((10,10)),'','',{'': ''}

class App:
    def __init__(self):
        self.demo = None
        self.main()
    def main(self):
        # get_name = gr.Interface(lambda name: name, inputs="textbox", outputs="textbox")
        # prepend_hello = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs="textbox")
        # append_nice = gr.Interface(lambda greeting: f"{greeting} Nice to meet you!",
        #                            inputs="textbox", outputs=gr.Textbox(label="Greeting"))

        #iface_1 = gr.Interface(fn=get_Image_reslice, inputs=gr.inputs.File(label="Upload NIfTI file"), outputs=[,gr.Image(shape=(5, 5)),gr.Image(shape=(5, 5))])

        with gr.Blocks() as demo:
            inp = gr.inputs.File(label="Upload NIfTI file")
            with gr.Row():
                btn1 = gr.Button("Upload Data")
                clear = gr.Button("Clear")
            with gr.Tab("Image"):
                with gr.Row():
                    with gr.Column(scale=1):
                        out1 = gr.Image(shape=(10, 10))
                        slider1 = gr.Slider(1, 128, label='z轴层数', step=1, interactive=True)
                    with gr.Column(scale=1):
                        out2 = gr.Image(shape=(10, 10))
                        slider2 = gr.Slider(1, 256, label='y轴层数', step=1, interactive=True)
                    with gr.Column(scale=1):
                        out3 = gr.Image(shape=(10, 10))
                        slider3 = gr.Slider(1, 128, label='x轴层数', step=1, interactive=True)



            with gr.Tab("Medical Information"):
                with gr.Row():
                    with gr.Column(scale=1):
                        btn2 = gr.Button(label="临床信息")
                        out4 = gr.Textbox(label="患病史")
                        out6 = gr.Textbox(label="现病史")

                    with gr.Column(scale=1):
                        btn3 = gr.Button("分期结果")
                        out5 = gr.Label(num_top_classes=2,label='分期结果')

                btn3.click(inference, inputs=None, outputs=out5)
                btn2.click(get_medical_message, inputs=None, outputs=[out4,out6])
                #demo = gr.Series(get_name, prepend_hello, append_nice)

            btn1.click(get_Image_reslice, inp, [out1, out2, out3, slider1, slider2, slider3])
            slider3.change(change_image_slice_x, inputs=slider3, outputs=out3)
            slider2.change(change_image_slice_y, inputs=slider2, outputs=out2)
            slider1.change(change_image_slice_z, inputs=slider1, outputs=out1)
            clear.click(clear_all, None, [out1, out2, out3, out4, out6, out5], queue=True)
            
            gr.Markdown("Examples")
            gr.Examples(
                #examples=r'F:\WorkSpacing\XS_data\FenQi\chuli_data\ALL\358small_exp4_cut_128_256_128\1093978_A_L_MRI.nii.gz',
                examples=[[os.path.join(os.path.dirname(__file__), "4171551_B_L_MRI.nii.gz")],
                         [os.path.join(os.path.dirname(__file__), "4153597_B_L_MRI.nii.gz")]],
                inputs = inp,
                outputs = [out1, out2, out3,slider1,slider2,slider3],
                fn=get_Image_reslice,
                cache_examples=True,
            )
        demo.launch()
app = App()