youssefreda9 commited on
Commit
e18c6c8
·
1 Parent(s): 7cd5afa

fix: Use client.post() for all models, fix summarization params, better error capture

Browse files
Files changed (1) hide show
  1. src/hf_inference.py +84 -63
src/hf_inference.py CHANGED
@@ -12,6 +12,7 @@ Models:
12
  """
13
 
14
  import os
 
15
  import logging
16
  import time
17
 
@@ -43,100 +44,120 @@ PUNCTUATION_REPO = os.environ.get("PUNCTUATION_REPO_ID", "bayan10/PuncAra-v1")
43
  AUTOCOMPLETE_REPO = os.environ.get("AUTOCOMPLETE_REPO_ID", "bayan10/AutoComplete")
44
 
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  # ============================================================
47
  # Model-specific wrappers
48
  # ============================================================
49
 
50
  def hf_summarize(text, max_length=128, min_length=30):
51
  """Summarize Arabic text via HF Inference API."""
52
- client = _get_client()
53
  logger.info("Calling HF summarization: %s (max_length=%d)", SUMMARIZATION_REPO, max_length)
54
-
55
- result = client.summarization(
56
- text,
57
- model=SUMMARIZATION_REPO,
58
- parameters={"max_length": max_length, "min_length": min_length},
59
- )
60
-
61
- logger.info("Summarization result type: %s", type(result).__name__)
62
-
63
- # Result is a SummarizationOutput with .summary_text
64
- if hasattr(result, 'summary_text'):
65
- return result.summary_text
66
-
67
- # Fallback for dict responses
 
 
 
68
  if isinstance(result, dict):
69
  return result.get("summary_text", result.get("generated_text", str(result)))
70
-
71
  return str(result)
72
 
73
 
74
  def hf_correct_spelling(text):
75
  """Correct spelling in Arabic text via HF Inference API."""
76
- client = _get_client()
77
  logger.info("Calling HF spelling correction: %s", SPELLING_REPO)
78
-
79
- # Use text_generation since model has no pipeline_tag
80
- result = client.text_generation(
81
- text,
82
- model=SPELLING_REPO,
83
- max_new_tokens=len(text) + 50,
84
- )
85
-
86
- logger.info("Spelling result type: %s, value: %s", type(result).__name__, str(result)[:100])
87
-
88
- if isinstance(result, str):
89
- return result if result.strip() else text
90
-
91
  if isinstance(result, dict):
92
- return result.get("generated_text", text)
93
-
94
  return text
95
 
96
 
97
  def hf_add_punctuation(text):
98
  """Add punctuation to Arabic text via HF Inference API."""
99
- client = _get_client()
100
  logger.info("Calling HF punctuation: %s", PUNCTUATION_REPO)
101
-
102
- # PuncAra is an encoder-decoder model
103
- result = client.text_generation(
104
- text,
105
- model=PUNCTUATION_REPO,
106
- max_new_tokens=len(text) + 50,
107
- )
108
-
109
- logger.info("Punctuation result type: %s, value: %s", type(result).__name__, str(result)[:100])
110
-
111
- if isinstance(result, str):
112
- return result if result.strip() else text
113
-
114
  if isinstance(result, dict):
115
- return result.get("generated_text", text)
116
-
117
  return text
118
 
119
 
120
  def hf_autocomplete(text, n=5):
121
  """Get autocomplete suggestions for Arabic text via HF Inference API."""
122
- client = _get_client()
123
  logger.info("Calling HF autocomplete: %s", AUTOCOMPLETE_REPO)
124
-
125
- result = client.text_generation(
126
- text,
127
- model=AUTOCOMPLETE_REPO,
128
- max_new_tokens=20,
129
- )
130
-
131
- logger.info("Autocomplete result type: %s, value: %s", type(result).__name__, str(result)[:100])
132
-
133
  if isinstance(result, str):
134
- # Result includes the input + completion
135
  completion = result
136
  if completion.startswith(text):
137
  completion = completion[len(text):].strip()
138
  return [completion] if completion else [text]
139
-
140
  if isinstance(result, list):
141
  suggestions = []
142
  for item in result:
@@ -146,7 +167,7 @@ def hf_autocomplete(text, n=5):
146
  if gen:
147
  suggestions.append(gen)
148
  return suggestions if suggestions else [text]
149
-
150
  return [text]
151
 
152
 
@@ -154,7 +175,6 @@ def check_hf_api_available():
154
  """Quick check if HF Inference API is reachable."""
155
  try:
156
  client = _get_client()
157
- # Just check if the client can be created
158
  return client is not None
159
  except Exception:
160
  return False
@@ -186,7 +206,8 @@ def debug_test_all_models():
186
  except Exception as e:
187
  results[name] = {
188
  "status": "error",
189
- "error": str(e)[:500],
 
190
  }
191
 
192
  return results
 
12
  """
13
 
14
  import os
15
+ import json
16
  import logging
17
  import time
18
 
 
44
  AUTOCOMPLETE_REPO = os.environ.get("AUTOCOMPLETE_REPO_ID", "bayan10/AutoComplete")
45
 
46
 
47
+ # ============================================================
48
+ # Generic low-level call (works for models without pipeline_tag)
49
+ # ============================================================
50
+
51
+ def _call_model_raw(repo_id, payload):
52
+ """
53
+ Call any HF model using the low-level .post() method.
54
+ This works even for models without a pipeline_tag configured.
55
+ Returns parsed JSON response.
56
+ """
57
+ client = _get_client()
58
+ logger.info("Calling HF model (raw): %s", repo_id)
59
+
60
+ response = client.post(
61
+ json=payload,
62
+ model=repo_id,
63
+ )
64
+
65
+ # response is bytes
66
+ result = json.loads(response)
67
+ logger.info("HF raw result for %s: type=%s, preview=%s",
68
+ repo_id, type(result).__name__, str(result)[:150])
69
+ return result
70
+
71
+
72
  # ============================================================
73
  # Model-specific wrappers
74
  # ============================================================
75
 
76
  def hf_summarize(text, max_length=128, min_length=30):
77
  """Summarize Arabic text via HF Inference API."""
 
78
  logger.info("Calling HF summarization: %s (max_length=%d)", SUMMARIZATION_REPO, max_length)
79
+
80
+ # Use raw post since .summarization() has different kwargs
81
+ result = _call_model_raw(SUMMARIZATION_REPO, {
82
+ "inputs": text,
83
+ "parameters": {
84
+ "max_length": max_length,
85
+ "min_length": min_length,
86
+ }
87
+ })
88
+
89
+ # HF summarization returns: [{"summary_text": "..."}]
90
+ if isinstance(result, list) and len(result) > 0:
91
+ item = result[0]
92
+ if isinstance(item, dict):
93
+ return item.get("summary_text", item.get("generated_text", str(item)))
94
+ return str(item)
95
+
96
  if isinstance(result, dict):
97
  return result.get("summary_text", result.get("generated_text", str(result)))
98
+
99
  return str(result)
100
 
101
 
102
  def hf_correct_spelling(text):
103
  """Correct spelling in Arabic text via HF Inference API."""
 
104
  logger.info("Calling HF spelling correction: %s", SPELLING_REPO)
105
+
106
+ result = _call_model_raw(SPELLING_REPO, {
107
+ "inputs": text,
108
+ })
109
+
110
+ # Seq2seq/text2text models return: [{"generated_text": "..."}]
111
+ if isinstance(result, list) and len(result) > 0:
112
+ item = result[0]
113
+ if isinstance(item, dict):
114
+ return item.get("generated_text", item.get("translation_text", text))
115
+ return str(item) if str(item).strip() else text
116
+
 
117
  if isinstance(result, dict):
118
+ return result.get("generated_text", result.get("translation_text", text))
119
+
120
  return text
121
 
122
 
123
  def hf_add_punctuation(text):
124
  """Add punctuation to Arabic text via HF Inference API."""
 
125
  logger.info("Calling HF punctuation: %s", PUNCTUATION_REPO)
126
+
127
+ result = _call_model_raw(PUNCTUATION_REPO, {
128
+ "inputs": text,
129
+ })
130
+
131
+ if isinstance(result, list) and len(result) > 0:
132
+ item = result[0]
133
+ if isinstance(item, dict):
134
+ return item.get("generated_text", item.get("translation_text", text))
135
+ return str(item) if str(item).strip() else text
136
+
 
 
137
  if isinstance(result, dict):
138
+ return result.get("generated_text", result.get("translation_text", text))
139
+
140
  return text
141
 
142
 
143
  def hf_autocomplete(text, n=5):
144
  """Get autocomplete suggestions for Arabic text via HF Inference API."""
 
145
  logger.info("Calling HF autocomplete: %s", AUTOCOMPLETE_REPO)
146
+
147
+ result = _call_model_raw(AUTOCOMPLETE_REPO, {
148
+ "inputs": text,
149
+ "parameters": {
150
+ "max_new_tokens": 20,
151
+ }
152
+ })
153
+
154
+ # Text generation returns: [{"generated_text": "..."}] or a string
155
  if isinstance(result, str):
 
156
  completion = result
157
  if completion.startswith(text):
158
  completion = completion[len(text):].strip()
159
  return [completion] if completion else [text]
160
+
161
  if isinstance(result, list):
162
  suggestions = []
163
  for item in result:
 
167
  if gen:
168
  suggestions.append(gen)
169
  return suggestions if suggestions else [text]
170
+
171
  return [text]
172
 
173
 
 
175
  """Quick check if HF Inference API is reachable."""
176
  try:
177
  client = _get_client()
 
178
  return client is not None
179
  except Exception:
180
  return False
 
206
  except Exception as e:
207
  results[name] = {
208
  "status": "error",
209
+ "error_type": type(e).__name__,
210
+ "error": str(e)[:500] if str(e) else repr(e)[:500],
211
  }
212
 
213
  return results