-
Notifications
You must be signed in to change notification settings - Fork 285
misc: add GLiNER2 Modal demo (extract_json + classify_text) #1530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vish86
wants to merge
4
commits into
modal-labs:main
Choose a base branch
from
vish86:misc/add-gliner2-modal-demo
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # # GLiNER2 on Modal | ||
| # | ||
| # [GLiNER2](https://github.com/fastino-ai/GLiNER2) structured extraction (`extract_json`) and | ||
| # classification (`classify_text`) on one string. From the repo root: | ||
| # `modal run misc/gliner2_modal_demo.py` | ||
|
|
||
| import json | ||
|
|
||
| import modal | ||
|
|
||
| APP_NAME = "example-gliner2-modal" | ||
| MODEL_ID = "fastino/gliner2-base-v1" | ||
| DEFAULT_TEXT = ( | ||
| "Tim Cook unveiled iPhone 15 Pro for $999 in Cupertino; " | ||
| "reviewers praised the titanium design but criticized battery life." | ||
| ) | ||
| SCHEMA = { | ||
| "announcement": [ | ||
| "company::str", | ||
| "person::str", | ||
| "product::str", | ||
| "price::str", | ||
| "location::str", | ||
| ] | ||
| } | ||
| CLS = {"sentiment": ["positive", "negative", "neutral", "mixed"]} | ||
|
|
||
| app = modal.App(APP_NAME) | ||
| image = modal.Image.debian_slim(python_version="3.11").pip_install( | ||
| "gliner2", | ||
| "torch>=2.0.0", | ||
| "transformers>=4.51.3,<5.2.0", | ||
| "huggingface_hub>=0.21.4", | ||
| "tqdm", | ||
| "sentencepiece", | ||
| "onnxruntime", | ||
| "requests", | ||
| "urllib3", | ||
| "certifi", | ||
| "charset-normalizer", | ||
| "idna", | ||
| "safetensors", | ||
| "tokenizers", | ||
| "filelock", | ||
| "packaging", | ||
| ) | ||
|
|
||
|
|
||
| @app.cls(image=image, cpu=2.0, memory=2048) | ||
| class GLiNERService: | ||
| @modal.enter() | ||
| def load(self): | ||
| from gliner2 import GLiNER2 | ||
|
|
||
| self.model = GLiNER2.from_pretrained(MODEL_ID) | ||
|
|
||
| @modal.method() | ||
| def analyze(self, text: str) -> dict: | ||
| m = self.model | ||
| return { | ||
| "structured": m.extract_json(text, SCHEMA), | ||
| "classification": m.classify_text(text, CLS, include_confidence=True), | ||
| } | ||
|
|
||
|
|
||
| @app.local_entrypoint() | ||
| def main(text: str = DEFAULT_TEXT): | ||
| print("Input:", text) | ||
| print(json.dumps(GLiNERService().analyze.remote(text), indent=2)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| # --- | ||
| # cmd: ["python", "misc/kafka_microbatch_etl.py", "--batch=25", "--timeout-s=5", "--local=true"] | ||
| # runtimes: ["runc", "gvisor"] | ||
| # --- | ||
| # | ||
| # # Kafka micro-batch ETL (bounded) | ||
| # | ||
| # Polls up to N Kafka messages (or time limit), applies a tiny transform, | ||
| # POSTs the batch to a REST sink, then exits. | ||
| # | ||
| # Intended for ETL/backfills/periodic jobs — NOT continuous stream processing | ||
| # (e.g. Flink / Kafka Streams). This example is intentionally single-worker. | ||
|
|
||
| import json | ||
| import os | ||
| import time | ||
|
|
||
| import modal | ||
| import requests | ||
| from confluent_kafka import Consumer | ||
vish86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| image = modal.Image.debian_slim().pip_install("confluent-kafka", "requests") | ||
| app = modal.App( | ||
| "kafka-microbatch-etl", | ||
| image=image, | ||
| secrets=[modal.Secret.from_name("kafka-etl-remote-v2")], | ||
| ) | ||
|
|
||
|
|
||
| @app.function() | ||
| def etl(batch: int = 100, timeout_s: int = 5): | ||
| c = Consumer( | ||
| { | ||
| "bootstrap.servers": os.environ["KAFKA_BOOTSTRAP"], | ||
| "group.id": os.getenv("KAFKA_GROUP", "modal-microbatch"), | ||
| "auto.offset.reset": "earliest", | ||
| "enable.auto.commit": False, # keep example safe/simple | ||
| # Confluent Cloud auth: | ||
| "security.protocol": "SASL_SSL", | ||
| "sasl.mechanism": "PLAIN", | ||
| "sasl.username": os.environ["KAFKA_API_KEY"], | ||
| "sasl.password": os.environ["KAFKA_API_SECRET"], | ||
| } | ||
| ) | ||
| c.subscribe([os.environ["KAFKA_TOPIC"]]) | ||
|
|
||
| rows, end = [], time.time() + timeout_s | ||
| while len(rows) < batch and time.time() < end: | ||
| m = c.poll(0.5) | ||
| if not m or m.error(): | ||
| continue | ||
| rows.append( | ||
| { | ||
| "ts": m.timestamp()[1], | ||
| "payload": json.loads(m.value().decode("utf-8")), | ||
| } | ||
| ) | ||
| c.close() | ||
|
|
||
| if rows: | ||
| url = os.getenv("SINK_URL", "https://httpbin.org/post") | ||
| requests.post( | ||
| url, json={"count": len(rows), "rows": rows}, timeout=10 | ||
| ).raise_for_status() | ||
| return {"sent": len(rows)} | ||
|
|
||
|
|
||
| @app.local_entrypoint() | ||
| def main(batch: int = 100, timeout_s: int = 5, local: bool = False): | ||
| fn = etl.local if local else etl.remote | ||
| print(fn(batch=batch, timeout_s=timeout_s)) | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Frontmatter
cmdusespythonbut file has noif __name__ == "__main__"blockThe frontmatter specifies
cmd: ["python", "misc/kafka_microbatch_etl.py", ...], but the file uses@app.local_entrypoint()(line 68) with noif __name__ == "__main__"block. Running withpythondirectly will import the module and exit without executing anything —@app.local_entrypoint()is only invoked bymodal run. Every other example in this repo that usescmd: ["python", ...]has aif __name__ == "__main__"block (e.g.,06_gpu_and_ml/gpu_snapshot.py:62,misc/queue_simple.py:51). The documented command silently does nothing.Was this helpful? React with 👍 or 👎 to provide feedback.