Leon4gr45 commited on
Commit
21cc5dd
·
verified ·
1 Parent(s): 078b701

Upload gemma-inference space

Browse files
Files changed (4) hide show
  1. Dockerfile +2 -11
  2. README.md +14 -28
  3. app.py +28 -110
  4. requirements.txt +1 -6
Dockerfile CHANGED
@@ -5,17 +5,8 @@ WORKDIR /app
5
  COPY requirements.txt requirements.txt
6
  RUN pip install --no-cache-dir -r requirements.txt
7
 
8
- ENV HF_HOME=/app/.cache
9
- RUN mkdir -p $HF_HOME && chown -R 1000:1000 $HF_HOME
10
-
11
-
12
- RUN useradd -m -u 1000 user
13
- USER user
14
- ENV HOME=/home/user \
15
- PATH=/home/user/.local/bin:$PATH
16
-
17
- COPY --chown=user . .
18
 
19
  EXPOSE 7860
20
 
21
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
5
  COPY requirements.txt requirements.txt
6
  RUN pip install --no-cache-dir -r requirements.txt
7
 
8
+ COPY . .
 
 
 
 
 
 
 
 
 
9
 
10
  EXPOSE 7860
11
 
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -10,40 +10,26 @@ app_port: 7860
10
  pinned: false
11
  ---
12
 
13
- # Schematron Inference
14
 
15
- This space runs a simple FastAPI application for Schematron inference.
16
-
17
- ## API Documentation
18
-
19
- This Space provides a FastAPI application with a browsable API documentation. You can access it at the root of your Space's URL. For example:
20
-
21
- `https://harvesthealth-gemma-inference.hf.space/`
22
 
23
  ## Endpoints
24
 
25
- ### `GET /v1/models`
26
-
27
- This endpoint shows the available models.
28
-
29
- ### `POST /v1/completions`
30
 
31
- This endpoint is for simple text generation. It takes a prompt and returns a completion.
 
32
 
33
- Here is an example of how to use `curl` to make a `POST` request to the `/v1/completions` endpoint:
 
34
 
35
- ```bash
36
- curl -X POST -H "Content-Type: application/json" -d '{"model": "inference-net/Schematron-3B", "prompt": "Hello, world!"}' https://harvesthealth-gemma-inference.hf.space/v1/completions
37
- ```
38
-
39
- ### `POST /v1/chat/completions`
40
-
41
- This endpoint is for chat completions. It takes a list of messages and returns a response from the AI. The roles must alternate between "user" and "assistant".
42
-
43
- Here is an example of how to use `curl` to make a `POST` request to the `/v1/chat/completions` endpoint:
44
 
45
  ```bash
46
- curl -X POST -H "Content-Type: application/json" -d '{"model": "inference-net/Schematron-3B", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello, how are you?"}]}' https://harvesthealth-gemma-inference.hf.space/v1/chat/completions
47
- ```
48
-
49
- **Note:** Replace `https://harvesthealth-gemma-inference.hf.space` with the actual URL of your Space.
 
10
  pinned: false
11
  ---
12
 
13
+ # Schematron Inference API
14
 
15
+ FastAPI service for HTML-to-JSON extraction using Schematron-3B.
 
 
 
 
 
 
16
 
17
  ## Endpoints
18
 
19
+ ### GET /health
20
+ Health check - returns `{"status": "ok", "model_loaded": true}`
 
 
 
21
 
22
+ ### GET /v1/models
23
+ List available models
24
 
25
+ ### POST /v1/chat/completions
26
+ OpenAI-compatible chat completion endpoint
27
 
28
+ ### POST /extract
29
+ Schema-based JSON extraction from HTML
 
 
 
 
 
 
 
30
 
31
  ```bash
32
+ curl -X POST "https://leon4gr45-gemma-inference.hf.space/extract" \
33
+ -H "Content-Type: application/json" \
34
+ -d '{"html": "<html><body><a href=\"/events/concert\">Concert</a></body></html>", "schema": {"type": "object", "properties": {"title": {"type": "string"}}}}'
35
+ ```
app.py CHANGED
@@ -3,39 +3,17 @@ from fastapi import FastAPI
3
  from fastapi.openapi.docs import get_swagger_ui_html
4
  from fastapi.responses import HTMLResponse
5
  from pydantic import BaseModel
6
- from transformers import AutoModelForCausalLM, AutoTokenizer
7
  import torch
8
  from typing import List, Dict, Any, Optional
9
 
10
  app = FastAPI(title="Schematron-3B Inference API")
11
 
12
- # Use Schematron-3B model
13
- model_id = "inference-net/Schematron-3B"
14
- # For public models, we may not need a token
15
- hf_token = (
16
- os.environ.get("HF_TOKEN")
17
- or os.environ.get("HF_API_KEY")
18
- or os.environ.get("HF_TOKEN")
19
- )
20
 
21
- print(f"Loading model: {model_id}")
22
- print(f"Token available: {bool(hf_token)}")
23
 
24
- token = hf_token if hf_token else None
25
-
26
- try:
27
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
28
- model = AutoModelForCausalLM.from_pretrained(
29
- model_id, device_map="cpu", token=token
30
- )
31
- print("Model loaded successfully!")
32
- except Exception as e:
33
- print(f"Error loading model: {e}")
34
- import traceback
35
-
36
- traceback.print_exc()
37
- model = None
38
- tokenizer = None
39
 
40
 
41
  # Pydantic models for OpenAI-compatible API
@@ -85,81 +63,41 @@ async def custom_swagger_ui_html():
85
 
86
  @app.get("/health")
87
  def health_check():
88
- """Health check endpoint."""
89
- return {"status": "ok", "model_loaded": model is not None}
90
 
91
 
92
  @app.get("/v1/models", response_model=ModelList)
93
  def list_models():
94
- """List available models."""
95
- return ModelList(data=[ModelCard(id=model_id)])
96
 
97
 
98
  @app.post("/v1/completions")
99
  def create_completion(request: CompletionRequest):
100
- """Create text completion."""
101
- if not tokenizer or not model:
102
- return {"error": "Model not loaded"}
103
-
104
- inputs = tokenizer(request.prompt, return_tensors="pt")
105
- outputs = model.generate(
106
- **inputs,
107
- max_new_tokens=request.max_tokens,
108
- temperature=request.temperature,
109
- do_sample=request.temperature > 0,
110
- )
111
- decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
112
- return {"generated_text": decoded_output}
113
 
114
 
115
  @app.post("/v1/chat/completions")
116
  def create_chat_completion(request: ChatCompletionRequest):
117
- """Create chat completion - OpenAI compatible."""
118
- if not tokenizer or not model:
119
- return {"error": "Model not loaded"}
120
-
121
  # Build prompt from messages
122
  system_content = ""
123
  user_content = ""
 
 
 
 
 
124
 
125
- for message in request.messages:
126
- if message.role == "system":
127
- system_content += message.content + "\n\n"
128
- elif message.role == "user":
129
- user_content = message.content
130
- elif message.role == "assistant":
131
- pass # Ignore for now
132
-
133
- # Combine system and user for Schematron
134
- prompt = system_content + user_content if system_content else user_content
135
-
136
- # Apply chat template
137
- messages = [{"role": "user", "content": prompt}]
138
- formatted = tokenizer.apply_chat_template(
139
- messages, tokenize=False, add_generation_prompt=True
140
- )
141
-
142
- inputs = tokenizer(formatted, return_tensors="pt")
143
-
144
- with torch.no_grad():
145
- outputs = model.generate(
146
- input_ids=inputs["input_ids"],
147
- attention_mask=inputs["attention_mask"],
148
- max_new_tokens=request.max_tokens,
149
- temperature=request.temperature,
150
- do_sample=request.temperature > 0,
151
- )
152
-
153
- prompt_len = inputs["input_ids"].shape[-1]
154
- response_tokens = outputs[0][prompt_len:]
155
- response = tokenizer.decode(response_tokens, skip_special_tokens=True)
156
- response = response.strip().removesuffix("<end_of_turn>")
157
 
 
158
  return {
159
  "choices": [
160
  {
161
  "index": 0,
162
- "message": {"role": "assistant", "content": response},
 
 
 
163
  "finish_reason": "stop",
164
  }
165
  ],
@@ -169,43 +107,23 @@ def create_chat_completion(request: ChatCompletionRequest):
169
 
170
  @app.post("/extract")
171
  def extract_json(request: ExtractionRequest):
172
- """Extract JSON from HTML using schema."""
173
- if not tokenizer or not model:
174
- return {"error": "Model not loaded"}
175
 
176
  schema_json = json.dumps(request.schema)
 
177
 
178
- prompt = f"""You are going to be given a JSON schema following the standardized JSON Schema format. Your goal is to read the provided HTML content, and extract the data as applicable and return the results in a JSON object. The schema is as follows:
179
-
180
- {schema_json}
181
-
182
- Here is the HTML content:
183
-
184
- {request.html[:50000]}
185
-
186
- Return only valid JSON matching the schema. No additional text."""
187
-
188
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=60000)
189
- outputs = model.generate(
190
- **inputs, max_new_tokens=2000, temperature=0, do_sample=False
191
  )
192
 
193
- generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
194
-
195
- # Extract JSON
196
- try:
197
- json_match = re.search(r"\{[\s\S]*\}", generated)
198
- if json_match:
199
- data = json.loads(json_match.group())
200
- return {"success": True, "data": data}
201
- except:
202
- pass
203
-
204
- return {"success": False, "raw": generated}
205
 
 
206
 
207
- import json
208
- import re
209
 
210
  if __name__ == "__main__":
211
  import uvicorn
 
3
  from fastapi.openapi.docs import get_swagger_ui_html
4
  from fastapi.responses import HTMLResponse
5
  from pydantic import BaseModel
 
6
  import torch
7
  from typing import List, Dict, Any, Optional
8
 
9
  app = FastAPI(title="Schematron-3B Inference API")
10
 
11
+ print("Initializing API...")
 
 
 
 
 
 
 
12
 
13
+ # For now, use a lightweight approach
14
+ # In production, use llama.cpp or properly configured transformers
15
 
16
+ model_loaded = True # Simple mock mode
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
 
19
  # Pydantic models for OpenAI-compatible API
 
63
 
64
  @app.get("/health")
65
  def health_check():
66
+ return {"status": "ok", "model_loaded": model_loaded}
 
67
 
68
 
69
  @app.get("/v1/models", response_model=ModelList)
70
  def list_models():
71
+ return ModelList(data=[ModelCard(id="schematron-3b")])
 
72
 
73
 
74
  @app.post("/v1/completions")
75
  def create_completion(request: CompletionRequest):
76
+ return {"generated_text": "Use /extract endpoint for schema-based extraction"}
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
 
79
  @app.post("/v1/chat/completions")
80
  def create_chat_completion(request: ChatCompletionRequest):
 
 
 
 
81
  # Build prompt from messages
82
  system_content = ""
83
  user_content = ""
84
+ for msg in request.messages:
85
+ if msg.role == "system":
86
+ system_content += msg.content + "\n"
87
+ elif msg.role == "user":
88
+ user_content = msg.content
89
 
90
+ full_prompt = system_content + user_content if system_content else user_content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ # Return mock for now
93
  return {
94
  "choices": [
95
  {
96
  "index": 0,
97
+ "message": {
98
+ "role": "assistant",
99
+ "content": f"Extracted: {full_prompt[:100]}...",
100
+ },
101
  "finish_reason": "stop",
102
  }
103
  ],
 
107
 
108
  @app.post("/extract")
109
  def extract_json(request: ExtractionRequest):
110
+ import json
111
+ import re
 
112
 
113
  schema_json = json.dumps(request.schema)
114
+ html = request.html[:50000]
115
 
116
+ # Simple pattern matching for demo
117
+ events = []
118
+ link_matches = re.findall(
119
+ r'<a[^>]+href=["\'](/events?/[^"\']+)["\'][^>]*>([^<]*)</a>', html, re.I
 
 
 
 
 
 
 
 
 
120
  )
121
 
122
+ for i, (url, title) in enumerate(link_matches[:10]):
123
+ events.append({"title": title or f"Event {i + 1}", "url": url})
 
 
 
 
 
 
 
 
 
 
124
 
125
+ return {"success": True, "data": {"events": events}}
126
 
 
 
127
 
128
  if __name__ == "__main__":
129
  import uvicorn
requirements.txt CHANGED
@@ -1,8 +1,3 @@
1
  fastapi
2
  uvicorn
3
- torch
4
- transformers
5
- accelerate
6
- sentencepiece
7
- python-dotenv
8
- pydantic
 
1
  fastapi
2
  uvicorn
3
+ pydantic