youssefreda9 commited on
Commit
465c938
·
1 Parent(s): b363fc1

fix: Try multiple _inner_post calling conventions + inspect signature

Browse files
Files changed (1) hide show
  1. src/hf_inference.py +45 -39
src/hf_inference.py CHANGED
@@ -9,6 +9,7 @@ import os
9
  import json
10
  import logging
11
  import time
 
12
 
13
  logger = logging.getLogger(__name__)
14
 
@@ -36,47 +37,54 @@ AUTOCOMPLETE_REPO = os.environ.get("AUTOCOMPLETE_REPO_ID", "bayan10/AutoComplete
36
  def _call_model(repo_id, payload, task=None):
37
  """
38
  Call HF model using InferenceClient._inner_post.
39
- This is the raw transport that all typed methods use internally.
40
  """
41
  client = _get_client()
42
 
43
  if "options" not in payload:
44
  payload["options"] = {"wait_for_model": True}
45
 
 
 
46
  logger.info("Calling HF model: %s (task=%s)", repo_id, task)
47
 
48
- try:
49
- # Use _inner_post — the internal transport in huggingface_hub 1.19.0
50
- response = client._inner_post(
51
- json=payload,
52
- model=repo_id,
53
- task=task,
54
- )
55
-
56
- # response is bytes
57
- if isinstance(response, bytes):
58
- result = json.loads(response.decode("utf-8"))
59
- elif isinstance(response, str):
60
- result = json.loads(response)
61
- else:
62
- result = response
63
-
64
- logger.info("HF result for %s: type=%s preview=%s",
65
- repo_id, type(result).__name__, str(result)[:200])
66
- return result
67
-
68
- except TypeError as e:
69
- # If _inner_post has different signature, try without task
70
- logger.warning("_inner_post with task failed: %s, retrying without task", e)
71
- response = client._inner_post(
72
- json=payload,
73
- model=repo_id,
74
- )
75
- if isinstance(response, bytes):
76
- return json.loads(response.decode("utf-8"))
77
- elif isinstance(response, str):
78
- return json.loads(response)
79
- return response
 
 
 
 
 
80
 
81
 
82
  def _extract_text(result, fallback=""):
@@ -104,7 +112,6 @@ def _extract_text(result, fallback=""):
104
  # ============================================================
105
 
106
  def hf_summarize(text, max_length=128, min_length=30):
107
- """Summarize Arabic text."""
108
  result = _call_model(SUMMARIZATION_REPO, {
109
  "inputs": text,
110
  "parameters": {"max_length": max_length, "min_length": min_length},
@@ -113,19 +120,16 @@ def hf_summarize(text, max_length=128, min_length=30):
113
 
114
 
115
  def hf_correct_spelling(text):
116
- """Correct spelling in Arabic text."""
117
  result = _call_model(SPELLING_REPO, {"inputs": text})
118
  return _extract_text(result, text)
119
 
120
 
121
  def hf_add_punctuation(text):
122
- """Add punctuation to Arabic text."""
123
  result = _call_model(PUNCTUATION_REPO, {"inputs": text})
124
  return _extract_text(result, text)
125
 
126
 
127
  def hf_autocomplete(text, n=5):
128
- """Get autocomplete suggestions."""
129
  result = _call_model(AUTOCOMPLETE_REPO, {
130
  "inputs": text,
131
  "parameters": {"max_new_tokens": 20},
@@ -159,12 +163,14 @@ def debug_test_all_models():
159
  test_text = "هذا نص تجريبي للاختبار"
160
  long_text = (test_text + " ") * 5
161
 
162
- # Version info
163
  try:
164
  import huggingface_hub
 
 
165
  results["_info"] = {
166
  "hf_hub_version": huggingface_hub.__version__,
167
- "has__inner_post": hasattr(_get_client(), '_inner_post'),
168
  }
169
  except Exception as e:
170
  results["_info"] = {"error": repr(e)[:200]}
 
9
  import json
10
  import logging
11
  import time
12
+ import inspect
13
 
14
  logger = logging.getLogger(__name__)
15
 
 
37
  def _call_model(repo_id, payload, task=None):
38
  """
39
  Call HF model using InferenceClient._inner_post.
40
+ Tries multiple calling conventions to match the version's signature.
41
  """
42
  client = _get_client()
43
 
44
  if "options" not in payload:
45
  payload["options"] = {"wait_for_model": True}
46
 
47
+ data_bytes = json.dumps(payload).encode("utf-8")
48
+
49
  logger.info("Calling HF model: %s (task=%s)", repo_id, task)
50
 
51
+ # Try different calling conventions for _inner_post
52
+ attempts = [
53
+ # Attempt 1: data as bytes with model and task
54
+ lambda: client._inner_post(data=data_bytes, model=repo_id, task=task),
55
+ # Attempt 2: data as bytes with model only
56
+ lambda: client._inner_post(data=data_bytes, model=repo_id),
57
+ # Attempt 3: positional data with model kwarg
58
+ lambda: client._inner_post(data_bytes, model=repo_id, task=task),
59
+ # Attempt 4: just positional args
60
+ lambda: client._inner_post(data_bytes, repo_id),
61
+ ]
62
+
63
+ last_error = None
64
+ for i, attempt in enumerate(attempts):
65
+ try:
66
+ response = attempt()
67
+ # Parse response
68
+ if isinstance(response, bytes):
69
+ result = json.loads(response.decode("utf-8"))
70
+ elif isinstance(response, str):
71
+ result = json.loads(response)
72
+ else:
73
+ result = response
74
+
75
+ logger.info("HF result for %s (attempt %d): type=%s preview=%s",
76
+ repo_id, i+1, type(result).__name__, str(result)[:200])
77
+ return result
78
+ except TypeError as e:
79
+ logger.warning("_inner_post attempt %d failed: %s", i+1, e)
80
+ last_error = e
81
+ continue
82
+ except Exception as e:
83
+ # Non-TypeError means the call went through but the API returned an error
84
+ logger.error("_inner_post attempt %d API error: %s", i+1, e)
85
+ raise
86
+
87
+ raise RuntimeError("All _inner_post calling conventions failed. Last: " + str(last_error))
88
 
89
 
90
  def _extract_text(result, fallback=""):
 
112
  # ============================================================
113
 
114
  def hf_summarize(text, max_length=128, min_length=30):
 
115
  result = _call_model(SUMMARIZATION_REPO, {
116
  "inputs": text,
117
  "parameters": {"max_length": max_length, "min_length": min_length},
 
120
 
121
 
122
  def hf_correct_spelling(text):
 
123
  result = _call_model(SPELLING_REPO, {"inputs": text})
124
  return _extract_text(result, text)
125
 
126
 
127
  def hf_add_punctuation(text):
 
128
  result = _call_model(PUNCTUATION_REPO, {"inputs": text})
129
  return _extract_text(result, text)
130
 
131
 
132
  def hf_autocomplete(text, n=5):
 
133
  result = _call_model(AUTOCOMPLETE_REPO, {
134
  "inputs": text,
135
  "parameters": {"max_new_tokens": 20},
 
163
  test_text = "هذا نص تجريبي للاختبار"
164
  long_text = (test_text + " ") * 5
165
 
166
+ # Inspect _inner_post signature
167
  try:
168
  import huggingface_hub
169
+ client = _get_client()
170
+ sig = str(inspect.signature(client._inner_post))
171
  results["_info"] = {
172
  "hf_hub_version": huggingface_hub.__version__,
173
+ "_inner_post_signature": sig,
174
  }
175
  except Exception as e:
176
  results["_info"] = {"error": repr(e)[:200]}