IamLevin40 commited on
Commit
dd73cae
·
verified ·
1 Parent(s): b6710f1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+
6
+ # Name of your public/private model on Hugging Face
7
+ model_id = "JAZL/ChemGist-Phi3"
8
+
9
+ # Fetch the secret token we just added to the Space settings
10
+ hf_token = os.environ.get("HF_TOKEN")
11
+
12
+ print(f"Loading tokenizer and model for {model_id} on CPU. This will take a few minutes...")
13
+
14
+ # Pass the token to the tokenizer
15
+ tokenizer = AutoTokenizer.from_pretrained(
16
+ model_id,
17
+ token=hf_token
18
+ )
19
+
20
+ # Pass the token to the model
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ model_id,
23
+ device_map="cpu",
24
+ torch_dtype=torch.float16,
25
+ low_cpu_mem_usage=True,
26
+ token=hf_token
27
+ )
28
+ print("Model loaded successfully into CPU memory!")
29
+
30
+ def generate_answer(message: str) -> str:
31
+ prompt = (
32
+ "<|user|>\n"
33
+ "You are ChemGist, an intelligent and conversational chemistry assistant. Answer the user's question accurately based on your training.\n\n"
34
+ "Answer the user's question by weaving the following facts into a natural, flowing paragraph. "
35
+ "CRITICAL: Do NOT use colons. Do NOT use bullet points. Do NOT output a list. "
36
+ "Write in complete sentences as if explaining it to a friend.\n\n"
37
+ f"Question: {message}<|end|>\n"
38
+ "<|assistant|>\n"
39
+ )
40
+
41
+ # Send inputs to CPU
42
+ inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
43
+
44
+ # Generate the text
45
+ # NOTE: max_new_tokens is set to 200 to prevent CPU timeouts
46
+ outputs = model.generate(
47
+ **inputs,
48
+ max_new_tokens=200,
49
+ temperature=0.3,
50
+ top_p=0.9,
51
+ repetition_penalty=1.1,
52
+ do_sample=True
53
+ )
54
+
55
+ full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
56
+
57
+ # Clean up the output to only return the assistant's reply
58
+ if "<|assistant|>" in full_response:
59
+ answer = full_response.split("<|assistant|>")[-1].strip()
60
+ else:
61
+ answer = full_response.strip()
62
+
63
+ return answer
64
+
65
+ # Build the Gradio Interface
66
+ demo = gr.Interface(
67
+ fn=generate_answer,
68
+ inputs=gr.Textbox(label="User Question", placeholder="Type your chemistry question here..."),
69
+ outputs=gr.Textbox(label="ChemGist Answer"),
70
+ title="ChemGist API Server (CPU Version)",
71
+ description="This Space hosts the ChemGist-Phi3 model on a Free CPU. Please be patient, CPU inference is slow and replies may take 1-3 minutes."
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()