Spaces:
Sleeping
Sleeping
Update backend/app.py
Browse files- backend/app.py +191 -190
backend/app.py
CHANGED
|
@@ -1,191 +1,192 @@
|
|
| 1 |
-
from flask import Flask, request, Response, jsonify
|
| 2 |
-
from flask_cors import CORS
|
| 3 |
-
from PIL import Image
|
| 4 |
-
import torch
|
| 5 |
-
from transformers import AutoProcessor, BlipForConditionalGeneration
|
| 6 |
-
from llama_cpp import Llama
|
| 7 |
-
import json
|
| 8 |
-
from tavily import TavilyClient
|
| 9 |
-
import os
|
| 10 |
-
from dotenv import load_dotenv
|
| 11 |
-
|
| 12 |
-
load_dotenv()
|
| 13 |
-
|
| 14 |
-
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 15 |
-
|
| 16 |
-
app = Flask(__name__)
|
| 17 |
-
CORS(app
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
"
|
| 153 |
-
|
| 154 |
-
"
|
| 155 |
-
"
|
| 156 |
-
"When
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
"
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
| 191 |
app.run(host="0.0.0.0", port=8080)
|
|
|
|
| 1 |
+
from flask import Flask, request, Response, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoProcessor, BlipForConditionalGeneration
|
| 6 |
+
from llama_cpp import Llama
|
| 7 |
+
import json
|
| 8 |
+
from tavily import TavilyClient
|
| 9 |
+
import os
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 15 |
+
|
| 16 |
+
app = Flask(__name__)
|
| 17 |
+
CORS(app, resources={r"/completion": {"origins": ["https://bangorinas.com", "https://www.bangorinas.com"]},
|
| 18 |
+
r"/research": {"origins": ["https://bangorinas.com", "https://www.bangorinas.com"]}})
|
| 19 |
+
|
| 20 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 21 |
+
print(f"Using device: {device}")
|
| 22 |
+
|
| 23 |
+
# --- Load Models ---
|
| 24 |
+
try:
|
| 25 |
+
vision_processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 26 |
+
vision_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large").to(device)
|
| 27 |
+
print("BLIP Vision model loaded successfully.")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"Error loading Vision model: {e}")
|
| 30 |
+
vision_model = None
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
llm = Llama.from_pretrained(
|
| 34 |
+
repo_id="ranggafermata/Effort-1",
|
| 35 |
+
filename="EffortQ43B.gguf",
|
| 36 |
+
n_ctx=2048,
|
| 37 |
+
n_gpu_layers=-1,
|
| 38 |
+
verbose=False,
|
| 39 |
+
chat_format="llama-3" # Use the standard Llama 3 chat format
|
| 40 |
+
)
|
| 41 |
+
print("Effort 1 model loaded successfully.")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Error loading Effort 1 model: {e}")
|
| 44 |
+
llm = None
|
| 45 |
+
|
| 46 |
+
# Load Endeavor preview model (pro)
|
| 47 |
+
try:
|
| 48 |
+
llm_endeavor = Llama.from_pretrained(
|
| 49 |
+
repo_id="ranggafermata/Endeavor-1",
|
| 50 |
+
filename="EndeavorPreview-q4.gguf",
|
| 51 |
+
n_ctx=2048,
|
| 52 |
+
n_gpu_layers=-1,
|
| 53 |
+
verbose=False,
|
| 54 |
+
chat_format="llama-3"
|
| 55 |
+
)
|
| 56 |
+
print("Endeavor 1 (preview) model loaded successfully.")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error loading Endeavor 1 model: {e}")
|
| 59 |
+
llm_endeavor = None
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
# Initialize the Tavily client instance
|
| 63 |
+
tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
|
| 64 |
+
print("Tavily client initialized successfully.")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"Error initializing Tavily client: {e}")
|
| 67 |
+
|
| 68 |
+
@app.route("/research", methods=["POST"])
|
| 69 |
+
def research():
|
| 70 |
+
|
| 71 |
+
global tavily_client
|
| 72 |
+
|
| 73 |
+
if not tavily_client:
|
| 74 |
+
return jsonify({"error": "Tavily client not available"}), 500
|
| 75 |
+
|
| 76 |
+
data = request.get_json()
|
| 77 |
+
task = data.get("task")
|
| 78 |
+
query = data.get("query")
|
| 79 |
+
|
| 80 |
+
if not task or not query:
|
| 81 |
+
return jsonify({"error": "Missing task or query"}), 400
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
if task == 'search':
|
| 85 |
+
results = tavily_client.search(query=query, search_depth="advanced")
|
| 86 |
+
elif task == 'extract':
|
| 87 |
+
results = tavily_client.extract(urls=[query])
|
| 88 |
+
else:
|
| 89 |
+
return jsonify({"error": "Invalid task"}), 400
|
| 90 |
+
|
| 91 |
+
return jsonify(results)
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"Error during Tavily research: {e}")
|
| 95 |
+
tavily_client = None
|
| 96 |
+
|
| 97 |
+
return jsonify({"error": str(e)}), 500
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# --- Main Endpoint ---
|
| 101 |
+
@app.route("/completion", methods=["POST"])
|
| 102 |
+
def completion():
|
| 103 |
+
prompt = request.form.get("prompt", "")
|
| 104 |
+
history_json = request.form.get("history", "[]")
|
| 105 |
+
image_file = request.files.get("image")
|
| 106 |
+
model_choice = request.form.get("model", "effort")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
pil_image = None
|
| 110 |
+
if image_file:
|
| 111 |
+
try:
|
| 112 |
+
pil_image = Image.open(image_file.stream).convert("RGB")
|
| 113 |
+
except Exception as e:
|
| 114 |
+
print(f"Error opening image file: {e}")
|
| 115 |
+
pil_image = None
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
chat_history = json.loads(history_json)
|
| 119 |
+
except json.JSONDecodeError:
|
| 120 |
+
chat_history = []
|
| 121 |
+
|
| 122 |
+
def generate_stream(user_prompt, image_obj, history, model_choice_inner):
|
| 123 |
+
if image_obj:
|
| 124 |
+
if vision_model:
|
| 125 |
+
try:
|
| 126 |
+
img = pil_image.resize((384, 384)) # Resize to match model input size
|
| 127 |
+
inputs = (
|
| 128 |
+
vision_processor(images=img, text=user_prompt, return_tensors="pt").to(device)
|
| 129 |
+
if user_prompt else vision_processor(images=img, return_tensors="pt").to(device)
|
| 130 |
+
)
|
| 131 |
+
output = vision_model.generate(**inputs, max_new_tokens=50)
|
| 132 |
+
caption = vision_processor.decode(output[0], skip_special_tokens=True).strip()
|
| 133 |
+
yield f"data: {json.dumps({'content': caption})}\n\n"
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error processing image: {e}")
|
| 136 |
+
yield f"data: {json.dumps({'content': 'Sorry, I had trouble reading that image.'})}\n\n"
|
| 137 |
+
else:
|
| 138 |
+
yield f"data: {json.dumps({'content': 'Vision model not available.'})}\n\n"
|
| 139 |
+
|
| 140 |
+
else:
|
| 141 |
+
# Choose model instance
|
| 142 |
+
if model_choice_inner == "endeavor" and llm_endeavor:
|
| 143 |
+
llm_to_use = llm_endeavor
|
| 144 |
+
else:
|
| 145 |
+
llm_to_use = llm
|
| 146 |
+
|
| 147 |
+
if llm_to_use:
|
| 148 |
+
try:
|
| 149 |
+
# Different system prompts for Effort vs Endeavor
|
| 150 |
+
if llm_to_use is llm_endeavor:
|
| 151 |
+
system_message = {
|
| 152 |
+
"role": "system",
|
| 153 |
+
"content": (
|
| 154 |
+
"You are Endeavor — a professional-grade AI assistant. "
|
| 155 |
+
"Provide concise, accurate, and context-aware answers. Prioritize technical precision, "
|
| 156 |
+
"clarity, and safety. When asked for code, include runnable examples and brief explanations. "
|
| 157 |
+
"When unsure, state limitations and offer next steps or references."
|
| 158 |
+
)
|
| 159 |
+
}
|
| 160 |
+
else:
|
| 161 |
+
system_message = {
|
| 162 |
+
"role": "system",
|
| 163 |
+
"content": "You are a helpful and brilliant AI assistant named Effort."
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
messages = [system_message] + history + [{"role": "user", "content": user_prompt}]
|
| 167 |
+
|
| 168 |
+
print(f"Sending {len(messages)} messages to the model ({'endeavor' if llm_to_use is llm_endeavor else 'effort'}).")
|
| 169 |
+
|
| 170 |
+
stream = llm_to_use.create_chat_completion(
|
| 171 |
+
messages=messages,
|
| 172 |
+
max_tokens=1024,
|
| 173 |
+
temperature=0.7,
|
| 174 |
+
stream=True
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
for output in stream:
|
| 178 |
+
token = output["choices"][0]["delta"].get("content", "")
|
| 179 |
+
if token:
|
| 180 |
+
yield f"data: {json.dumps({'content': token})}\n\n"
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
print(f"Error during text generation: {e}")
|
| 184 |
+
yield f"data: {json.dumps({'content': 'I encountered an error.'})}\n\n"
|
| 185 |
+
else:
|
| 186 |
+
yield f"data: {json.dumps({'content': 'Requested text model not available.'})}\n\n"
|
| 187 |
+
|
| 188 |
+
return Response(generate_stream(prompt, image_file, chat_history, model_choice), mimetype="text-event-stream")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
app.run(host="0.0.0.0", port=8080)
|