Spaces:
Sleeping
Sleeping
Download app.py from mathanmithun/dhigrowth_api: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/mathanmithun/dhigrowth_api/resolve/main/app.py
- Command line
-
hf download hf://spaces/mathanmithun/dhigrowth_api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mathanmithun/dhigrowth_api/resolve/main/app.py
10.5 kB
| import subprocess | |
| import os | |
| import logging | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # Detect if running in Docker/container environment | |
| IS_DOCKER = os.path.exists("/llama.cpp") or os.environ.get("DOCKER_CONTAINER", "").lower() == "true" | |
| if IS_DOCKER: | |
| # Docker/container paths | |
| MODEL_PATH = "model/lfm2-q5_km.gguf" | |
| LLAMA_BIN = "/llama.cpp/build/bin/llama-cli" | |
| else: | |
| # Local development paths | |
| MODEL_PATH = os.path.join(os.path.dirname(__file__), "model", "lfm2-q5_km.gguf") | |
| LLAMA_BIN = os.path.join(os.path.dirname(__file__), "llama.cpp", "build", "bin", "llama-cli") | |
| # For Windows compatibility | |
| if os.name == 'nt': | |
| LLAMA_BIN += ".exe" | |
| # Windows Release build puts binaries in Release subdirectory | |
| release_path = LLAMA_BIN.replace("bin\\llama-cli.exe", "bin\\Release\\llama-cli.exe") | |
| if os.path.exists(release_path): | |
| LLAMA_BIN = release_path | |
| SYSTEM_PROMPT = "<|startoftext|><|im_start|>system\nYou are a helpful assistant trained by Liquid AI.<|im_end|>\n" | |
| app = Flask(__name__) | |
| CORS(app) # Enable CORS for cross-origin requests | |
| def validate_paths(): | |
| """Validate that required files exist""" | |
| errors = [] | |
| if not os.path.exists(MODEL_PATH): | |
| errors.append(f"Model not found at: {MODEL_PATH}") | |
| if not os.path.exists(LLAMA_BIN): | |
| errors.append(f"llama-cli not found at: {LLAMA_BIN}") | |
| return errors | |
| def generate_text(user_prompt, ctx_size=4096, threads=2, temp=0.3, min_p=0.15, | |
| repeat_penalty=1.05, max_tokens=512): | |
| """ | |
| Generate text using llama.cpp | |
| Args: | |
| user_prompt: The user's input prompt | |
| ctx_size: Context window size | |
| threads: Number of threads to use | |
| temp: Temperature for sampling | |
| min_p: Minimum probability threshold | |
| repeat_penalty: Repetition penalty | |
| max_tokens: Maximum number of tokens to generate | |
| Returns: | |
| Generated text response | |
| """ | |
| # Format prompt according to LFM2 ChatML format | |
| prompt = ( | |
| SYSTEM_PROMPT | |
| + f"<|im_start|>user\n{user_prompt}<|im_end|>\n" | |
| + "<|im_start|>assistant\n" | |
| ) | |
| cmd = [ | |
| LLAMA_BIN, | |
| "-m", MODEL_PATH, | |
| "--ctx-size", str(ctx_size), | |
| "--threads", str(threads), | |
| "--temp", str(temp), | |
| "--min-p", str(min_p), | |
| "--repeat-penalty", str(repeat_penalty), | |
| "-n", str(max_tokens), | |
| "-p", prompt, | |
| "--no-display-prompt", # Don't echo the prompt | |
| "--simple-io", # Use simple IO for cleaner output | |
| "-no-cnv" # Disable conversation mode for cleaner output | |
| ] | |
| try: | |
| logger.info(f"Running inference with prompt length: {len(prompt)}") | |
| logger.info(f"Command: {' '.join(cmd[:5])}...") # Log first part of command | |
| # Use Popen for better control and to handle stderr separately | |
| process = subprocess.Popen( | |
| cmd, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| text=True, | |
| encoding='utf-8', | |
| errors='ignore', | |
| bufsize=1 # Line buffered | |
| ) | |
| try: | |
| stdout, stderr = process.communicate(timeout=300) # 5 minute timeout | |
| except subprocess.TimeoutExpired: | |
| process.kill() | |
| stdout, stderr = process.communicate() | |
| logger.error(f"Inference timed out. stderr: {stderr[:200] if stderr else 'None'}") | |
| raise Exception("Inference timed out after 5 minutes") | |
| if process.returncode != 0: | |
| error_msg = stderr or stdout or "Unknown error" | |
| logger.error(f"llama.cpp exited with code {process.returncode}") | |
| logger.error(f"Error output: {error_msg[:500]}") | |
| raise Exception(f"Inference failed: {error_msg[:500]}") | |
| # Log stderr for debugging (contains model loading info) | |
| if stderr: | |
| logger.debug(f"llama.cpp stderr (first 200 chars): {stderr[:200]}") | |
| # Extract the generated text from output | |
| output = stdout.strip() if stdout else "" | |
| # The output may contain the prompt echoed back, metadata, and the response | |
| # Look for the assistant tag and extract everything after it | |
| assistant_marker = "<|im_start|>assistant\n" | |
| if assistant_marker in output: | |
| # Extract everything after the assistant marker | |
| response = output.split(assistant_marker, 1)[-1] | |
| elif prompt in output: | |
| # Fallback: if prompt is in output, get everything after it | |
| response = output.split(prompt, 1)[-1] | |
| else: | |
| # If neither marker found, use the whole output (might be just the response) | |
| response = output | |
| # Clean up: remove any trailing metadata or performance info | |
| # Look for common patterns that indicate end of generation | |
| lines = response.split('\n') | |
| cleaned_lines = [] | |
| for line in lines: | |
| # Stop at performance info or metadata markers | |
| if any(marker in line.lower() for marker in [ | |
| 'common_perf_print', | |
| 'llama_memory_breakdown', | |
| 'sampler seed:', | |
| 'sampler params:', | |
| 'generate:', | |
| 'system_info:', | |
| 'load:', | |
| 'llama_model_loader:', | |
| 'print_info:' | |
| ]): | |
| break | |
| cleaned_lines.append(line) | |
| response = '\n'.join(cleaned_lines).strip() | |
| # Remove any remaining prompt fragments | |
| if prompt[:50] in response: # Check first 50 chars to avoid full prompt match issues | |
| response = response.replace(prompt[:50], "").strip() | |
| # Remove common end markers | |
| response = response.replace("[end of text]", "").strip() | |
| response = response.replace("<|endoftext|>", "").strip() | |
| response = response.replace("<|im_end|>", "").strip() | |
| if not response: | |
| logger.warning("Empty response from llama.cpp") | |
| # If output is empty, check stderr for clues | |
| if stderr: | |
| logger.warning(f"stderr content: {stderr[:300]}") | |
| response = "No response generated" | |
| logger.info(f"Generated response length: {len(response)}") | |
| return response | |
| except subprocess.TimeoutExpired: | |
| logger.error("Inference timed out") | |
| raise Exception("Inference timed out after 5 minutes") | |
| except Exception as e: | |
| error_msg = str(e) | |
| logger.error(f"Error during inference: {error_msg}") | |
| # Don't re-raise if it's already our custom exception | |
| if "timed out" in error_msg or "Inference failed" in error_msg: | |
| raise | |
| raise Exception(f"Unexpected error during inference: {error_msg}") | |
| def generate(): | |
| """Generate text from user prompt""" | |
| try: | |
| data = request.get_json(force=True) | |
| if not data: | |
| return jsonify({"error": "No JSON data provided"}), 400 | |
| user_prompt = data.get("prompt", "") | |
| if not user_prompt: | |
| return jsonify({"error": "Prompt is required"}), 400 | |
| # Optional parameters with defaults (conservative for free tier) | |
| ctx_size = int(data.get("ctx_size", 4096)) | |
| threads = int(data.get("threads", 2)) | |
| temp = float(data.get("temp", 0.3)) | |
| min_p = float(data.get("min_p", 0.15)) | |
| repeat_penalty = float(data.get("repeat_penalty", 1.05)) | |
| max_tokens = int(data.get("max_tokens", 512)) | |
| # Enforce limits for free tier safety | |
| ctx_size = min(ctx_size, 4096) | |
| threads = min(threads, 4) | |
| max_tokens = min(max_tokens, 512) | |
| response = generate_text( | |
| user_prompt, | |
| ctx_size=ctx_size, | |
| threads=threads, | |
| temp=temp, | |
| min_p=min_p, | |
| repeat_penalty=repeat_penalty, | |
| max_tokens=max_tokens | |
| ) | |
| return jsonify({"response": response}) | |
| except ValueError as e: | |
| return jsonify({"error": f"Invalid parameter: {str(e)}"}), 400 | |
| except Exception as e: | |
| logger.error(f"Error in /generate: {str(e)}") | |
| return jsonify({"error": str(e)}), 500 | |
| def health(): | |
| """Health check endpoint""" | |
| errors = validate_paths() | |
| if errors: | |
| return jsonify({ | |
| "status": "error", | |
| "errors": errors | |
| }), 503 | |
| return jsonify({ | |
| "status": "ok", | |
| "model_path": MODEL_PATH, | |
| "llama_bin": LLAMA_BIN, | |
| "environment": "docker" if IS_DOCKER else "local" | |
| }) | |
| def root(): | |
| """Root endpoint with API information""" | |
| return jsonify({ | |
| "service": "LFM2 GGUF Backend", | |
| "version": "1.0.0", | |
| "status": "✅ LFM2 GGUF server is running", | |
| "endpoints": { | |
| "POST /generate": "Generate text from a prompt", | |
| "GET /health": "Check service health" | |
| }, | |
| "example_request": { | |
| "url": "/generate", | |
| "method": "POST", | |
| "body": { | |
| "prompt": "What is C. elegans?", | |
| "temp": 0.3, | |
| "max_tokens": 512 | |
| } | |
| } | |
| }) | |
| if __name__ == "__main__": | |
| # Validate paths on startup | |
| errors = validate_paths() | |
| if errors: | |
| logger.warning("Startup validation errors:") | |
| for error in errors: | |
| logger.warning(f" - {error}") | |
| logger.warning("Service will start but may not function correctly.") | |
| port = int(os.environ.get("PORT", 7860)) | |
| host = os.environ.get("HOST", "0.0.0.0") | |
| logger.info(f"Starting Flask server on {host}:{port}") | |
| logger.info(f"Environment: {'Docker' if IS_DOCKER else 'Local'}") | |
| logger.info(f"Model path: {MODEL_PATH}") | |
| logger.info(f"llama-cli path: {LLAMA_BIN}") | |
| app.run(host=host, port=port, debug=False) | |