viskav commited on
Commit
08cf85d
·
verified ·
1 Parent(s): 4f86b29

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -24
app.py CHANGED
@@ -2,23 +2,31 @@ from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from llama_cpp import Llama
5
- from huggingface_hub import hf_hub_download # just to ensure import works
6
 
7
- # GGUF MODEL
 
 
8
  MODEL_REPO = "bartowski/Phi-3.1-mini-4k-instruct-GGUF"
 
 
 
9
  MODEL_FILE = "Phi-3.1-mini-4k-instruct-IQ2_M.gguf"
10
 
11
  print("Loading Phi-3.1 Mini GGUF model...")
12
  llm = Llama.from_pretrained(
13
  repo_id=MODEL_REPO,
14
  filename=MODEL_FILE,
15
- n_threads=4, # increase if you have more CPU cores
16
- n_ctx=2048, # 2048 is enough for humanization, smaller = faster
17
- n_batch=256, # larger batch = faster generation on CPU
18
  verbose=False,
19
  )
20
  print("Model loaded successfully.")
21
 
 
 
 
22
  app = FastAPI()
23
 
24
  app.add_middleware(
@@ -32,18 +40,21 @@ class RequestBody(BaseModel):
32
  text: str
33
 
34
 
35
- # -------------------------------
36
- # STRONG SINGLE-PASS HUMANIZE PROMPT
37
- # -------------------------------
38
- SYSTEM_PROMPT = """You are a rewriting engine, not a question-answering assistant.
39
 
40
- Your job:
41
- - Take the user's text and rewrite it in more natural, human-like English.
42
- - Keep the same intent, meaning, and sentence type (a question stays a question).
43
- - Do NOT answer the question, ask for information, or add new content.
 
 
44
  - Do NOT explain what you are doing.
45
- - Output only one rewritten version of the text and nothing else."""
 
46
 
 
47
 
48
 
49
  @app.post("/api/humanize")
@@ -52,23 +63,33 @@ async def humanize(body: RequestBody):
52
  if not text:
53
  raise HTTPException(status_code=400, detail="Text cannot be empty")
54
 
55
- # Phi-3.1-style instruction formatting
 
 
 
 
56
  prompt = (
57
- f"<s>[SYSTEM]\n{SYSTEM_PROMPT}\n[/SYSTEM]\n"
58
- f"[USER]\n{text}\n[/USER]\n"
59
- "[ASSISTANT]\n"
 
60
  )
61
 
62
  try:
63
  output = llm(
64
  prompt,
65
- max_tokens=260, # ⬅ bump this up from 160
66
- temperature=0.3, # if you already set deterministic mode
67
- top_p=1.0,
68
- repeat_penalty=1.0,
69
- stop=["</s>", "[USER]", "[SYSTEM]", "[ASSISTANT]", "[/ASSISTANT]"],
70
  )
71
  result = output["choices"][0]["text"].strip()
 
 
 
 
 
72
  return {"result": result}
73
 
74
  except Exception as e:
@@ -78,4 +99,4 @@ async def humanize(body: RequestBody):
78
 
79
  @app.get("/")
80
  def health():
81
- return {"status": "ok"}
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from llama_cpp import Llama
5
+ from huggingface_hub import hf_hub_download # keep to satisfy HF Spaces
6
 
7
+ # -----------------------------
8
+ # MODEL CONFIG
9
+ # -----------------------------
10
  MODEL_REPO = "bartowski/Phi-3.1-mini-4k-instruct-GGUF"
11
+
12
+ # Use a lighter, faster quant. You can keep Q4_K_M if you want,
13
+ # but IQ2_M will usually be faster on CPU.
14
  MODEL_FILE = "Phi-3.1-mini-4k-instruct-IQ2_M.gguf"
15
 
16
  print("Loading Phi-3.1 Mini GGUF model...")
17
  llm = Llama.from_pretrained(
18
  repo_id=MODEL_REPO,
19
  filename=MODEL_FILE,
20
+ n_threads=4, # match your CPU cores
21
+ n_ctx=1024, # enough for a few paragraphs, faster than 2048
22
+ n_batch=512, # big speed-up
23
  verbose=False,
24
  )
25
  print("Model loaded successfully.")
26
 
27
+ # -----------------------------
28
+ # FASTAPI APP
29
+ # -----------------------------
30
  app = FastAPI()
31
 
32
  app.add_middleware(
 
40
  text: str
41
 
42
 
43
+ # Strong paraphrasing / humanizing prompt
44
+ SYSTEM_PROMPT = """
45
+ You are a professional paraphrasing engine.
 
46
 
47
+ Rewrite the given text so that:
48
+ - The wording and sentence structure are clearly different from the original.
49
+ - The meaning, facts, and tone stay exactly the same.
50
+ - You avoid copying long phrases from the input. Do not keep more than 5–6 consecutive words the same.
51
+ - Vary sentence lengths and break or merge sentences when natural.
52
+ - Do NOT answer questions or add new information.
53
  - Do NOT explain what you are doing.
54
+ Output ONLY the rewritten text and nothing else.
55
+ """
56
 
57
+ MAX_INPUT_CHARS = 3000 # safety limit so long essays don't kill the CPU
58
 
59
 
60
  @app.post("/api/humanize")
 
63
  if not text:
64
  raise HTTPException(status_code=400, detail="Text cannot be empty")
65
 
66
+ # truncate extremely long inputs for speed/stability
67
+ if len(text) > MAX_INPUT_CHARS:
68
+ text = text[:MAX_INPUT_CHARS]
69
+
70
+ # Simple instruct-style prompt (NO chat tags)
71
  prompt = (
72
+ SYSTEM_PROMPT
73
+ + "\n\nOriginal text:\n"
74
+ + text
75
+ + "\n\nRewritten text:\n"
76
  )
77
 
78
  try:
79
  output = llm(
80
  prompt,
81
+ max_tokens=260, # enough to fully rewrite a long paragraph
82
+ temperature=0.6, # some variation → more human-like
83
+ top_p=0.9,
84
+ repeat_penalty=1.05,
85
+ # no chat stop tokens; model will stop on its own
86
  )
87
  result = output["choices"][0]["text"].strip()
88
+
89
+ if not result:
90
+ # this prevents your frontend from showing confusing "No output" forever
91
+ raise HTTPException(status_code=500, detail="Model returned empty output")
92
+
93
  return {"result": result}
94
 
95
  except Exception as e:
 
99
 
100
  @app.get("/")
101
  def health():
102
+ return {"status": "ok"}