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

fix: Construct RequestParameters properly using inspect.signature

Browse files
Files changed (1) hide show
  1. src/hf_inference.py +56 -47
src/hf_inference.py CHANGED
@@ -1,8 +1,8 @@
1
  """
2
  HuggingFace Inference API client for Bayan models.
3
 
4
- Uses huggingface_hub.InferenceClient._inner_post (v1.19.0) which handles
5
- internal routing inside HF Spaces.
6
  """
7
 
8
  import os
@@ -16,6 +16,7 @@ logger = logging.getLogger(__name__)
16
  HF_API_TOKEN = os.environ.get("HF_API_TOKEN", "")
17
 
18
  _client = None
 
19
 
20
 
21
  def _get_client():
@@ -23,10 +24,17 @@ def _get_client():
23
  if _client is None:
24
  from huggingface_hub import InferenceClient
25
  _client = InferenceClient(token=HF_API_TOKEN if HF_API_TOKEN else None)
26
- logger.info("InferenceClient v1.19.0 initialized")
27
  return _client
28
 
29
 
 
 
 
 
 
 
 
 
30
  # Repository IDs
31
  SUMMARIZATION_REPO = os.environ.get("SUMMARIZATION_REPO_ID", "bayan10/summarization-model")
32
  SPELLING_REPO = os.environ.get("SPELLING_REPO_ID", "bayan10/AraSpell-Model")
@@ -36,55 +44,55 @@ AUTOCOMPLETE_REPO = os.environ.get("AUTOCOMPLETE_REPO_ID", "bayan10/AutoComplete
36
 
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=""):
@@ -163,17 +171,18 @@ def debug_test_all_models():
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]}
177
 
178
  for name, fn, args in [
179
  ("summarization", hf_summarize, (long_text, 30, 10)),
 
1
  """
2
  HuggingFace Inference API client for Bayan models.
3
 
4
+ Uses huggingface_hub.InferenceClient._inner_post with RequestParameters
5
+ (v1.19.0) for internal routing inside HF Spaces.
6
  """
7
 
8
  import os
 
16
  HF_API_TOKEN = os.environ.get("HF_API_TOKEN", "")
17
 
18
  _client = None
19
+ _RequestParameters = None
20
 
21
 
22
  def _get_client():
 
24
  if _client is None:
25
  from huggingface_hub import InferenceClient
26
  _client = InferenceClient(token=HF_API_TOKEN if HF_API_TOKEN else None)
 
27
  return _client
28
 
29
 
30
+ def _get_request_params_class():
31
+ global _RequestParameters
32
+ if _RequestParameters is None:
33
+ from huggingface_hub.inference._common import RequestParameters
34
+ _RequestParameters = RequestParameters
35
+ return _RequestParameters
36
+
37
+
38
  # Repository IDs
39
  SUMMARIZATION_REPO = os.environ.get("SUMMARIZATION_REPO_ID", "bayan10/summarization-model")
40
  SPELLING_REPO = os.environ.get("SPELLING_REPO_ID", "bayan10/AraSpell-Model")
 
44
 
45
  def _call_model(repo_id, payload, task=None):
46
  """
47
+ Call HF model using _inner_post with RequestParameters.
 
48
  """
49
  client = _get_client()
50
+ RP = _get_request_params_class()
51
 
52
  if "options" not in payload:
53
  payload["options"] = {"wait_for_model": True}
54
 
55
  data_bytes = json.dumps(payload).encode("utf-8")
 
56
  logger.info("Calling HF model: %s (task=%s)", repo_id, task)
57
 
58
+ # Construct RequestParameters - try with fields we know
59
+ try:
60
+ # Inspect what fields RequestParameters accepts
61
+ sig = inspect.signature(RP)
62
+ params = sig.parameters
63
+ logger.info("RequestParameters fields: %s", list(params.keys()))
64
+
65
+ # Build kwargs based on what's available
66
+ rp_kwargs = {}
67
+ if "model" in params:
68
+ rp_kwargs["model"] = repo_id
69
+ if "task" in params and task:
70
+ rp_kwargs["task"] = task
71
+ if "data" in params:
72
+ rp_kwargs["data"] = data_bytes
73
+ if "json" in params:
74
+ rp_kwargs["json"] = payload
75
+
76
+ rp = RP(**rp_kwargs)
77
+ response = client._inner_post(rp)
78
+
79
+ except Exception as e:
80
+ logger.warning("RequestParameters construction failed: %s", e)
81
+ # Last resort: try creating with just positional arg
82
+ rp = RP(data_bytes)
83
+ response = client._inner_post(rp)
84
+
85
+ # Parse response
86
+ if isinstance(response, bytes):
87
+ result = json.loads(response.decode("utf-8"))
88
+ elif isinstance(response, str):
89
+ result = json.loads(response)
90
+ else:
91
+ result = response
 
92
 
93
+ logger.info("HF result for %s: type=%s preview=%s",
94
+ repo_id, type(result).__name__, str(result)[:200])
95
+ return result
96
 
97
 
98
  def _extract_text(result, fallback=""):
 
171
  test_text = "هذا نص تجريبي للاختبار"
172
  long_text = (test_text + " ") * 5
173
 
 
174
  try:
175
  import huggingface_hub
176
+ RP = _get_request_params_class()
177
+ rp_sig = str(inspect.signature(RP))
178
+ rp_fields = list(inspect.signature(RP).parameters.keys())
179
  results["_info"] = {
180
  "hf_hub_version": huggingface_hub.__version__,
181
+ "RequestParameters_signature": rp_sig[:300],
182
+ "RequestParameters_fields": rp_fields,
183
  }
184
  except Exception as e:
185
+ results["_info"] = {"error": repr(e)[:300]}
186
 
187
  for name, fn, args in [
188
  ("summarization", hf_summarize, (long_text, 30, 10)),