viskav commited on
Commit
7a3d163
·
verified ·
1 Parent(s): 420f7ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -18
app.py CHANGED
@@ -3,12 +3,11 @@ from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from llama_cpp import Llama
5
  import os
6
- import uvicorn # Required for running the app correctly on HF Spaces
7
 
8
  # -----------------------------
9
  # MODEL CONFIG
10
  # -----------------------------
11
- # Ensure these files are available in your HF Space repository
12
  MODEL_REPO = "bartowski/Phi-3.1-mini-4k-instruct-GGUF"
13
  MODEL_FILE = "Phi-3.1-mini-4k-instruct-IQ2_M.gguf"
14
 
@@ -17,16 +16,15 @@ try:
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, # Context length for speed/memory
22
- n_batch=512,
23
  verbose=False,
24
  )
25
  print("Model loaded successfully.")
26
  except Exception as e:
27
- # Crucial for debugging HF Spaces issues
28
  print(f"FATAL ERROR: Could not load model: {e}")
29
- llm = None # Set to None so the server can start, but API calls will fail
30
 
31
  # -----------------------------
32
  # FASTAPI APP
@@ -43,7 +41,7 @@ app.add_middleware(
43
  class RequestBody(BaseModel):
44
  text: str
45
 
46
- # ⭐ ENHANCED SYSTEM PROMPT - Emphasizing natural, human-like output
47
  SYSTEM_PROMPT = """
48
  You are a highly skilled professional editor specializing in making academic or technical text sound natural, engaging, and indistinguishable from human writing.
49
  Your task is to rewrite the provided text following these strict rules:
@@ -84,18 +82,18 @@ async def humanize(body: RequestBody):
84
  output = llm(
85
  prompt,
86
  max_tokens=512,
87
- temperature=0.45, # Increased for more human-like variation
88
- top_p=0.9,
 
 
89
  repeat_penalty=1.05,
90
  stop=[END_TAG, "\nOriginal text:"],
91
  )
92
 
 
93
  raw_result = output["choices"][0]["text"].strip()
94
-
95
- # Robust extraction: look for the closing tag and clean up
96
  result = raw_result.split(END_TAG)[0].strip()
97
 
98
- # Remove the starting tag if the model included it in the output
99
  if result.startswith(START_TAG):
100
  result = result[len(START_TAG):].strip()
101
 
@@ -106,23 +104,18 @@ async def humanize(body: RequestBody):
106
 
107
  except Exception as e:
108
  print(f"Model execution error: {e}")
109
- # Return a 500 status code, which matches your frontend's catch block logic
110
  raise HTTPException(status_code=500, detail="Model execution error")
111
 
112
 
113
  @app.get("/")
114
  def health():
115
- # Simple health check, CRITICAL for HF Spaces to know the app is running
116
  return {"status": "ok"}
117
 
118
  # -----------------------------
119
  # DEPLOYMENT CONFIG FOR HUGGING FACE SPACES
120
  # -----------------------------
121
  if __name__ == "__main__":
122
- # 🚨 CRITICAL: Use 0.0.0.0 host and 7860 port for HF Spaces deployments
123
  HOST = os.environ.get("HOST", "0.0.0.0")
124
  PORT = int(os.environ.get("PORT", 7860))
125
  print(f"Starting server on {HOST}:{PORT}")
126
-
127
- # You will need to install uvicorn: pip install uvicorn
128
  uvicorn.run(app, host=HOST, port=PORT)
 
3
  from pydantic import BaseModel
4
  from llama_cpp import Llama
5
  import os
6
+ import uvicorn
7
 
8
  # -----------------------------
9
  # MODEL CONFIG
10
  # -----------------------------
 
11
  MODEL_REPO = "bartowski/Phi-3.1-mini-4k-instruct-GGUF"
12
  MODEL_FILE = "Phi-3.1-mini-4k-instruct-IQ2_M.gguf"
13
 
 
16
  llm = Llama.from_pretrained(
17
  repo_id=MODEL_REPO,
18
  filename=MODEL_FILE,
19
+ n_threads=4,
20
+ n_ctx=1024,
21
+ n_batch=512,
22
  verbose=False,
23
  )
24
  print("Model loaded successfully.")
25
  except Exception as e:
 
26
  print(f"FATAL ERROR: Could not load model: {e}")
27
+ llm = None
28
 
29
  # -----------------------------
30
  # FASTAPI APP
 
41
  class RequestBody(BaseModel):
42
  text: str
43
 
44
+ # Enhanced System Prompt (Same as before, it is strong enough)
45
  SYSTEM_PROMPT = """
46
  You are a highly skilled professional editor specializing in making academic or technical text sound natural, engaging, and indistinguishable from human writing.
47
  Your task is to rewrite the provided text following these strict rules:
 
82
  output = llm(
83
  prompt,
84
  max_tokens=512,
85
+ # ⭐ CRITICAL TWEAK: Increase Temperature for randomness/creativity
86
+ temperature=0.8, # AGGRESSIVELY increased from 0.45 to 0.8
87
+ # ⭐ CRITICAL TWEAK: Decrease top_p to focus on a smaller set of high-probability tokens
88
+ top_p=0.8, # Decreased from 0.9 to 0.8
89
  repeat_penalty=1.05,
90
  stop=[END_TAG, "\nOriginal text:"],
91
  )
92
 
93
+ # ... (rest of the robust post-processing remains the same)
94
  raw_result = output["choices"][0]["text"].strip()
 
 
95
  result = raw_result.split(END_TAG)[0].strip()
96
 
 
97
  if result.startswith(START_TAG):
98
  result = result[len(START_TAG):].strip()
99
 
 
104
 
105
  except Exception as e:
106
  print(f"Model execution error: {e}")
 
107
  raise HTTPException(status_code=500, detail="Model execution error")
108
 
109
 
110
  @app.get("/")
111
  def health():
 
112
  return {"status": "ok"}
113
 
114
  # -----------------------------
115
  # DEPLOYMENT CONFIG FOR HUGGING FACE SPACES
116
  # -----------------------------
117
  if __name__ == "__main__":
 
118
  HOST = os.environ.get("HOST", "0.0.0.0")
119
  PORT = int(os.environ.get("PORT", 7860))
120
  print(f"Starting server on {HOST}:{PORT}")
 
 
121
  uvicorn.run(app, host=HOST, port=PORT)