clean unnecessary files

This commit is contained in:
2025-08-25 00:43:42 +09:00
parent 7d8e627fe4
commit ca332f7d26
17 changed files with 25 additions and 437 deletions

View File

@@ -1,65 +0,0 @@
#!/usr/bin/env python3
"""
Project Cleanup Summary for GPTEdit
Generated after cleanup operation
"""
import os
from pathlib import Path
from datetime import datetime
def generate_cleanup_summary():
"""Generate summary of cleaned files"""
print("🧹 GPTEdit Project Cleanup Summary")
print("=" * 50)
print(f"📅 Cleanup Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
print("✅ REMOVED FILES:")
removed_files = [
"src/connector/openai_client_backup.py.disabled (contained problematic response_format)",
"tests/image_utils_backup.py (outdated backup)",
"debug_gptedit.py (debug script)",
"debug_path.py (debug script)",
"quick_test.py (test script)",
"replay_edit.py (utility script)",
"test_api_key.py (standalone test)",
"test_size_optimization.py (standalone test)",
"test_verification.py (standalone test)",
"temp/fairy_image.png (old temp file)",
"clear_cache.py (cleanup utility)",
"search_response_format.py (diagnostic utility)"
]
for item in removed_files:
print(f" 🗑️ {item}")
print()
print("📁 KEPT ESSENTIAL FILES:")
essential_files = [
"main.py (main server entry point)",
"requirements.txt (dependencies)",
".env / .env.example (configuration)",
"README.md (documentation)",
"src/ (core source code)",
"tests/ (unit tests)",
"input_images/ (input directory)",
"generated_images/ (output directory)",
"temp/imagen4.png (current working file)",
"temp/optimized_imagen4.png (current optimized file)"
]
for item in essential_files:
print(f" 📄 {item}")
print()
print("🎯 NEXT STEPS:")
print(" 1. Restart the MCP server completely")
print(" 2. Test image editing functionality")
print(" 3. Verify no more response_format errors")
print()
print("✅ PROJECT CLEANUP COMPLETED!")
if __name__ == "__main__":
generate_cleanup_summary()

View File

@@ -1,100 +0,0 @@
#!/usr/bin/env python3
"""
Clean up script for GPTEdit project
Removes unnecessary files safely
"""
import os
import shutil
from pathlib import Path
def cleanup_project(root_dir):
"""Clean up unnecessary files"""
root_path = Path(root_dir)
print(f"🧹 Cleaning up project: {root_path}")
# Files and directories to remove
cleanup_targets = [
# Backup files
"src/connector/openai_client_backup.py.disabled",
"tests/image_utils_backup.py",
# Debug and test files in root
"debug_gptedit.py",
"debug_path.py",
"quick_test.py",
"replay_edit.py",
"test_api_key.py",
"test_size_optimization.py",
"test_verification.py",
"clear_cache.py",
"search_response_format.py",
# Temporary files
"temp/fairy_image.png",
"temp/imagen4.png",
"temp/optimized_imagen4.png",
# Python cache directories
"src/__pycache__",
"src/connector/__pycache__",
"src/server/__pycache__",
"src/utils/__pycache__"
]
removed_count = 0
for target in cleanup_targets:
target_path = root_path / target
if target_path.exists():
try:
if target_path.is_dir():
shutil.rmtree(target_path)
print(f"✅ Removed directory: {target}")
else:
target_path.unlink()
print(f"✅ Removed file: {target}")
removed_count += 1
except Exception as e:
print(f"❌ Failed to remove {target}: {e}")
else:
print(f"⚠️ Not found: {target}")
print(f"\n🎉 Cleanup complete! Removed {removed_count} items")
# Show remaining structure
print(f"\n📁 Remaining project structure:")
essential_files = [
"main.py",
"requirements.txt",
".env",
".env.example",
"README.md",
"src/",
"input_images/",
"generated_images/",
"tests/"
]
for item in essential_files:
item_path = root_path / item
if item_path.exists():
print(f"{item}")
else:
print(f"{item} (missing)")
if __name__ == "__main__":
script_dir = Path(__file__).parent
print("=" * 60)
print("GPTEdit Project Cleanup")
print("=" * 60)
cleanup_project(script_dir)
print("\n" + "=" * 60)
print("✅ PROJECT CLEANUP COMPLETED!")
print("Ready to restart the MCP server")
print("=" * 60)

View File

@@ -1,53 +0,0 @@
#!/usr/bin/env python3
"""
Clear Python cache and restart script for GPTEdit
Run this script to clear all __pycache__ directories and .pyc files
"""
import os
import shutil
import sys
from pathlib import Path
def clear_python_cache(root_dir):
"""Clear all Python cache files and directories"""
root_path = Path(root_dir)
print(f"🧹 Clearing Python cache in: {root_path}")
# Find and remove __pycache__ directories
pycache_dirs = list(root_path.rglob("__pycache__"))
for pycache_dir in pycache_dirs:
try:
shutil.rmtree(pycache_dir)
print(f"✅ Removed: {pycache_dir}")
except Exception as e:
print(f"❌ Failed to remove {pycache_dir}: {e}")
# Find and remove .pyc files
pyc_files = list(root_path.rglob("*.pyc"))
for pyc_file in pyc_files:
try:
pyc_file.unlink()
print(f"✅ Removed: {pyc_file}")
except Exception as e:
print(f"❌ Failed to remove {pyc_file}: {e}")
print(f"🎉 Cache clearing complete!")
if __name__ == "__main__":
# Get the directory of this script
script_dir = Path(__file__).parent
print("=" * 50)
print("GPTEdit Python Cache Cleaner")
print("=" * 50)
clear_python_cache(script_dir)
print("\n" + "=" * 50)
print("✅ CACHE CLEARED SUCCESSFULLY!")
print("Please restart your MCP server/application")
print("=" * 50)

View File

@@ -1 +0,0 @@
# REMOVED: Debug file cleaned up during project organization

View File

@@ -1 +0,0 @@
# REMOVED: Debug file cleaned up during project organization

View File

@@ -1,29 +0,0 @@
@echo off
echo ==========================================
echo GPTEdit Project Final Cleanup
echo ==========================================
echo 🧹 Removing Python cache files...
if exist "src\__pycache__" rmdir /s /q "src\__pycache__"
if exist "src\connector\__pycache__" rmdir /s /q "src\connector\__pycache__"
if exist "src\server\__pycache__" rmdir /s /q "src\server\__pycache__"
if exist "src\utils\__pycache__" rmdir /s /q "src\utils\__pycache__"
echo 🗑️ Removing temporary cleanup files...
if exist "clear_cache.py" del "clear_cache.py"
if exist "search_response_format.py" del "search_response_format.py"
if exist "cleanup_project.py" del "cleanup_project.py"
if exist "temp_delete_marker.txt" del "temp_delete_marker.txt"
echo 🔄 Cleaning old temp files...
if exist "temp\fairy_image.png" del "temp\fairy_image.png"
echo ✅ Cleanup completed!
echo.
echo 🚀 Next steps:
echo 1. Restart your MCP server completely
echo 2. Test image editing functionality
echo 3. The response_format error should be resolved
echo.
echo ==========================================
pause

View File

@@ -1 +0,0 @@
# REMOVED: Quick test file cleaned up during project organization

View File

@@ -1 +0,0 @@
# REMOVED: Replay script cleaned up during project organization

View File

@@ -1,63 +0,0 @@
#!/usr/bin/env python3
"""
Search for response_format usage in all Python files
"""
import os
import re
from pathlib import Path
def search_response_format(root_dir):
"""Search for response_format in all Python files"""
root_path = Path(root_dir)
print(f"🔍 Searching for 'response_format' in: {root_path}")
# Find all Python files
py_files = list(root_path.rglob("*.py"))
found_files = []
for py_file in py_files:
try:
with open(py_file, 'r', encoding='utf-8') as f:
content = f.read()
# Search for response_format (case insensitive)
lines = content.split('\n')
matches = []
for line_num, line in enumerate(lines, 1):
if 'response_format' in line.lower():
matches.append((line_num, line.strip()))
if matches:
found_files.append((py_file, matches))
print(f"\n📁 {py_file}")
for line_num, line in matches:
print(f" Line {line_num}: {line}")
except Exception as e:
print(f"❌ Error reading {py_file}: {e}")
if not found_files:
print("✅ No 'response_format' found in any Python files")
else:
print(f"\n⚠️ Found 'response_format' in {len(found_files)} files")
return found_files
if __name__ == "__main__":
script_dir = Path(__file__).parent
print("=" * 60)
print("GPTEdit response_format Search")
print("=" * 60)
found = search_response_format(script_dir)
print("\n" + "=" * 60)
if found:
print("❌ ACTION REQUIRED: Remove response_format from found files")
else:
print("✅ NO ACTION NEEDED: response_format not found")
print("=" * 60)

View File

@@ -1,3 +0,0 @@
# REMOVED: This backup file contained response_format parameter that caused API errors
# The issue has been fixed in the main openai_client.py file
# This file was causing conflicts and has been removed during cleanup

View File

@@ -168,30 +168,6 @@ class ToolHandlers:
"""
return self._move_temp_to_generated(temp_file_path, base_name, index, extension)
async def _read_claude_temp_file(self, image_name: str) -> bytes:
"""Read image file from Claude's temp directory using window.fs.readFile
Args:
image_name: Name of the image file in Claude temp
Returns:
bytes: Image file data
Raises:
FileNotFoundError: If file doesn't exist in Claude temp
RuntimeError: If reading fails
"""
try:
# Use Claude's window.fs.readFile API to read from Claude temp
# This is a mock implementation - in real MCP this would be handled differently
# For now, we'll raise an immediate error as requested
raise RuntimeError(f"❌ IMMEDIATE ERROR: Cannot read from Claude temp directory in MCP server. File: {image_name}")
except Exception as e:
logger.error(f"Failed to read {image_name} from Claude temp: {e}")
raise RuntimeError(f"❌ Cannot access Claude temp file: {image_name}") from e
async def handle_edit_image(self, arguments: Dict[str, Any]) -> List[TextContent | ImageContent]:
"""
@@ -510,37 +486,55 @@ class ToolHandlers:
# Create edit requests
requests = []
temp_files_data = {} # Store Claude temp file data
temp_files_data = {} # Store file data
# First, read all files from Claude temp
# Note: Batch editing currently requires files to be in input_images directory
# This is a limitation that will be addressed in future versions
for edit_params in edits:
image_name = edit_params['input_image_name']
# Read from input_images directory instead of Claude temp
input_file_path = self.config.input_path / image_name
if not input_file_path.exists():
return [TextContent(
type="text",
text=f"❌ File not found in input directory: {image_name}"
)]
try:
image_data = await self._read_claude_temp_file(image_name)
with open(input_file_path, 'rb') as f:
image_data = f.read()
temp_files_data[image_name] = image_data
except Exception as e:
return [TextContent(
type="text",
text=f"❌ Failed to read {image_name} from Claude temp: {str(e)}"
text=f"❌ Failed to read {image_name}: {str(e)}"
)]
# Check if mask is specified
if 'mask_image_name' in edit_params:
mask_name = edit_params['mask_image_name']
mask_file_path = self.config.input_path / mask_name
if not mask_file_path.exists():
return [TextContent(
type="text",
text=f"❌ Mask file not found in input directory: {mask_name}"
)]
try:
mask_data = await self._read_claude_temp_file(mask_name)
with open(mask_file_path, 'rb') as f:
mask_data = f.read()
temp_files_data[mask_name] = mask_data
except Exception as e:
return [TextContent(
type="text",
text=f"❌ Failed to read mask {mask_name} from Claude temp: {str(e)}"
text=f"❌ Failed to read mask {mask_name}: {str(e)}"
)]
# Now create requests using the read data
for edit_params in edits:
image_name = edit_params['input_image_name']
# Save temp data to local temp file for processing
# Save data to local temp file for processing
local_temp_path = self._save_b64_to_temp_file(
encode_image_base64(temp_files_data[image_name]),
image_name

View File

@@ -1 +0,0 @@
# This file was removed during cleanup

View File

@@ -1 +0,0 @@
# REMOVED: Test file cleaned up during project organization

View File

@@ -1 +0,0 @@
# REMOVED: Test file cleaned up during project organization

View File

@@ -1,84 +0,0 @@
#!/usr/bin/env python3
"""Test script for timeout fixes"""
import asyncio
import logging
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent / 'src'))
from src.connector import Config, OpenAIEditClient, ImageEditRequest
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
async def test_image_edit():
"""Test image editing with new timeout settings"""
try:
# Initialize config
config = Config()
logger.info(f"Timeout setting: {config.default_timeout}s")
logger.info(f"Max image size: {config.max_image_size_mb}MB")
# Find test image
input_path = config.input_path / "imagen4.png"
if not input_path.exists():
logger.error(f"Test image not found: {input_path}")
return False
# Check original size
original_size = input_path.stat().st_size / (1024 * 1024)
logger.info(f"Original image size: {original_size:.2f}MB")
# Create client
client = OpenAIEditClient(config)
# Create edit request
request = ImageEditRequest(
image_path=str(input_path),
prompt="Add magical sparkles around the fairy",
background="transparent",
auto_optimize=True
)
logger.info("Starting edit request...")
start_time = asyncio.get_event_loop().time()
# Process edit
response = await client.edit_image(request)
end_time = asyncio.get_event_loop().time()
total_time = end_time - start_time
if response.success:
logger.info(f"✅ Edit successful in {total_time:.1f}s")
logger.info(f"Output size: {response.image_size}")
# Save result
output_path = config.generated_images_path / "test_timeout_fix.png"
if output_path.parent.exists():
with open(output_path, 'wb') as f:
f.write(response.edited_image_data)
logger.info(f"Saved to: {output_path}")
return True
else:
logger.error(f"❌ Edit failed: {response.error_message}")
logger.error(f"Error type: {response.error_type}")
return False
except Exception as e:
logger.error(f"Test failed with exception: {e}")
return False
if __name__ == "__main__":
# Run test
success = asyncio.run(test_image_edit())
sys.exit(0 if success else 1)

View File

@@ -1 +0,0 @@
# REMOVED: Test file cleaned up during project organization

View File

@@ -1 +0,0 @@
# REMOVED: Backup file cleaned up during project organization