Download app.py from anjomj/ai_model: direct link, hf CLI and curl.
- Browser
- Download file 5.27 kB
-
https://huggingface.co/spaces/anjomj/ai_model/resolve/main/app.py
- Command line
-
hf download hf://spaces/anjomj/ai_model/app.py
-
curl -L -o app.py https://huggingface.co/spaces/anjomj/ai_model/resolve/main/app.py
5.27 kB
| import os | |
| import json | |
| from threading import Thread | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from fastapi import Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import StreamingResponse | |
| from transformers import ( | |
| AutoModelForImageTextToText, | |
| AutoProcessor, | |
| AutoTokenizer, | |
| TextIteratorStreamer, | |
| ) | |
| MODEL_ID = os.getenv("MODEL_ID", "google/gemma-4-E2B-it") | |
| HF_TOKEN = os.getenv("HF_TOKEN", None) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.bfloat16 if device == "cuda" else torch.float32 | |
| print(f"Loading {MODEL_ID} locally on {device} ({dtype})...") | |
| try: | |
| processor = AutoProcessor.from_pretrained(MODEL_ID, token=HF_TOKEN) | |
| tokenizer = processor.tokenizer | |
| except Exception as e: | |
| print(f"AutoProcessor fallback to AutoTokenizer: {e}") | |
| processor = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN) | |
| tokenizer = processor | |
| model = AutoModelForImageTextToText.from_pretrained( | |
| MODEL_ID, | |
| torch_dtype=dtype, | |
| device_map="auto", | |
| token=HF_TOKEN, | |
| ).eval() | |
| def clean_gemma_stream_chunk(text: str) -> str: | |
| """Keep thought channel markers so the frontend can split Thought vs Text vs Code blocks.""" | |
| for tok in ["", "", "<|turn>model\n", "<|turn>model", ""]: | |
| text = text.replace(tok, "") | |
| return text | |
| def generate_response( | |
| message: str, | |
| history: list, | |
| enable_thinking: bool = True, | |
| max_new_tokens: int = 1024, | |
| temperature: float = 1.0, | |
| ): | |
| messages = [] | |
| sys_prompt = "You are Gemma 4, a helpful, clear, and thoughtful AI assistant. Use markdown and fenced code blocks with language tags for any code." | |
| if enable_thinking: | |
| sys_prompt = "<|think|>" + sys_prompt | |
| messages.append({ | |
| "role": "system", | |
| "content": [{"type": "text", "text": sys_prompt}], | |
| }) | |
| if history: | |
| for turn in history: | |
| if isinstance(turn, dict) and "role" in turn: | |
| content = turn["content"] | |
| if isinstance(content, str): | |
| content = [{"type": "text", "text": content}] | |
| messages.append({"role": turn["role"], "content": content}) | |
| elif isinstance(turn, (list, tuple)) and len(turn) == 2: | |
| u, a = turn | |
| if u: | |
| messages.append({"role": "user", "content": [{"type": "text", "text": str(u)}]}) | |
| if a: | |
| messages.append({"role": "assistant", "content": [{"type": "text", "text": str(a)}]}) | |
| messages.append({ | |
| "role": "user", | |
| "content": [{"type": "text", "text": message}], | |
| }) | |
| inputs = processor.apply_chat_template( | |
| messages, | |
| tokenize=True, | |
| add_generation_prompt=True, | |
| return_dict=True, | |
| return_tensors="pt", | |
| ).to(model.device) | |
| # IMPORTANT: skip_special_tokens=False preserves <|channel>thought ... | |
| # so the custom UI can render the Thought Process in its own collapsible card! | |
| streamer = TextIteratorStreamer( | |
| tokenizer, | |
| skip_prompt=True, | |
| skip_special_tokens=False, | |
| ) | |
| temp = float(temperature) | |
| generation_kwargs = dict( | |
| **inputs, | |
| streamer=streamer, | |
| max_new_tokens=int(max_new_tokens), | |
| do_sample=temp > 0.0, | |
| temperature=temp if temp > 0.0 else None, | |
| top_p=0.95 if temp > 0.0 else None, | |
| top_k=64 if temp > 0.0 else None, | |
| ) | |
| thread = Thread(target=model.generate, kwargs=generation_kwargs) | |
| thread.start() | |
| partial_text = "" | |
| for new_text in streamer: | |
| partial_text += clean_gemma_stream_chunk(new_text) | |
| yield partial_text | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(f"# 💎 {MODEL_ID} — Public Local Inference Space") | |
| with gr.Row(): | |
| enable_thinking = gr.Checkbox(label="Enable Thinking (<|think|>)", value=True) | |
| max_new_tokens = gr.Slider(64, 4096, value=1024, step=64, label="Max New Tokens") | |
| temperature = gr.Slider(0.0, 1.5, value=1.0, step=0.05, label="Temperature") | |
| gr.ChatInterface( | |
| fn=generate_response, | |
| additional_inputs=[enable_thinking, max_new_tokens, temperature], | |
| api_name="chat_api", | |
| ) | |
| # Enable unrestricted public CORS so your external Chat UI can call this Space directly | |
| demo.queue() | |
| app = demo.app | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def public_chat_endpoint(req: Request): | |
| body = await req.json() | |
| message = body.get("message", "") | |
| history = body.get("history", []) | |
| enable_thinking = body.get("enable_thinking", True) | |
| max_new_tokens = body.get("max_new_tokens", 1024) | |
| temperature = body.get("temperature", 1.0) | |
| def event_stream(): | |
| for snapshot in generate_response( | |
| message, history, enable_thinking, max_new_tokens, temperature | |
| ): | |
| yield f"data: {json.dumps({'text': snapshot})}\n\n" | |
| yield "data: [DONE]\n\n" | |
| return StreamingResponse(event_stream(), media_type="text/event-stream") | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |