tahamajs's picture
download
raw
10.9 kB
import os
import base64
from typing import Dict, List, Any, Optional, Union
from dataclasses import dataclass
import json
import logging
try:
import google.generativeai as genai
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_core.tools import Tool
GEMINI_AVAILABLE = True
except ImportError:
GEMINI_AVAILABLE = False
print("⚠️ Gemini API not available. Install with: pip install google-generativeai langchain-google-genai")
try:
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool
LANGCHAIN_AVAILABLE = True
except ImportError:
LANGCHAIN_AVAILABLE = False
print("⚠️ LangChain not available. Install with: pip install langchain")
try:
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
LANGGRAPH_AVAILABLE = True
except ImportError:
LANGGRAPH_AVAILABLE = False
print("⚠️ LangGraph not available. Install with: pip install langgraph")
import numpy as np
import torch
from PIL import Image
import io
logger = logging.getLogger(__name__)
@dataclass
class GeminiConfig:
api_key: str
model_name: str = "gemini-1.5-pro"
temperature: float = 0.7
max_tokens: int = 2048
safety_settings: Optional[Dict] = None
class GeminiManager:
def __init__(self, config: GeminiConfig):
if not GEMINI_AVAILABLE:
raise ImportError("Gemini API not available. Please install required packages.")
self.config = config
self._setup_gemini()
self._setup_langchain()
def _setup_gemini(self):
genai.configure(api_key=self.config.api_key)
safety_settings = self.config.safety_settings or [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
}
]
generation_config = genai.types.GenerationConfig(
temperature=self.config.temperature,
max_output_tokens=self.config.max_tokens,
)
self.model = genai.GenerativeModel(
model_name=self.config.model_name,
generation_config=generation_config,
safety_settings=safety_settings
)
logger.info(f"✅ Gemini model {self.config.model_name} initialized")
def _setup_langchain(self):
if not LANGCHAIN_AVAILABLE:
logger.warning("LangChain not available")
return
self.llm = ChatGoogleGenerativeAI(
model=self.config.model_name,
temperature=self.config.temperature,
max_output_tokens=self.config.max_tokens,
google_api_key=self.config.api_key
)
logger.info("✅ LangChain Gemini integration initialized")
def encode_image(self, image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> str:
if isinstance(image, str):
with open(image, "rb") as f:
return base64.b64encode(f.read()).decode()
elif isinstance(image, Image.Image):
buffer = io.BytesIO()
image.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode()
elif isinstance(image, np.ndarray):
pil_image = Image.fromarray(image.astype(np.uint8))
buffer = io.BytesIO()
pil_image.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode()
elif isinstance(image, torch.Tensor):
if image.dim() == 4:
image = image[0]
if image.is_cuda:
image = image.cpu()
if image.max() <= 1.0:
image = image * 255
image_np = image.permute(1, 2, 0).numpy().astype(np.uint8)
pil_image = Image.fromarray(image_np)
buffer = io.BytesIO()
pil_image.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode()
else:
raise ValueError(f"Unsupported image type: {type(image)}")
def ask_question_with_image(self, question: str, image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> Dict[str, Any]:
try:
image_data = self.encode_image(image)
content = [
{
"type": "text",
"text": f
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_data}"
}
}
]
response = self.model.generate_content(content)
if response.prompt_feedback:
logger.warning(f"Prompt feedback: {response.prompt_feedback}")
if response.candidates:
candidate = response.candidates[0]
if candidate.finish_reason == "SAFETY":
return {
"answer": "متأسفانه نمی‌توانم به این سوال پاسخ دهم به دلیل محدودیت‌های ایمنی.",
"reasoning": [],
"confidence": 0.0,
"safety_concern": True
}
answer_text = candidate.content.parts[0].text if candidate.content.parts else ""
reasoning_steps = self._extract_reasoning(answer_text)
return {
"answer": answer_text,
"reasoning": reasoning_steps,
"confidence": 0.9,
"model": self.config.model_name,
"safety_concern": False
}
return {
"answer": "خطا در تولید پاسخ",
"reasoning": [],
"confidence": 0.0,
"error": "No candidates generated"
}
except Exception as e:
logger.error(f"Error in Gemini VQA: {e}")
return {
"answer": f"خطا در پردازش: {str(e)}",
"reasoning": [],
"confidence": 0.0,
"error": str(e)
}
def _extract_reasoning(self, answer_text: str) -> List[str]:
reasoning_steps = []
lines = answer_text.split('\n')
for line in lines:
line = line.strip()
if any(keyword in line.lower() for keyword in ['اول', 'سپس', 'بعد', 'در نهایت', 'نتیجه']):
reasoning_steps.append(line)
elif line.startswith(('1.', '2.', '3.', '4.', '5.')):
reasoning_steps.append(line)
elif line.startswith(('•', '-', '*')):
reasoning_steps.append(line)
return reasoning_steps if reasoning_steps else ["استدلال مستقیم از مدل Gemini"]
def batch_ask_questions(self, questions: List[str], image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> List[Dict[str, Any]]:
results = []
for question in questions:
result = self.ask_question_with_image(question, image)
results.append(result)
return results
def get_model_info(self) -> Dict[str, Any]:
return {
"model_name": self.config.model_name,
"temperature": self.config.temperature,
"max_tokens": self.config.max_tokens,
"langchain_available": LANGCHAIN_AVAILABLE,
"langgraph_available": LANGGRAPH_AVAILABLE
}
class GeminiVQAAgent:
def __init__(self, gemini_manager: GeminiManager):
self.gemini_manager = gemini_manager
self.conversation_history = []
def add_to_history(self, question: str, answer: str, reasoning: List[str]):
self.conversation_history.append({
"question": question,
"answer": answer,
"reasoning": reasoning,
"timestamp": self._get_timestamp()
})
def _get_timestamp(self) -> str:
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def ask_follow_up_question(self, question: str, image: Union[str, Image.Image, np.ndarray, torch.Tensor]) -> Dict[str, Any]:
context = ""
if self.conversation_history:
context = "تاریخچه مکالمه قبلی:\n"
for entry in self.conversation_history[-3:]:
context += f"سوال: {entry['question']}\n"
context += f"پاسخ: {entry['answer']}\n\n"
enhanced_question = f"{context}سوال جدید: {question}"
result = self.gemini_manager.ask_question_with_image(enhanced_question, image)
self.add_to_history(question, result["answer"], result["reasoning"])
return result
def get_conversation_summary(self) -> str:
if not self.conversation_history:
return "هیچ مکالمه‌ای ثبت نشده است."
summary = f"خلاصه مکالمه ({len(self.conversation_history)} سوال):\n\n"
for i, entry in enumerate(self.conversation_history, 1):
summary += f"{i}. سوال: {entry['question']}\n"
summary += f" پاسخ: {entry['answer'][:100]}...\n\n"
return summary
def create_gemini_manager(api_key: str = None) -> GeminiManager:
if api_key is None:
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
raise ValueError("API key not provided. Set GOOGLE_API_KEY environment variable or pass api_key parameter.")
config = GeminiConfig(api_key=api_key)
return GeminiManager(config)
if __name__ == "__main__":
api_key = "your_gemini_api_key_here"
try:
manager = create_gemini_manager(api_key)
print("✅ Gemini Manager created successfully")
print(f"Model info: {manager.get_model_info()}")
except Exception as e:
print(f"❌ Error: {e}")

Xet Storage Details

Size:
10.9 kB
·
Xet hash:
1f4fffa2a654ccd47b41d78dbded8970dd4481301c44977054cb5e886f4e0a8f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.