Trigger82 commited on
Commit
0ff477a
·
verified ·
1 Parent(s): 41c21f1

Rename main.py to app.py

Browse files
Files changed (2) hide show
  1. app.py +32 -0
  2. main.py +0 -65
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from fastapi import FastAPI
5
+
6
+ # Ensure cache env vars point to writable directory (same as Dockerfile)
7
+ home = os.environ.get("HOME", "/home/user")
8
+ cache_dir = os.path.join(home, ".cache", "huggingface")
9
+ os.makedirs(cache_dir, exist_ok=True)
10
+ os.environ["HF_HOME"] = cache_dir
11
+ os.environ["TRANSFORMERS_CACHE"] = cache_dir
12
+
13
+ model_id = "rasyosef/Phi-1_5-Instruct-v0.1"
14
+ model = AutoModelForCausalLM.from_pretrained(model_id)
15
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
16
+
17
+ app = FastAPI()
18
+ @app.get("/chat")
19
+ def chat(query: str):
20
+ # Compose chat-format prompt (system + user) for Phi-1.5
21
+ prompt = (
22
+ "<|im_start|>system\nYou are a helpful assistant.<|im_end|>"
23
+ "<|im_start|>user\n" + query + "<|im_end|>"
24
+ "<|im_start|>assistant\n"
25
+ )
26
+ inputs = tokenizer(prompt, return_tensors="pt")
27
+ outputs = model.generate(**inputs, max_new_tokens=200)
28
+ # Decode only the newly generated tokens (skip input tokens)
29
+ response = tokenizer.decode(
30
+ outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True
31
+ )
32
+ return {"answer": response.strip()}
main.py DELETED
@@ -1,65 +0,0 @@
1
- import os
2
- # Limit parallelism to fit 2 CPU cores
3
- os.environ["OMP_NUM_THREADS"] = "2"
4
- os.environ["MKL_NUM_THREADS"] = "2"
5
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
6
-
7
- from fastapi import FastAPI, HTTPException
8
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
9
- import gradio as gr
10
-
11
- # Load the Phi-1.5 Instruct model (1.3B) from Hugging Face
12
- model_id = "rasyosef/Phi-1_5-Instruct-v0.1"
13
- tokenizer = AutoTokenizer.from_pretrained(model_id)
14
- model = AutoModelForCausalLM.from_pretrained(model_id)
15
- pipe = pipeline(
16
- "text-generation",
17
- model=model,
18
- tokenizer=tokenizer
19
- )
20
-
21
- app = FastAPI()
22
-
23
- @app.get("/chat")
24
- def chat(query: str):
25
- """
26
- REST API endpoint. Use: GET /chat?query=Your question
27
- Returns a JSON {"response": "..."}.
28
- """
29
- if not query:
30
- raise HTTPException(status_code=400, detail="Query parameter 'query' is required.")
31
- # Use the same prompt format expected by the model:
32
- messages = [
33
- {"role": "system", "content": "You are a helpful assistant."},
34
- {"role": "user", "content": query}
35
- ]
36
- result = pipe(
37
- messages,
38
- max_new_tokens=100,
39
- do_sample=False,
40
- return_full_text=False
41
- )
42
- answer = result[0]["generated_text"].strip()
43
- return {"response": answer}
44
-
45
- # Define Gradio UI (optional)
46
- def gradio_chat(input_text):
47
- if not input_text:
48
- return ""
49
- messages = [
50
- {"role": "system", "content": "You are a helpful assistant."},
51
- {"role": "user", "content": input_text}
52
- ]
53
- result = pipe(messages, max_new_tokens=100, do_sample=False, return_full_text=False)
54
- return result[0]["generated_text"].strip()
55
-
56
- iface = gr.Interface(
57
- fn=gradio_chat,
58
- inputs=gr.Textbox(lines=2, placeholder="Type a message..."),
59
- outputs="text",
60
- title="Phi-1.5 Chatbot",
61
- description="Enter a message and press **Submit** to get a response."
62
- )
63
-
64
- # Mount Gradio at root so it does not conflict with /chat
65
- app = gr.mount_gradio_app(app, iface, path="/")