-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_dify_file_handling.py
More file actions
653 lines (534 loc) · 18.9 KB
/
fix_dify_file_handling.py
File metadata and controls
653 lines (534 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复Dify文件处理问题的脚本
处理Dify传递的文件对象格式
"""
script_content = '''#!/bin/bash
# -*- coding: utf-8 -*-
# 修复Dify文件处理脚本
set -e
# 颜色定义
RED='\\033[0;31m'
GREEN='\\033[0;32m'
YELLOW='\\033[1;33m'
BLUE='\\033[0;34m'
NC='\\033[0m'
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
APP_DIR="/home/ubuntu/image-extractor"
# 修复app.py以处理Dify文件格式
fix_dify_file_handling() {
log_info "修复Dify文件处理逻辑..."
cat > "$APP_DIR/app.py" << 'EOFF'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片信息提取API服务
提供RESTful API接口用于提取图片的EXIF信息
支持Dify平台的文件格式
"""
import os
import sys
import logging
import json
import requests
import tempfile
from datetime import datetime
from flask import Flask, request, jsonify, Response
from werkzeug.utils import secure_filename
from werkzeug.exceptions import RequestEntityTooLarge
import uuid
# 导入自定义模块
from extract_info import ImageExtractor, make_json_serializable
from config import Config
# 创建Flask应用
app = Flask(__name__)
# 加载配置
app.config.from_object(Config)
# 配置日志
def setup_logging():
"""设置日志配置"""
if not os.path.exists('logs'):
os.makedirs('logs')
# 创建日志格式
formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(name)s: %(message)s'
)
# 文件日志处理器
file_handler = logging.FileHandler('logs/app.log', encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
# 错误日志处理器
error_handler = logging.FileHandler('logs/error.log', encoding='utf-8')
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.ERROR)
# 控制台日志处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.INFO)
# 配置应用日志
app.logger.addHandler(file_handler)
app.logger.addHandler(error_handler)
app.logger.addHandler(console_handler)
app.logger.setLevel(logging.INFO)
return app.logger
# 初始化日志
logger = setup_logging()
# 初始化图片提取器
extractor = ImageExtractor()
def allowed_file(filename):
"""检查文件是否被允许"""
return '.' in filename and \\
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def create_response(success=True, data=None, error=None, message=None):
"""创建统一格式的响应"""
response = {
'success': success,
'timestamp': datetime.now().isoformat()
}
if success:
if data:
# 确保数据可以被JSON序列化
serializable_data = make_json_serializable(data)
response['data'] = serializable_data
if message:
response['message'] = message
else:
if error:
response['error'] = error
if message:
response['message'] = message
# 手动序列化为JSON字符串,然后创建Response对象
json_str = json.dumps(response, ensure_ascii=False, indent=2)
return Response(json_str, mimetype='application/json')
def download_file_from_url(url, filename=None):
"""
从URL下载文件
Args:
url (str): 文件URL
filename (str): 保存的文件名
Returns:
str: 下载文件的本地路径
"""
try:
# 如果没有提供文件名,从URL中提取
if not filename:
filename = url.split('/')[-1]
if '?' in filename:
filename = filename.split('?')[0]
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_path = os.path.join(temp_dir, temp_filename)
logger.info(f"开始下载文件: {url}")
# 下载文件
response = requests.get(url, timeout=30, stream=True)
response.raise_for_status()
# 保存文件
with open(temp_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logger.info(f"文件下载完成: {temp_path}")
return temp_path
except Exception as e:
logger.error(f"下载文件失败: {str(e)}")
raise
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查接口"""
return create_response(
success=True,
message='服务运行正常',
data={
'status': 'healthy',
'version': '1.0.0',
'timestamp': datetime.now().isoformat()
}
)
@app.route('/extract', methods=['POST'])
def extract_image_info():
"""
提取图片信息的主要接口
支持多种输入格式:
1. 直接文件上传 (multipart/form-data)
2. Dify文件对象 (JSON)
3. 文件URL
"""
temp_file_path = None
try:
# 方式1:检查是否是Dify文件对象
if request.is_json:
json_data = request.get_json()
logger.info(f"收到JSON请求: {json_data}")
if 'pic' in json_data:
pic_data = json_data['pic']
if 'url' in pic_data:
# 从Dify URL下载文件
file_url = pic_data['url']
filename = pic_data.get('filename', 'image.jpg')
logger.info(f"从Dify URL下载文件: {file_url}")
temp_file_path = download_file_from_url(file_url, filename)
elif 'remote_url' in pic_data:
# 尝试从remote_url下载
file_url = pic_data['remote_url']
filename = pic_data.get('filename', 'image.jpg')
logger.info(f"从remote_url下载文件: {file_url}")
temp_file_path = download_file_from_url(file_url, filename)
else:
return create_response(
success=False,
error='INVALID_DIFY_FORMAT',
message='Dify文件对象中未找到有效的文件URL'
), 400
else:
return create_response(
success=False,
error='NO_PIC_DATA',
message='JSON请求中未找到pic字段'
), 400
# 方式2:传统的文件上传
elif 'image' in request.files:
file = request.files['image']
if file.filename == '':
return create_response(
success=False,
error='EMPTY_FILENAME',
message='文件名为空'
), 400
# 检查文件格式是否支持
if not allowed_file(file.filename):
return create_response(
success=False,
error='INVALID_FILE',
message=f'不支持的文件格式,支持的格式:{", ".join(app.config["ALLOWED_EXTENSIONS"])}'
), 400
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(file.filename)}"
temp_file_path = os.path.join(temp_dir, temp_filename)
# 保存上传的文件到临时位置
file.save(temp_file_path)
logger.info(f"文件已保存到临时路径: {temp_file_path}")
# 方式3:检查是否是URL参数
elif request.form.get('image_url'):
image_url = request.form.get('image_url')
temp_file_path = download_file_from_url(image_url)
else:
return create_response(
success=False,
error='MISSING_FILE',
message='未找到图片文件。请提供以下之一:\\n1. 上传image文件\\n2. 传递包含pic的JSON对象\\n3. 提供image_url参数'
), 400
# 验证文件是否存在
if not temp_file_path or not os.path.exists(temp_file_path):
return create_response(
success=False,
error='FILE_NOT_FOUND',
message='文件处理失败,临时文件不存在'
), 500
# 提取图片信息
logger.info(f"开始提取图片信息: {temp_file_path}")
image_info = extractor.extract_all_info(temp_file_path)
# 记录访问日志
client_ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.environ.get('REMOTE_ADDR', 'unknown'))
logger.info(f"成功处理图片,客户端IP: {client_ip}")
# 返回结果
return create_response(
success=True,
data=image_info,
message='图片信息提取成功'
)
except requests.exceptions.RequestException as e:
logger.error(f"网络请求错误: {str(e)}")
return create_response(
success=False,
error='NETWORK_ERROR',
message=f'下载文件时发生网络错误: {str(e)}'
), 500
except FileNotFoundError as e:
logger.error(f"文件未找到: {str(e)}")
return create_response(
success=False,
error='FILE_NOT_FOUND',
message='处理文件时发生错误'
), 500
except ValueError as e:
logger.error(f"文件格式错误: {str(e)}")
return create_response(
success=False,
error='INVALID_FILE',
message=str(e)
), 400
except Exception as e:
logger.error(f"处理图片时发生错误: {str(e)}", exc_info=True)
return create_response(
success=False,
error='PROCESSING_ERROR',
message='处理图片时发生内部错误'
), 500
finally:
# 清理临时文件
if temp_file_path and os.path.exists(temp_file_path):
try:
os.remove(temp_file_path)
logger.info(f"临时文件已清理: {temp_file_path}")
except Exception as e:
logger.warning(f"清理临时文件失败: {str(e)}")
@app.route('/extract_dify', methods=['POST'])
def extract_dify_image():
"""
专门处理Dify文件对象的接口
"""
return extract_image_info()
@app.route('/info', methods=['GET'])
def get_api_info():
"""获取API信息"""
return create_response(
success=True,
message='图片信息提取API',
data={
'name': '图片信息提取API',
'version': '1.0.0',
'description': '提取图片的EXIF信息,包括拍摄时间和GPS位置',
'supported_formats': {
'file_upload': ['multipart/form-data'],
'dify_object': ['application/json'],
'url_upload': ['application/x-www-form-urlencoded']
},
'endpoints': {
'health': {
'method': 'GET',
'path': '/health',
'description': '健康检查'
},
'extract': {
'method': 'POST',
'path': '/extract',
'description': '提取图片信息(支持多种格式)',
'formats': [
'文件上传: image file',
'Dify对象: {"pic": {...}}',
'URL参数: image_url=http://...'
]
},
'extract_dify': {
'method': 'POST',
'path': '/extract_dify',
'description': '专门处理Dify文件对象'
},
'info': {
'method': 'GET',
'path': '/info',
'description': 'API信息'
}
}
}
)
@app.errorhandler(404)
def not_found(error):
"""404错误处理"""
return create_response(
success=False,
error='NOT_FOUND',
message='请求的资源不存在'
), 404
@app.errorhandler(405)
def method_not_allowed(error):
"""405错误处理"""
return create_response(
success=False,
error='METHOD_NOT_ALLOWED',
message='请求方法不被允许'
), 405
@app.errorhandler(500)
def internal_error(error):
"""500错误处理"""
logger.error(f"服务器内部错误: {str(error)}", exc_info=True)
return create_response(
success=False,
error='INTERNAL_ERROR',
message='服务器内部错误'
), 500
@app.before_request
def log_request_info():
"""记录请求信息"""
client_ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.environ.get('REMOTE_ADDR', 'unknown'))
content_type = request.headers.get('Content-Type', 'unknown')
logger.info(f"收到请求: {request.method} {request.path} [{content_type}] 来自: {client_ip}")
@app.after_request
def log_response_info(response):
"""记录响应信息"""
client_ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.environ.get('REMOTE_ADDR', 'unknown'))
logger.info(f"响应返回: {response.status_code} 给: {client_ip}")
return response
def main():
"""主函数"""
try:
# 确保必要的目录存在
os.makedirs('logs', exist_ok=True)
os.makedirs('uploads', exist_ok=True)
logger.info("图片信息提取服务启动中...")
logger.info(f"服务地址: http://{app.config['HOST']}:{app.config['PORT']}")
logger.info(f"最大文件大小: {app.config['MAX_CONTENT_LENGTH'] // (1024*1024)}MB")
logger.info(f"支持的文件格式: {', '.join(app.config['ALLOWED_EXTENSIONS'])}")
logger.info("支持多种输入格式:")
logger.info(" 1. 直接文件上传 (multipart/form-data)")
logger.info(" 2. Dify文件对象 (JSON)")
logger.info(" 3. 文件URL")
# 启动Flask应用
app.run(
host=app.config['HOST'],
port=app.config['PORT'],
debug=app.config['DEBUG'],
threaded=True
)
except Exception as e:
logger.error(f"启动服务失败: {str(e)}", exc_info=True)
sys.exit(1)
if __name__ == '__main__':
main()
EOFF
if [ $? -eq 0 ]; then
log_success "Dify文件处理逻辑修复完成"
else
log_error "Dify文件处理逻辑修复失败"
return 1
fi
}
# 检查是否需要安装requests
check_dependencies() {
log_info "检查依赖包..."
cd "$APP_DIR"
source "$APP_DIR/image_extractor_env/bin/activate"
# 检查requests是否已安装
python -c "import requests" 2>/dev/null
if [ $? -ne 0 ]; then
log_info "安装requests包..."
pip install requests
log_success "requests包安装完成"
else
log_success "requests包已存在"
fi
}
# 重启服务
restart_service() {
log_info "重启服务..."
cd "$APP_DIR"
# 停止现有服务
pkill -f "python.*app.py" 2>/dev/null || true
sleep 3
# 激活虚拟环境
source "$APP_DIR/image_extractor_env/bin/activate"
# 启动服务
nohup python app.py > logs/app.log 2>&1 &
local pid=$!
echo $pid > app.pid
log_success "服务启动完成,PID: $pid"
# 等待启动
sleep 5
# 测试健康检查
response=$(curl -s http://localhost:5000/health 2>/dev/null || echo "")
if [[ -n "$response" ]]; then
log_success "服务健康检查通过"
else
log_warning "服务健康检查失败,查看日志..."
if [[ -f "logs/app.log" ]]; then
echo "最近日志:"
tail -10 logs/app.log
fi
fi
}
# 测试Dify格式
test_dify_format() {
log_info "测试Dify文件格式处理..."
# 创建测试JSON数据
test_json='{
"pic": {
"dify_model_identity": "__dify__file__",
"id": null,
"type": "image",
"filename": "test.jpg",
"extension": ".jpg",
"mime_type": "image/jpeg",
"size": 459691,
"url": "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
}
}'
# 测试API
response=$(curl -s -X POST \\
-H "Content-Type: application/json" \\
-d "$test_json" \\
http://localhost:5000/extract 2>/dev/null || echo "")
if [[ -n "$response" ]]; then
log_success "Dify格式测试成功"
echo "响应: $response"
else
log_warning "Dify格式测试失败"
fi
}
# 主函数
main() {
echo
echo "========================================"
echo "修复Dify文件处理问题"
echo "========================================"
echo
# 进入项目目录
cd "$APP_DIR"
# 1. 检查依赖
check_dependencies
echo
# 2. 修复Dify处理逻辑
fix_dify_file_handling
echo
# 3. 重启服务
restart_service
echo
# 4. 测试Dify格式
test_dify_format
echo
echo "========================================"
log_success "Dify文件处理修复完成!"
echo
echo "修复内容:"
echo "1. ✅ 支持Dify文件对象格式"
echo "2. ✅ 自动从Dify URL下载文件"
echo "3. ✅ 保持向后兼容性(支持直接文件上传)"
echo "4. ✅ 增强的错误处理和日志记录"
echo "5. ✅ 新增专门的Dify接口:/extract_dify"
echo
echo "现在在Dify中的配置:"
echo "1. HTTP方法:POST"
echo "2. URL:http://60.205.165.40:5000/extract"
echo "3. Content-Type:application/json"
echo "4. 请求体:直接传递Dify的文件对象"
echo
echo "API现在支持以下格式:"
echo "• Dify文件对象:{\\"pic\\": {...}}"
echo "• 直接文件上传:multipart/form-data"
echo "• URL参数:image_url=http://..."
echo "========================================"
}
# 执行主函数
main "$@"
'''
# 保存脚本
with open('/tmp/fix_dify_file_handling.sh', 'w', encoding='utf-8') as f:
f.write(script_content)
print("✓ 已创建Dify文件处理修复脚本")
print(f"📁 脚本路径: /tmp/fix_dify_file_handling.sh")
print("\n🚀 在服务器上执行以下命令:")
print("cat /tmp/fix_dify_file_handling.sh > fix_dify_file_handling.sh")
print("chmod +x fix_dify_file_handling.sh")
print("./fix_dify_file_handling.sh")