Basementup commited on
Commit
aec9d5b
·
verified ·
1 Parent(s): 9035f56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -17
app.py CHANGED
@@ -5,7 +5,6 @@ import time
5
  import subprocess
6
  import tempfile
7
  from pathlib import Path
8
- from huggingface_hub import InferenceClient
9
 
10
  # ── INSTALL ───────────────────────────────────────────────────────────────────
11
  for pkg in ["pypdf", "edge-tts", "pydub", "pillow", "pytesseract", "openai-whisper", "ffmpeg-python"]:
@@ -19,27 +18,61 @@ from pydub import AudioSegment
19
  from PIL import Image
20
  import pytesseract
21
 
22
- # ── MODEL — free on HF Pro, no credit cost ───────────────────────────────────
23
- # Primary: Mistral 7B — free, fast, no credit drain
24
- # Fallback: Zephyr 7B — also free
25
- PRIMARY_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
26
- FALLBACK_MODEL = "HuggingFaceH4/zephyr-7b-beta"
 
 
 
 
 
 
27
 
28
  def call_llama(prompt: str, max_tokens: int = 2000) -> str:
29
  token = os.environ.get("HF_TOKEN", "")
30
- for model in [PRIMARY_MODEL, FALLBACK_MODEL]:
 
 
31
  try:
32
- client = InferenceClient(model=model, token=token if token else None)
33
- response = client.chat_completion(
34
- messages=[{"role": "user", "content": prompt}],
35
- max_tokens=max_tokens,
36
- temperature=0.7,
37
- )
38
- return response.choices[0].message.content
39
- except Exception as e:
40
- last_err = str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  continue
42
- return f"Could not reach AI — check your HF_TOKEN is set in Space secrets. ({last_err})"
 
43
 
44
 
45
  # ── FILE EXTRACTION ───────────────────────────────────────────────────────────
 
5
  import subprocess
6
  import tempfile
7
  from pathlib import Path
 
8
 
9
  # ── INSTALL ───────────────────────────────────────────────────────────────────
10
  for pkg in ["pypdf", "edge-tts", "pydub", "pillow", "pytesseract", "openai-whisper", "ffmpeg-python"]:
 
18
  from PIL import Image
19
  import pytesseract
20
 
21
+ # ── MODEL — FREE HF INFERENCE API ────────────────────────────────────────────
22
+ # Bypasses router.huggingface.co (PAID) entirely.
23
+ # Uses api-inference.huggingface.co — completely free, same HF_TOKEN, no credits.
24
+ import requests as _req
25
+
26
+ _FREE_API = "https://api-inference.huggingface.co/models/{model}"
27
+ _MODELS = [
28
+ "HuggingFaceH4/zephyr-7b-beta",
29
+ "mistralai/Mistral-7B-Instruct-v0.3",
30
+ "microsoft/Phi-3-mini-4k-instruct",
31
+ ]
32
 
33
  def call_llama(prompt: str, max_tokens: int = 2000) -> str:
34
  token = os.environ.get("HF_TOKEN", "")
35
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
36
+
37
+ for model in _MODELS:
38
  try:
39
+ # Format prompt correctly for each model family
40
+ if "zephyr" in model:
41
+ fmt = f"<|system|>\nYou are a precise legal document analyst.</s>\n<|user|>\n{prompt}</s>\n<|assistant|>\n"
42
+ elif "Phi-3" in model:
43
+ fmt = f"<|user|>\n{prompt}<|end|>\n<|assistant|>\n"
44
+ else:
45
+ fmt = f"[INST] {prompt} [/INST]"
46
+
47
+ def _post(f):
48
+ return _req.post(
49
+ _FREE_API.format(model=model), headers=headers,
50
+ json={"inputs": f,
51
+ "parameters": {"max_new_tokens": max_tokens,
52
+ "temperature": 0.7,
53
+ "return_full_text": False,
54
+ "do_sample": True}},
55
+ timeout=120
56
+ )
57
+
58
+ resp = _post(fmt)
59
+
60
+ # Model loading — wait and retry once
61
+ if resp.status_code == 503:
62
+ import time; time.sleep(20)
63
+ resp = _post(fmt)
64
+
65
+ if resp.status_code == 200:
66
+ result = resp.json()
67
+ if isinstance(result, list) and result:
68
+ text = result[0].get("generated_text", "").strip()
69
+ if text:
70
+ return text
71
+
72
+ except Exception:
73
  continue
74
+
75
+ return "Could not reach AI. Make sure HF_TOKEN is set in your Space secrets."
76
 
77
 
78
  # ── FILE EXTRACTION ───────────────────────────────────────────────────────────