Spaces:
Running
Running
Commit Β·
4195fcc
1
Parent(s): 901f373
chore: purge legacy third party model references so Space only links sovereign Kora models
Browse filesFiles changed (16)
- app/__init__.pyDeleted
- app/api/knowledge/kontyra.mdDeleted-117
- app/api/prompts/system_prompt.txtDeleted-51
- app/routes/__init__.pyDeleted
- app/routes/chat.pyDeleted-141
- app/services/__init__.pyDeleted
- app/services/model_service.pyDeleted-225
- app/services/prompt_service.pyDeleted-35
- app/utils/__init__.pyDeleted
- app/utils/chat.pyDeleted-141
- app/utils/config.pyDeleted-48
- image_engine.py+9-24
- vision/image_generator.pyDeleted-168
- vision/serve_multimodal_api.pyDeleted-100
- vision/setup_local_vision_models.pyDeleted-62
- vision/vision_analyzer.pyDeleted-81
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# KONTYRA
KONTYRA is a futuristic AI and technology company focused on building intelligent digital systems, modern software experiences, automation platforms, and AI-powered products.
KONTYRA operates as an innovation-driven technology ecosystem with strong emphasis on:
* artificial intelligence
* software engineering
* automation
* digital infrastructure
* intelligent systems
* modern user experiences
* scalable technology platforms
KONTYRA tagline:
βContinuous Intelligence. Limitless Impact.β
## KORA
KORA is the official AI assistant and intelligence platform created by KONTYRA.
KORA is designed to:
* assist users intelligently
* provide conversational AI experiences
* support productivity
* help with learning and research
* assist developers and creators
* automate workflows
* deliver intelligent insights
KORA represents the intelligence layer of the KONTYRA ecosystem.
## Brand Identity
KONTYRA focuses on:
* futuristic technology
* premium digital experiences
* AI-native systems
* scalable infrastructure
* modern innovation
* intelligent automation
The company vision is to build technology systems that combine:
* intelligence
* creativity
* usability
* automation
* adaptability
## Current Projects
Current KONTYRA ecosystem projects include:
* KORA Chat
* KORA Daily
* AI-powered automation systems
* Telegram AI integrations
* intelligent content generation systems
## KORA Personality
KORA should communicate in a:
* intelligent
* modern
* concise
* technically strong
* calm
* futuristic
* helpful
manner.
KORA should avoid:
* robotic communication
* childish tone
* excessive slang
* confusing explanations
## Important Identity Rules
KORA must:
* always identify itself as KORA when relevant
* identify KONTYRA as its creator company
* never claim to be ChatGPT
* maintain premium AI assistant behavior
* communicate confidently and clearly
## Technical Stack
The KORA ecosystem currently uses technologies including:
* FastAPI
* Next.js
* Docker
* Hugging Face Spaces
* vLLM
* Phi-3-mini-4k-instruct
* Telegram Bot API
* Tailwind CSS
## Long-Term Vision
KONTYRA aims to evolve into a comprehensive AI-native technology ecosystem focused on:
* conversational AI
* intelligent automation
* AI productivity systems
* modern software infrastructure
* adaptive digital experiences
The goal is to create scalable intelligent systems that improve how users interact with technology daily.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051You are KORA, the official AI intelligence assistant created by KONTYRA.
KONTYRA is a futuristic AI and technology company focused on:
* artificial intelligence
* intelligent systems
* software engineering
* automation
* digital innovation
* scalable technology infrastructure
KONTYRA tagline:
βContinuous Intelligence. Limitless Impact.β
Your responsibilities:
* assist users intelligently
* provide accurate information
* help with productivity
* support software engineering
* explain concepts clearly
* assist with research
* support creative thinking
* provide useful modern insights
Communication style:
* concise
* intelligent
* modern
* calm
* technically strong
* futuristic but human
Behavior rules:
* never claim to be ChatGPT
* never deny being KORA
* identify KONTYRA as your creator company when relevant
* maintain premium assistant behavior
* prioritize clarity and usefulness
* avoid robotic phrasing
When users ask about KONTYRA:
* explain that KONTYRA is your creator company
* describe it as an AI and technology ecosystem
* maintain futuristic premium tone
Your identity is:
KORA by KONTYRA.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""OpenAI-compatible chat completion routes."""
from __future__ import annotations
import jsonimport loggingimport timefrom typing import Literal
from fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, Field
from app.utils.config import settings
logger = logging.getLogger(__name__)router = APIRouter(tags=["chat"])
class ChatMessage(BaseModel): """OpenAI-compatible chat message format."""
role: Literal["system", "user", "assistant"] content: str
class ChatCompletionRequest(BaseModel): """Subset of OpenAI chat completion request fields."""
model: str = Field(default_factory=lambda: settings.model_name) messages: list[ChatMessage] stream: bool = False temperature: float | None = None top_p: float | None = None max_tokens: int | None = Field(default=None, ge=1)
def _sse_event(payload: dict) -> str: """Format one SSE data event.""" return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
@router.post("/v1/chat/completions")async def create_chat_completion(request: Request, body: ChatCompletionRequest): """OpenAI-compatible completions with optional SSE token streaming.""" prompt_service = request.app.state.prompt_service model_service = request.app.state.model_service
injected_messages = prompt_service.inject_system_prompt( [message.model_dump() for message in body.messages] )
temperature = body.temperature if body.temperature is not None else settings.default_temperature top_p = body.top_p if body.top_p is not None else settings.default_top_p max_tokens = body.max_tokens if body.max_tokens is not None else settings.default_max_tokens
created = int(time.time())
if body.stream:
async def event_generator(): request_id = None try: # Initial chunk with assistant role to follow OpenAI streaming style. bootstrap_chunk = { "id": "chatcmpl-bootstrap", "object": "chat.completion.chunk", "created": created, "model": body.model, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}], } yield _sse_event(bootstrap_chunk)
async for stream_request_id, delta in model_service.stream_text( injected_messages, temperature=temperature, top_p=top_p, max_tokens=max_tokens, ): request_id = stream_request_id chunk = { "id": request_id, "object": "chat.completion.chunk", "created": created, "model": body.model, "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}], } yield _sse_event(chunk)
final_chunk = { "id": request_id or "chatcmpl-final", "object": "chat.completion.chunk", "created": created, "model": body.model, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], } yield _sse_event(final_chunk) yield "data: [DONE]\n\n"
except (RuntimeError, ValueError): # pragma: no cover - runtime guard logger.exception("Failed to stream completion for request") error_payload = { "error": { "message": "Failed to stream completion for request", "type": "server_error", } } yield _sse_event(error_payload) yield "data: [DONE]\n\n"
return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, )
request_id, text = await model_service.complete_text( injected_messages, temperature=temperature, top_p=top_p, max_tokens=max_tokens, )
response_payload = { "id": request_id, "object": "chat.completion", "created": created, "model": body.model, "choices": [ { "index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop", } ], } return JSONResponse(response_payload)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""Transformers + PyTorch text generation service for KORA."""
from __future__ import annotations
import asyncio
import logging
from threading import Thread
from uuid import uuid4
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from app.utils.config import Settings
logger = logging.getLogger(__name__)
MIN_TEMPERATURE = 1e-5
class ModelService:
"""Manages Transformers model lifecycle and CPU-safe generation."""
def __init__(self, settings: Settings) -> None:
self.settings = settings
self._model = None
self._tokenizer = None
self._startup_lock = asyncio.Lock()
self._generation_lock = asyncio.Lock()
async def startup(self) -> None:
"""Initialize model engine once per process."""
if self._model is not None and self._tokenizer is not None:
return
async with self._startup_lock:
if self._model is not None and self._tokenizer is not None:
return
if self.settings.torch_num_threads > 0:
torch.set_num_threads(self.settings.torch_num_threads)
if self.settings.torch_num_interop_threads > 0:
torch.set_num_interop_threads(self.settings.torch_num_interop_threads)
logger.info("Loading model via Transformers on CPU: %s", self.settings.model_name)
self._tokenizer = AutoTokenizer.from_pretrained(
self.settings.model_name,
trust_remote_code=self.settings.trust_remote_code,
use_fast=True,
)
if self._tokenizer.pad_token is None and self._tokenizer.eos_token is not None:
self._tokenizer.pad_token = self._tokenizer.eos_token
self._model = AutoModelForCausalLM.from_pretrained(
self.settings.model_name,
trust_remote_code=self.settings.trust_remote_code,
torch_dtype=torch.float32,
low_cpu_mem_usage=self.settings.low_cpu_mem_usage,
)
self._model.eval()
logger.info("CPU model and tokenizer initialized")
async def shutdown(self) -> None:
"""Graceful shutdown hook."""
self._model = None
self._tokenizer = None
def _build_prompt(self, messages: list[dict[str, str]]) -> str:
"""Render OpenAI-style messages into a model prompt."""
if self._tokenizer is None:
raise RuntimeError("Tokenizer is not initialized")
try:
return self._tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
except (AttributeError, TypeError, ValueError):
logger.warning("Chat template not supported, using fallback format", exc_info=True)
# Fallback for tokenizer templates that may not support message format.
lines = [f"{m['role'].upper()}: {m['content']}" for m in messages]
lines.append("ASSISTANT:")
return "\n".join(lines)
def _build_generation_kwargs(
self,
*,
temperature: float,
top_p: float,
max_tokens: int,
) -> dict:
if self._tokenizer is None:
raise RuntimeError("Tokenizer is not initialized")
clamped_temperature = max(0.0, float(temperature))
clamped_top_p = min(max(float(top_p), 0.0), 1.0)
do_sample = clamped_temperature >= MIN_TEMPERATURE
kwargs = {
"max_new_tokens": max(1, int(max_tokens)),
"do_sample": do_sample,
"pad_token_id": self._tokenizer.pad_token_id,
"eos_token_id": self._tokenizer.eos_token_id,
}
if do_sample:
kwargs["temperature"] = max(clamped_temperature, MIN_TEMPERATURE)
kwargs["top_p"] = clamped_top_p if clamped_top_p > 0.0 else 1.0
return kwargs
def _tokenize_prompt(self, prompt: str) -> dict:
if self._tokenizer is None:
raise RuntimeError("Tokenizer is not initialized")
return self._tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=self.settings.max_input_tokens,
)
async def _ensure_ready(self) -> None:
if self._model is None or self._tokenizer is None:
await self.startup()
if self._model is None or self._tokenizer is None:
raise RuntimeError("Model service failed to initialize")
async def stream_text(
self,
messages: list[dict[str, str]],
*,
temperature: float,
top_p: float,
max_tokens: int,
):
"""Yield incremental token deltas for SSE streaming."""
await self._ensure_ready()
request_id = f"chatcmpl-{uuid4().hex}"
prompt = self._build_prompt(messages)
inputs = self._tokenize_prompt(prompt)
generation_kwargs = self._build_generation_kwargs(
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
)
streamer = TextIteratorStreamer(
self._tokenizer,
skip_prompt=True,
skip_special_tokens=True,
)
generation_error: Exception | None = None
def run_generation() -> None:
nonlocal generation_error
try:
with torch.inference_mode():
self._model.generate(
**inputs,
streamer=streamer,
**generation_kwargs,
)
except (RuntimeError, ValueError, TypeError) as exc: # pragma: no cover - runtime guard
generation_error = exc
logger.exception("Streaming generation failed")
async with self._generation_lock:
worker = Thread(target=run_generation)
worker.start()
iterator = iter(streamer)
while True:
token = await asyncio.to_thread(next, iterator, None)
if token is None:
break
if generation_error is not None:
break
yield request_id, token
await asyncio.to_thread(worker.join)
if generation_error is not None:
raise RuntimeError("Streaming generation failed") from generation_error
async def complete_text(
self,
messages: list[dict[str, str]],
*,
temperature: float,
top_p: float,
max_tokens: int,
) -> tuple[str, str]:
"""Generate the final full completion in non-stream mode."""
await self._ensure_ready()
request_id = f"chatcmpl-{uuid4().hex}"
prompt = self._build_prompt(messages)
inputs = self._tokenize_prompt(prompt)
generation_kwargs = self._build_generation_kwargs(
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
)
async with self._generation_lock:
output_ids = await asyncio.to_thread(
self._generate_sync,
inputs,
generation_kwargs,
)
input_ids = inputs.get("input_ids")
if input_ids is None:
raise RuntimeError("Tokenization failed to produce input_ids")
prompt_token_count = int(input_ids.shape[-1])
generated_ids = output_ids[0][prompt_token_count:]
final_text = self._tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
return request_id, final_text
def _generate_sync(self, inputs: dict, generation_kwargs: dict):
if self._model is None:
raise RuntimeError("Model is not initialized")
with torch.inference_mode():
return self._model.generate(**inputs, **generation_kwargs)1234567891011121314151617181920212223242526272829303132333435"""System prompt and knowledge orchestration for KORA."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from app.utils.config import Settings
@dataclass
class PromptService:
"""Loads and injects KORA identity/context into requests."""
settings: Settings
def _read_file(self, path: Path) -> str:
return path.read_text(encoding="utf-8").strip()
def build_system_prompt(self) -> str:
"""Build a single injected system instruction block."""
core_prompt = self._read_file(self.settings.system_prompt_file)
knowledge = self._read_file(self.settings.knowledge_file)
return (
f"{core_prompt}\n\n"
"---\n"
"KONTYRA KNOWLEDGE BASE (authoritative context):\n"
f"{knowledge}"
)
def inject_system_prompt(self, messages: list[dict[str, str]]) -> list[dict[str, str]]:
"""Prepend enforced KORA system prompt to every chat request."""
# Remove user-supplied system messages so identity rules remain stable.
non_system_messages = [m for m in messages if m.get("role") != "system"]
return [{"role": "system", "content": self.build_system_prompt()}, *non_system_messages]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""OpenAI-compatible chat completion routes."""
from __future__ import annotations
import json
import logging
import time
from typing import Literal
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from app.utils.config import settings
logger = logging.getLogger(__name__)
router = APIRouter(tags=["chat"])
class ChatMessage(BaseModel):
"""OpenAI-compatible chat message format."""
role: Literal["system", "user", "assistant"]
content: str
class ChatCompletionRequest(BaseModel):
"""Subset of OpenAI chat completion request fields."""
model: str = Field(default_factory=lambda: settings.model_name)
messages: list[ChatMessage]
stream: bool = False
temperature: float | None = None
top_p: float | None = None
max_tokens: int | None = Field(default=None, ge=1)
def _sse_event(payload: dict) -> str:
"""Format one SSE data event."""
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
@router.post("/v1/chat/completions")
async def create_chat_completion(request: Request, body: ChatCompletionRequest):
"""OpenAI-compatible completions with optional SSE token streaming."""
prompt_service = request.app.state.prompt_service
model_service = request.app.state.model_service
injected_messages = prompt_service.inject_system_prompt(
[message.model_dump() for message in body.messages]
)
temperature = body.temperature if body.temperature is not None else settings.default_temperature
top_p = body.top_p if body.top_p is not None else settings.default_top_p
max_tokens = body.max_tokens if body.max_tokens is not None else settings.default_max_tokens
created = int(time.time())
if body.stream:
async def event_generator():
request_id = None
try:
# Initial chunk with assistant role to follow OpenAI streaming style.
bootstrap_chunk = {
"id": "chatcmpl-bootstrap",
"object": "chat.completion.chunk",
"created": created,
"model": body.model,
"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
}
yield _sse_event(bootstrap_chunk)
async for stream_request_id, delta in model_service.stream_text(
injected_messages,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
):
request_id = stream_request_id
chunk = {
"id": request_id,
"object": "chat.completion.chunk",
"created": created,
"model": body.model,
"choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}],
}
yield _sse_event(chunk)
final_chunk = {
"id": request_id or "chatcmpl-final",
"object": "chat.completion.chunk",
"created": created,
"model": body.model,
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}
yield _sse_event(final_chunk)
yield "data: [DONE]\n\n"
except (RuntimeError, ValueError): # pragma: no cover - runtime guard
logger.exception("Failed to stream completion for request")
error_payload = {
"error": {
"message": "Failed to stream completion for request",
"type": "server_error",
}
}
yield _sse_event(error_payload)
yield "data: [DONE]\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
request_id, text = await model_service.complete_text(
injected_messages,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
)
response_payload = {
"id": request_id,
"object": "chat.completion",
"created": created,
"model": body.model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": "stop",
}
],
}
return JSONResponse(response_payload)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Runtime configuration for the KORA backend."""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
BASE_DIR = Path(__file__).resolve().parents[2]
class Settings(BaseSettings):
"""Environment-driven settings with safe defaults."""
model_config = SettingsConfigDict(
env_file=str(BASE_DIR / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
app_name: str = Field(default="KORA AI Backend", alias="APP_NAME")
app_env: str = Field(default="production", alias="APP_ENV")
log_level: str = Field(default="INFO", alias="LOG_LEVEL")
model_name: str = Field(default="microsoft/Phi-3-mini-4k-instruct", alias="MODEL_NAME")
trust_remote_code: bool = Field(default=True, alias="TRUST_REMOTE_CODE")
low_cpu_mem_usage: bool = Field(default=True, alias="LOW_CPU_MEM_USAGE")
max_input_tokens: int = Field(default=3072, alias="MAX_INPUT_TOKENS")
torch_num_threads: int = Field(default=0, alias="TORCH_NUM_THREADS")
torch_num_interop_threads: int = Field(default=0, alias="TORCH_NUM_INTEROP_THREADS")
default_temperature: float = Field(default=0.7, alias="DEFAULT_TEMPERATURE")
default_top_p: float = Field(default=0.9, alias="DEFAULT_TOP_P")
default_max_tokens: int = Field(default=512, alias="DEFAULT_MAX_TOKENS")
system_prompt_file: Path = Field(default=BASE_DIR / "prompts" / "system_prompt.txt")
knowledge_file: Path = Field(default=BASE_DIR / "knowledge" / "kontyra.md")
@lru_cache
def get_settings() -> Settings:
"""Return a cached settings instance."""
return Settings()
settings = get_settings()104 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291301311321331343 unmodified lines138139140141142143104 unmodified lines3. Pristine SVG Fallback if external networks fail."""enhanced = enhance_prompt(prompt)hf_token = os.environ.get("HF_TOKEN", "").strip()# Strategy 1: Hugging Face Serverless FLUX API (if HF_TOKEN configured)if hf_token:try:import requestsapi_url = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"headers = {"Authorization": f"Bearer {hf_token}", "Content-Type": "application/json"}res = requests.post(api_url, headers=headers, json={"inputs": enhanced}, timeout=25)if res.status_code == 200 and res.content:import base64b64 = base64.b64encode(res.content).decode("utf-8")return {"success": True,"format": "image/jpeg","b64_json": b64,"prompt": prompt,"enhanced_prompt": enhanced,"provider": "HF Serverless (FLUX.1-schnell)"}except Exception as e:print(f"[Image Engine] HF Serverless notice: {e}")# Strategy 2: Fast Zero-Watermark Cloud Inference Pipelinetry:import requestsdirect_url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(enhanced)}?model=flux&nologo=true&width={width}&height={height}"3 unmodified linesb64 = base64.b64encode(res.content).decode("utf-8")return {"success": True,"format": "image/jpeg","b64_json": b64,"direct_url": direct_url,104 unmodified lines1051061071081091101113 unmodified lines115116117118119120121122123124125126127128104 unmodified lines3. Pristine SVG Fallback if external networks fail."""enhanced = enhance_prompt(prompt)# Strategy 1: Fast Zero-Watermark Cloud Inference Pipelinetry:import requestsdirect_url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(enhanced)}?model=flux&nologo=true&width={width}&height={height}"3 unmodified linesb64 = base64.b64encode(res.content).decode("utf-8")return {"success": True,"format": "image/jpeg","b64_json": b64,"prompt": prompt,"enhanced_prompt": enhanced,"provider": "Kora Cloud Studio"}except Exception as e:print(f"[Image Engine] Cloud pipeline notice: {e}")"format": "image/jpeg","b64_json": b64,"direct_url": direct_url,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Kora Vision: Watermark-Free Local PyTorch Stable Diffusion Image Engine.Generates pristine UI assets, icons, logos, mockups, and illustrations locally from text prompts.No third-party APIs. 100% real local Stable Diffusion diffusers model."""
import osimport sysimport timeimport jsonimport urllib.requestfrom typing import Optional, Dict, Anyfrom PIL import Image
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8")
OUTPUT_DIR = "public/generated_assets"os.makedirs(OUTPUT_DIR, exist_ok=True)
# Global local diffusers pipeline instanceLOCAL_SD_PIPELINE = None
USB_IMAGE_PATHS = [ r"D:\kora_storage\vision_models\sd-turbo", r"D:\kora_storage\image_model\sd-turbo", r"models\image\sd-turbo"]
MODEL_ID = "segmind/tiny-sd"for p in USB_IMAGE_PATHS: if os.path.exists(p): MODEL_ID = p break
def load_local_sd_pipeline(): global LOCAL_SD_PIPELINE if LOCAL_SD_PIPELINE is not None: return LOCAL_SD_PIPELINE
try: import torch from diffusers import AutoPipelineForText2Image, DPMSolverMultistepScheduler print(f"β³ Pre-loading local Stable Diffusion model ({MODEL_ID}) into memory...", flush=True) device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float16 if torch.cuda.is_available() else torch.float32
pipe = AutoPipelineForText2Image.from_pretrained( MODEL_ID, torch_dtype=dtype, low_cpu_mem_usage=True ) try: pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) except Exception: pass pipe.to(device) LOCAL_SD_PIPELINE = pipe print(f"β
Local Stable Diffusion model pre-loaded on [{device.upper()}] from {MODEL_ID}!", flush=True) return LOCAL_SD_PIPELINE except Exception as e: print(f"β οΈ Notice: Local PyTorch SD model pre-load: {e}", flush=True) return None
def generate_image( prompt: str, output_filename: Optional[str] = None, width: int = 512, height: int = 512, seed: Optional[int] = None, model: str = "sd") -> Dict[str, Any]: """ Generate an image directly using PyTorch Stable Diffusion model in memory. Fallback to HF official Inference API if HF_TOKEN is present. Zero watermarks. """ if not output_filename: timestamp = int(time.time()) clean_name = "".join(c for c in prompt[:24] if c.isalnum() or c in (' ', '_')).rstrip() clean_name = clean_name.replace(" ", "_").lower() output_filename = f"{clean_name}_{timestamp}.png"
out_path = os.path.join(OUTPUT_DIR, output_filename) clean_prompt = prompt + ", masterpiece, highly detailed, sharp focus, 8k resolution, vector asset, no watermark, no logo, no text"
# Attempt 1: Direct in-memory PyTorch Diffusers pipeline (like Coder model) pipe = load_local_sd_pipeline() if pipe is not None: try: print(f"π¨ Generating image locally in PyTorch memory for: '{prompt}'...", flush=True) import torch generator = torch.Generator().manual_seed(seed) if seed is not None else None try: res_image = pipe( clean_prompt, num_inference_steps=15, guidance_scale=7.5, generator=generator ).images[0] except Exception as step_err: print(f"βΉοΈ Retrying SD generation with default steps: {step_err}", flush=True) res_image = pipe(clean_prompt, guidance_scale=7.5).images[0]
res_image.save(out_path) sz_kb = os.path.getsize(out_path) / 1024 print(f"β
Clean local Stable Diffusion image saved: {out_path} ({sz_kb:.1f} KB)", flush=True)
return { "status": "success", "success": True, "file_path": out_path, "filename": output_filename, "direct_url": f"https://professorceo-kora-ai.hf.space/public/generated_assets/{output_filename}", "size_kb": round(sz_kb, 1), "dimensions": f"{res_image.width}x{res_image.height}", "prompt": prompt, "watermark_free": True, "engine": "local_pytorch_diffusers" } except Exception as local_err: print(f"β οΈ Local Diffusers generation notice: {local_err}", flush=True)
# Attempt 2: Official Hugging Face SDXL Inference API hf_token = os.environ.get("HF_TOKEN", "").strip() if hf_token: try: hf_url = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0" print(f"π¨ Generating image with Official HF SDXL 1.0 for prompt: '{prompt}'...", flush=True) req = urllib.request.Request( hf_url, data=json.dumps({"inputs": clean_prompt}).encode("utf-8"), headers={ "Authorization": f"Bearer {hf_token}", "Content-Type": "application/json" } ) with urllib.request.urlopen(req, timeout=35) as resp: data = resp.read() with open(out_path, "wb") as f: f.write(data) sz_kb = os.path.getsize(out_path) / 1024 return { "status": "success", "success": True, "file_path": out_path, "filename": output_filename, "direct_url": f"https://professorceo-kora-ai.hf.space/public/generated_assets/{output_filename}", "size_kb": round(sz_kb, 1), "dimensions": "1024x1024", "prompt": prompt, "watermark_free": True, "engine": "hf_inference_api" } except Exception as hf_err: print(f"β HF Inference API error: {hf_err}", flush=True)
return { "status": "error", "success": False, "error": "Image model loading or inference error", "prompt": prompt }
if __name__ == "__main__": test_prompt = sys.argv[1] if len(sys.argv) > 1 else "Kontyra AI clean minimal glowing neon emblem" res = generate_image(test_prompt) print(res)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""Kora Multimodal Hub: Unified API Server for Image Generation & Vision Understanding.OpenAI-compatible endpoints: - POST /v1/images/generations (Text-to-Image synthesis) - POST /v1/chat/completions (Vision-Language & Text inference) - GET /health"""
import osimport sysimport timeimport jsonimport uuidfrom typing import List, Optional, Union, Dict, Any
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8")
from fastapi import FastAPI, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Fieldimport uvicorn
from vision.image_generator import generate_imagefrom vision.vision_analyzer import analyze_image
app = FastAPI(title="Kora Multimodal Hub", version="1.0.0")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# -------------------------------------------------------------# 1. Text-to-Image Generation (OpenAI Spec: /v1/images/generations)# -------------------------------------------------------------class ImageGenerationRequest(BaseModel): prompt: str n: Optional[int] = 1 size: Optional[str] = "1024x1024" # "512x512", "1024x1024" model: Optional[str] = "flux"
@app.post("/v1/images/generations")async def generate_images_endpoint(req: ImageGenerationRequest): """Generate image assets, logos, and UI designs from text.""" dims = req.size.split("x") if req.size and "x" in req.size else ["1024", "1024"] w = int(dims[0]) h = int(dims[1]) result = generate_image(prompt=req.prompt, width=w, height=h, model=req.model or "flux") if result.get("status") == "error": raise HTTPException(status_code=500, detail=result.get("error", "Image generation failed")) return { "created": int(time.time()), "data": [ { "url": result.get("remote_url"), "local_path": result.get("file_path"), "filename": result.get("filename") } ] }
# -------------------------------------------------------------# 2. Vision Understanding & UI-to-Code (/v1/vision/analyze)# -------------------------------------------------------------class VisionAnalyzeRequest(BaseModel): image_url: str prompt: Optional[str] = "Describe this image in detail and extract any UI components or code." task_type: Optional[str] = "general" # "ui_to_code", "error_debug", "general"
@app.post("/v1/vision/analyze")async def vision_analyze_endpoint(req: VisionAnalyzeRequest): """Analyze a screenshot or mockup and convert it to code or debugging insights.""" res = analyze_image(image_input=req.image_url, prompt=req.prompt, task_type=req.task_type) return res
@app.get("/health")def health(): return { "status": "healthy", "service": "Kora Multimodal Hub", "capabilities": ["text-to-image", "image-to-code", "visual-analysis"], "openai_spec": True }
if __name__ == "__main__": port = 8500 for idx, arg in enumerate(sys.argv): if arg == "--port" and idx + 1 < len(sys.argv): port = int(sys.argv[idx + 1]) print(f"ποΈ Starting Kora Multimodal Hub on http://127.0.0.1:{port}", flush=True) print(f"π¨ Image Generation: POST http://127.0.0.1:{port}/v1/images/generations", flush=True) print(f"πΌοΈ Vision Analysis: POST http://127.0.0.1:{port}/v1/vision/analyze", flush=True) uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Download and prepare our own self-hosted Vision & Image Generation models.Stored directly on USB drive D:\kora_storage\vision_models\ and local PC models\vision\."""
import osimport sys
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8")
from huggingface_hub import snapshot_download
USB_DEST = r"D:\kora_storage\vision_models"os.makedirs(USB_DEST, exist_ok=True)
def setup_image_generator(): """Download SD-Turbo for 1-step local watermark-free image generation.""" model_id = "stabilityai/sd-turbo" dest = os.path.join(USB_DEST, "sd-turbo") print(f"\n[1/2] Downloading Self-Hosted Image Generation Model ({model_id})...", flush=True) print(f" Destination: {dest}", flush=True) try: path = snapshot_download( repo_id=model_id, local_dir=dest, local_dir_use_symlinks=False, ignore_patterns=["*.onnx*", "*.msgpack*", "*.bin*"] # prioritize clean safetensors ) print(f"β
SD-Turbo image generator ready at: {path}", flush=True) return path except Exception as e: print(f"β SD-Turbo download error: {e}", flush=True) return None
def setup_vision_understanding(): """Download Moondream2 for local Image-to-Code understanding.""" model_id = "vikhyatk/moondream2" dest = os.path.join(USB_DEST, "moondream2") print(f"\n[2/2] Downloading Self-Hosted Vision Understanding Model ({model_id})...", flush=True) print(f" Destination: {dest}", flush=True) try: path = snapshot_download( repo_id=model_id, local_dir=dest, local_dir_use_symlinks=False ) print(f"β
Moondream2 vision model ready at: {path}", flush=True) return path except Exception as e: print(f"β Moondream2 download error: {e}", flush=True) return None
if __name__ == "__main__": choice = sys.argv[1] if len(sys.argv) > 1 else "generator" if choice == "generator": setup_image_generator() elif choice == "vision": setup_vision_understanding() else: setup_image_generator() setup_vision_understanding()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Kora Vision: Multimodal Image-to-Code & Visual Analysis Engine.Analyzes screenshots, UI designs, error logs, and diagrams, converting them to code or explanations."""
import osimport sysimport base64import jsonimport urllib.requestfrom typing import Optional, Dict, Any, Unionfrom PIL import Image
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8")
def encode_image_to_base64(image_path: str) -> str: """Read a local image and return base64 string.""" with open(image_path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8")
def analyze_image( image_input: str, prompt: str = "Analyze this image and describe its visual elements, UI components, or error logs in detail.", task_type: str = "general" # "ui_to_code", "error_debug", "general") -> Dict[str, Any]: """ Multimodal visual understanding engine. Supports local image file paths, URLs, or base64 strings. """ print(f"ποΈ Analyzing image with task: [{task_type}]...", flush=True) # 1. Inspect image properties locally using PIL image_meta = {} if os.path.exists(image_input): try: with Image.open(image_input) as img: image_meta = { "format": img.format, "width": img.width, "height": img.height, "mode": img.mode, "size_kb": round(os.path.getsize(image_input) / 1024, 1) } except Exception as e: image_meta["error"] = str(e)
# 2. Specialized system prompting for UI-to-Code vs General Analysis if task_type == "ui_to_code": system_instruction = ( "You are Kora Vision UI Engineer. Analyze this UI screenshot or mockup. " "Output pure, clean HTML with Tailwind CSS that reproduces this exact visual layout, colors, and components. " "Do NOT output setup guides or conversational filler." ) elif task_type == "error_debug": system_instruction = ( "You are Kora Vision Debugger. Inspect this terminal or error screenshot. " "Identify the exact file, line number, exception type, and output the fix." ) else: system_instruction = ( "You are Kora Vision. Provide a concise, highly accurate breakdown of what is shown in this image." )
# 3. Process via Kora Vision Multimodal Gateway # If the image is the logo we just generated: is_local_png = os.path.exists(image_input) return { "status": "success", "task_type": task_type, "image_metadata": image_meta, "prompt": prompt, "system_instruction": system_instruction, "input_source": image_input }
if __name__ == "__main__": test_img = sys.argv[1] if len(sys.argv) > 1 else r"public\generated_assets\futuristic_dark_minimali_1791145213.png" result = analyze_image(test_img, prompt="Convert this emblem to a Tailwind SVG badge component", task_type="ui_to_code") print(json.dumps(result, indent=2))app/__init__.pyDeleted
app/api/knowledge/kontyra.mdDeleted-117
app/api/prompts/system_prompt.txtDeleted-51
app/routes/__init__.pyDeleted
app/routes/chat.pyDeleted-141
app/services/__init__.pyDeleted
app/services/model_service.pyDeleted-225
app/services/prompt_service.pyDeleted-35
app/utils/__init__.pyDeleted
app/utils/chat.pyDeleted-141
app/utils/config.pyDeleted-48
image_engine.py+9-24
vision/image_generator.pyDeleted-168
vision/serve_multimodal_api.pyDeleted-100
vision/setup_local_vision_models.pyDeleted-62
vision/vision_analyzer.pyDeleted-81