File size: 5,963 Bytes
022ace2
 
636cfae
022ace2
636cfae
 
 
 
 
 
 
 
 
 
 
c33e580
7ca4926
c33e580
 
 
636cfae
 
 
c33e580
7ca4926
c33e580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636cfae
c33e580
 
636cfae
 
c33e580
 
022ace2
c33e580
 
 
 
 
 
636cfae
c33e580
 
 
636cfae
c33e580
 
c7eeac3
022ace2
c33e580
 
636cfae
c33e580
 
636cfae
c33e580
 
 
 
 
636cfae
c33e580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022ace2
c33e580
 
 
022ace2
c33e580
636cfae
 
 
 
c33e580
636cfae
c33e580
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
import gradio as gr
import pandas as pd
import os

# 環境変数チェック
def check_environment():
    """環境変数をチェックし、不足している場合は警告"""
    missing_vars = []
    
    if not os.getenv("GROQ_API_KEY"):
        missing_vars.append("GROQ_API_KEY")
    
    if not os.getenv("OPENAI_API_KEY"):
        missing_vars.append("OPENAI_API_KEY")
    
    return missing_vars

# 軽量版データ生成関数
def generate_sample_dataframe(age, sex, tumor_type, GeneMutation, Meseable, Biopsiable):
    """サンプルデータを生成(デバッグ用)"""
    try:
        # 入力検証
        if not all([age, sex, tumor_type]):
            return pd.DataFrame()
        
        # サンプルデータの作成
        sample_data = {
            'NCTID': ['NCT12345678', 'NCT87654321', 'NCT11111111'],
            'AgentGrade': ['yes', 'no', 'unclear'],
            'Title': [
                f'Clinical Trial for {tumor_type} in {sex} patients',
                f'Alternative treatment for {tumor_type}',
                f'Experimental therapy for {tumor_type} with {GeneMutation}'
            ],
            'AgentJudgment': [
                f'{age}{sex}{tumor_type}患者は参加可能です',
                f'{age}{sex}{tumor_type}患者は参加できません',
                f'{age}{sex}{tumor_type}患者の参加は不明確です'
            ],
            'Japanese_Locations': ['Tokyo', 'Osaka', 'Kyoto'],
            'Cancer': [tumor_type, tumor_type, tumor_type]
        }
        
        df = pd.DataFrame(sample_data)
        return df
        
    except Exception as e:
        print(f"データフレーム生成エラー: {e}")
        return pd.DataFrame()

# フィルタリング関数
def filter_dataframe(df, grade):
    """データフレームをフィルタリング"""
    if df is None or len(df) == 0:
        return df
    
    try:
        if grade == "all":
            return df
        return df[df['AgentGrade'] == grade]
    except Exception as e:
        print(f"フィルタリングエラー: {e}")
        return df

# Gradioインターフェースの作成
def create_interface():
    missing_vars = check_environment()
    
    with gr.Blocks(title="臨床試験適格性評価(軽量版)", theme=gr.themes.Soft()) as demo:
        gr.Markdown("## 臨床試験適格性評価インターフェース(デバッグ版)")
        
        # 環境変数状態の表示
        if not missing_vars:
            gr.Markdown("✅ **ステータス**: 全ての環境変数が設定されています")
        else:
            gr.Markdown(f"⚠️ **注意**: 環境変数が不足しています: {', '.join(missing_vars)}")
        
        gr.Markdown("💡 **使用方法**: 患者情報を入力して「Generate Sample Data」をクリックしてください。")

        # 入力フィールド
        with gr.Row():
            with gr.Column():
                age_input = gr.Textbox(label="Age", placeholder="例: 65", value="65")
                sex_input = gr.Dropdown(choices=["男性", "女性"], label="Sex", value="男性")
                tumor_type_input = gr.Textbox(label="Tumor Type", placeholder="例: gastric cancer", value="gastric cancer")
            
            with gr.Column():
                gene_mutation_input = gr.Textbox(label="Gene Mutation", placeholder="例: HER2", value="HER2")
                measurable_input = gr.Dropdown(choices=["有り", "無し", "不明"], label="Measurable Tumor", value="有り")
                biopsiable_input = gr.Dropdown(choices=["有り", "無し", "不明"], label="Biopsiable Tumor", value="有り")

        # データフレーム表示
        dataframe_output = gr.DataFrame(
            label="Clinical Trials Results",
            interactive=False
        )
        
        # フィルタボタン
        with gr.Row():
            generate_button = gr.Button("Generate Sample Data", variant="primary")
            all_button = gr.Button("Show All", variant="secondary")
            yes_button = gr.Button("Show Eligible", variant="secondary")
            no_button = gr.Button("Show Ineligible", variant="secondary")
            unclear_button = gr.Button("Show Unclear", variant="secondary")

        # 状態管理
        df_state = gr.State(value=None)

        # イベントハンドリング
        def update_dataframe(age, sex, tumor_type, gene_mutation, measurable, biopsiable):
            df = generate_sample_dataframe(age, sex, tumor_type, gene_mutation, measurable, biopsiable)
            return df, df

        def filter_and_show(df, grade):
            filtered_df = filter_dataframe(df, grade)
            return filtered_df

        # ボタンイベント
        generate_button.click(
            fn=update_dataframe,
            inputs=[age_input, sex_input, tumor_type_input, gene_mutation_input, measurable_input, biopsiable_input],
            outputs=[dataframe_output, df_state]
        )
        
        all_button.click(
            fn=lambda df: filter_and_show(df, "all"),
            inputs=[df_state],
            outputs=[dataframe_output]
        )
        
        yes_button.click(
            fn=lambda df: filter_and_show(df, "yes"),
            inputs=[df_state],
            outputs=[dataframe_output]
        )
        
        no_button.click(
            fn=lambda df: filter_and_show(df, "no"),
            inputs=[df_state],
            outputs=[dataframe_output]
        )
        
        unclear_button.click(
            fn=lambda df: filter_and_show(df, "unclear"),
            inputs=[df_state],
            outputs=[dataframe_output]
        )

    return demo

# アプリケーション起動
if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True,
        show_error=True
    )