import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE' import torch import pandas as pd import gradio as gr from transformers import EsmForSequenceClassification, EsmTokenizer from pathlib import Path import tempfile # ========== 关键修改:使用绝对路径 ========== # Hugging Face Space 中文件在 /app/ 目录下 BASE_DIR = Path(__file__).parent.absolute() MODEL_PATH = str(BASE_DIR / "car-toner-final") print(f"Loading model from: {MODEL_PATH}") # 检查路径是否存在 if not os.path.exists(MODEL_PATH): print(f"ERROR: Model path not found: {MODEL_PATH}") print(f"Current directory: {os.getcwd()}") print(f"Files in current dir: {os.listdir('.')}") raise FileNotFoundError(f"Model not found at {MODEL_PATH}") tokenizer = EsmTokenizer.from_pretrained(MODEL_PATH, local_files_only=True) model = EsmForSequenceClassification.from_pretrained(MODEL_PATH, local_files_only=True) model.eval() print("Model loaded!") def predict_sequence(seq): seq = ''.join([c for c in seq if c.isalpha()]) if not seq: return None, "Empty" inputs = tokenizer(seq, return_tensors="pt", truncation=True, max_length=512) with torch.no_grad(): score = model(**inputs).logits.item() if score > 0.7: level = "Strong (may exhaust)" elif score > 0.4: level = "Medium" else: level = "Weak (persistent)" return score, level def predict_text(text): if not text or not text.strip(): return None, "Please enter sequences", None sequences = [s.strip() for s in text.strip().split('\n') if s.strip()] if not sequences: return None, "No valid sequences", None results = [] for seq in sequences: score, level = predict_sequence(seq) results.append({ 'Sequence': seq[:50] + '...' if len(seq) > 50 else seq, 'PCP_Score': round(score, 4), 'Signal_Level': level }) df = pd.DataFrame(results) valid_scores = [r['PCP_Score'] for r in results] stats = f"Mean={sum(valid_scores)/len(valid_scores):.4f}, Min={min(valid_scores):.4f}, Max={max(valid_scores):.4f}" temp_path = os.path.join(tempfile.gettempdir(), "predictions.xlsx") df.to_excel(temp_path, index=False) return df, f"Predicted {len(results)} sequences. {stats}", temp_path def predict_file(file_obj): if file_obj is None: return None, "Please upload a file", None try: if file_obj.name.endswith('.csv'): df = pd.read_csv(file_obj.name) else: df = pd.read_excel(file_obj.name) seq_col = None for col in df.columns: if 'seq' in col.lower(): seq_col = col break if seq_col is None: seq_col = df.columns[0] sequences = df[seq_col].dropna().astype(str).tolist() scores, levels = [], [] for seq in sequences: score, level = predict_sequence(seq) scores.append(score) levels.append(level) df['PCP_Score'] = scores df['Signal_Level'] = levels temp_path = os.path.join(tempfile.gettempdir(), "batch_predictions.xlsx") df.to_excel(temp_path, index=False) return df, f"Processed {len(sequences)} sequences from '{seq_col}'", temp_path except Exception as e: return None, f"Error: {str(e)}", None with gr.Blocks(title="CAR") as demo: gr.Markdown("# 🧬 CAR: CAR Prediction") gr.Markdown("Predict PCP scores for CAR constructs") with gr.Tab("📝 Text Input"): input_text = gr.Textbox( label="Enter sequences (one per line)", lines=10, placeholder="MWSAGQGGMWSAGQGG\nMALWMRLLPLLALLALWGPDPAA..." ) predict_btn = gr.Button("🔮 Predict", variant="primary") output_table = gr.DataFrame(label="Results") output_msg = gr.Markdown() download = gr.File(label="📥 Download Excel") predict_btn.click(predict_text, inputs=input_text, outputs=[output_table, output_msg, download]) with gr.Tab("📁 File Upload"): input_file = gr.File(label="Upload Excel or CSV file") predict_file_btn = gr.Button("📁 Process File", variant="primary") output_file_table = gr.DataFrame(label="Results") output_file_msg = gr.Markdown() download2 = gr.File(label="📥 Download Results") predict_file_btn.click(predict_file, inputs=input_file, outputs=[output_file_table, output_file_msg, download2]) if __name__ == "__main__": demo.launch()