Basementup commited on
Commit
2c6d8b6
·
verified ·
1 Parent(s): 9cf5257

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -44
app.py CHANGED
@@ -19,6 +19,7 @@ from docx.enum.text import WD_ALIGN_PARAGRAPH
19
  SAVE_DIR = Path("/data/saved_docs")
20
  SAVE_DIR.mkdir(parents=True, exist_ok=True)
21
 
 
22
  MODEL = "meta-llama/Llama-3.3-70B-Instruct"
23
 
24
 
@@ -30,6 +31,7 @@ def call_llama(prompt, user_token=None, max_tokens=1200):
30
  """
31
  Pulls Llama directly via Hugging Face using HF_TOKEN.
32
  Prioritizes user_token from UI if provided, otherwise looks for HF_TOKEN env var.
 
33
  """
34
  # Use user provided token first, then fallback to env var
35
  token = (user_token or os.environ.get("HF_TOKEN", "")).strip()
@@ -41,45 +43,38 @@ def call_llama(prompt, user_token=None, max_tokens=1200):
41
  return "Model error: HF_TOKEN exists but does not look like a Hugging Face token. It should start with hf_."
42
 
43
  try:
44
- url = f"https://api-inference.huggingface.co/models/{MODEL}"
 
45
  headers = {
46
  "Authorization": f"Bearer {token}",
47
  "Content-Type": "application/json",
48
  }
 
 
49
  payload = {
50
- "inputs": prompt,
51
- "parameters": {
52
- "max_new_tokens": max_tokens,
53
- "temperature": 0.4,
54
- "return_full_text": False,
55
- },
56
- "options": {
57
- "wait_for_model": True,
58
- "use_cache": False,
59
- },
60
  }
61
 
62
  # Increased timeout for large case summaries
63
  response = requests.post(url, headers=headers, json=payload, timeout=180)
64
 
65
  if response.status_code != 200:
66
- return f"Model error: Hugging Face returned {response.status_code}: {response.text[:1200]}"
67
 
68
  data = response.json()
69
 
70
- if isinstance(data, list) and data:
71
- first = data[0]
72
- if isinstance(first, dict):
73
- return first.get("generated_text") or first.get("summary_text") or str(first)
74
- return str(first)
75
-
76
- if isinstance(data, dict):
77
- if "generated_text" in data:
78
- return data["generated_text"]
79
- if "error" in data:
80
- return f"Model error: {data['error']}"
81
- return str(data)
82
-
83
  return str(data)
84
 
85
  except Exception as e:
@@ -524,28 +519,28 @@ Document excerpt:
524
  {merged_doc[:50000]}
525
  """.strip()
526
 
527
- headers = {"Content-Type": "application/json"}
528
- if hf_token:
529
- headers["Authorization"] = f"Bearer {hf_token}"
530
-
531
- response = requests.post(
532
- "https://api-inference.huggingface.co/models/facebook/bart-large-cnn",
533
- headers=headers,
534
- json={
535
- "inputs": input_text,
536
- "parameters": {
537
- "max_length": 400,
538
- "min_length": 100,
539
- "do_sample": False,
540
- },
541
- },
542
- timeout=120,
543
- )
544
 
545
  if response.status_code == 200:
546
  data = response.json()
547
- if isinstance(data, list) and data:
548
- summary = data[0].get("summary_text", "")
549
  risk_lines = "\n".join(
550
  [f"- {k.replace('_', ' ').title()}: {v} instances" for k, v in risk_summary.items()]
551
  )
 
19
  SAVE_DIR = Path("/data/saved_docs")
20
  SAVE_DIR.mkdir(parents=True, exist_ok=True)
21
 
22
+ # Llama 3.3 70B is supported via the Hugging Face Router
23
  MODEL = "meta-llama/Llama-3.3-70B-Instruct"
24
 
25
 
 
31
  """
32
  Pulls Llama directly via Hugging Face using HF_TOKEN.
33
  Prioritizes user_token from UI if provided, otherwise looks for HF_TOKEN env var.
34
+ Uses the OpenAI-compatible Router API for Llama 3.3 70B.
35
  """
36
  # Use user provided token first, then fallback to env var
37
  token = (user_token or os.environ.get("HF_TOKEN", "")).strip()
 
43
  return "Model error: HF_TOKEN exists but does not look like a Hugging Face token. It should start with hf_."
44
 
45
  try:
46
+ # Use the Hugging Face Router endpoint which supports Llama 3.3 70B
47
+ url = "https://router.huggingface.co/v1/chat/completions"
48
  headers = {
49
  "Authorization": f"Bearer {token}",
50
  "Content-Type": "application/json",
51
  }
52
+
53
+ # Router uses OpenAI-style chat completions payload
54
  payload = {
55
+ "model": MODEL,
56
+ "messages": [
57
+ {"role": "user", "content": prompt}
58
+ ],
59
+ "max_tokens": max_tokens,
60
+ "temperature": 0.4,
61
+ "stream": False
 
 
 
62
  }
63
 
64
  # Increased timeout for large case summaries
65
  response = requests.post(url, headers=headers, json=payload, timeout=180)
66
 
67
  if response.status_code != 200:
68
+ return f"Model error: Hugging Face Router returned {response.status_code}: {response.text[:1200]}"
69
 
70
  data = response.json()
71
 
72
+ if "choices" in data and len(data["choices"]) > 0:
73
+ return data["choices"][0]["message"]["content"]
74
+
75
+ if "error" in data:
76
+ return f"Model error: {data['error']}"
77
+
 
 
 
 
 
 
 
78
  return str(data)
79
 
80
  except Exception as e:
 
519
  {merged_doc[:50000]}
520
  """.strip()
521
 
522
+ # Use the Router endpoint for summaries as well
523
+ url = "https://router.huggingface.co/v1/chat/completions"
524
+ headers = {
525
+ "Authorization": f"Bearer {hf_token}",
526
+ "Content-Type": "application/json",
527
+ }
528
+
529
+ payload = {
530
+ "model": "facebook/bart-large-cnn", # Router will handle this or we can use Llama
531
+ "messages": [
532
+ {"role": "user", "content": f"Summarise this forensic analysis:\n\n{input_text}"}
533
+ ],
534
+ "max_tokens": 400,
535
+ "temperature": 0.4
536
+ }
537
+
538
+ response = requests.post(url, headers=headers, json=payload, timeout=120)
539
 
540
  if response.status_code == 200:
541
  data = response.json()
542
+ if "choices" in data and len(data["choices"]) > 0:
543
+ summary = data["choices"][0]["message"]["content"]
544
  risk_lines = "\n".join(
545
  [f"- {k.replace('_', ' ').title()}: {v} instances" for k, v in risk_summary.items()]
546
  )