-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_dify_file_object.py
More file actions
897 lines (738 loc) · 28.1 KB
/
fix_dify_file_object.py
File metadata and controls
897 lines (738 loc) · 28.1 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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复Dify文件对象处理的脚本
正确处理Dify传递的文件对象,而不是URL
"""
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_object() {
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 tempfile
import base64
from datetime import datetime
from flask import Flask, request, jsonify, Response
from werkzeug.utils import secure_filename
from werkzeug.exceptions import RequestEntityTooLarge
import uuid
import io
# 导入自定义模块
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 save_uploaded_file(file_storage, filename):
"""
保存上传的文件到临时位置
Args:
file_storage: Flask的FileStorage对象
filename (str): 文件名
Returns:
str: 临时文件路径
"""
try:
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_path = os.path.join(temp_dir, temp_filename)
# 保存文件
file_storage.save(temp_path)
file_size = os.path.getsize(temp_path)
logger.info(f"文件已保存: {temp_path}, 大小: {file_size} bytes")
return temp_path
except Exception as e:
logger.error(f"保存文件失败: {str(e)}")
raise
def process_dify_file_object(dify_data):
"""
处理Dify文件对象
Args:
dify_data (dict): Dify文件对象数据
Returns:
tuple: (file_path, filename)
"""
try:
logger.info(f"处理Dify文件对象: {dify_data}")
# 检查文件类型
if dify_data.get('type') != 'image':
raise ValueError(f"不支持的文件类型: {dify_data.get('type')}")
filename = dify_data.get('filename', 'image.jpg')
mime_type = dify_data.get('mime_type', '')
size = dify_data.get('size', 0)
logger.info(f"文件信息: {filename}, 类型: {mime_type}, 大小: {size}")
# 检查MIME类型
if not mime_type.startswith('image/'):
raise ValueError(f"不是有效的图片文件: {mime_type}")
# 检查文件大小
if size == 0:
raise ValueError("文件大小为0")
# 检查是否包含base64数据
if 'data' in dify_data:
# 如果是base64编码的数据
file_data = base64.b64decode(dify_data['data'])
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_path = os.path.join(temp_dir, temp_filename)
# 写入文件
with open(temp_path, 'wb') as f:
f.write(file_data)
logger.info(f"从base64数据创建文件: {temp_path}")
return temp_path, filename
# 如果有URL字段,尝试下载
elif 'url' in dify_data:
import requests
url = dify_data['url']
logger.info(f"从URL下载文件: {url}")
# 下载文件
response = requests.get(url, timeout=30, stream=True)
response.raise_for_status()
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_path = os.path.join(temp_dir, temp_filename)
# 保存文件
with open(temp_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logger.info(f"从URL下载完成: {temp_path}")
return temp_path, filename
else:
# 如果没有文件数据,可能需要通过其他方式获取
# 这种情况下,我们假设文件已经在请求的其他部分
raise ValueError("Dify文件对象中没有找到文件数据")
except Exception as e:
logger.error(f"处理Dify文件对象失败: {str(e)}")
raise
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查接口"""
return create_response(
success=True,
message='服务运行正常',
data={
'status': 'healthy',
'version': '1.2.0',
'timestamp': datetime.now().isoformat(),
'features': [
'Dify文件对象支持',
'Base64文件处理',
'URL文件下载',
'直接文件上传',
'多种输入格式'
]
}
)
@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请求,数据键: {list(json_data.keys()) if json_data else 'None'}")
# 检查是否直接包含pic字段
if 'pic' in json_data:
pic_data = json_data['pic']
logger.info(f"找到pic字段: {pic_data}")
# 处理Dify文件对象
temp_file_path, filename = process_dify_file_object(pic_data)
# 检查是否是直接的文件数据(可能的格式)
elif 'data' in json_data and 'filename' in json_data:
logger.info("直接处理文件数据")
temp_file_path, filename = process_dify_file_object(json_data)
else:
return create_response(
success=False,
error='INVALID_DIFY_FORMAT',
message='JSON请求中未找到有效的文件对象。期望格式:{"pic": {...}} 或 {"data": "...", "filename": "..."}'
), 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_file_path = save_uploaded_file(file, file.filename)
filename = file.filename
# 方式3:检查是否是base64数据
elif request.form.get('image_data') and request.form.get('filename'):
try:
image_data = request.form.get('image_data')
filename = request.form.get('filename')
# 解码base64
file_data = base64.b64decode(image_data)
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_file_path = os.path.join(temp_dir, temp_filename)
# 写入文件
with open(temp_file_path, 'wb') as f:
f.write(file_data)
logger.info(f"从base64数据创建文件: {temp_file_path}")
except Exception as e:
return create_response(
success=False,
error='BASE64_ERROR',
message=f'处理base64数据失败: {str(e)}'
), 400
# 方式4:检查是否是URL参数
elif request.form.get('image_url'):
import requests
image_url = request.form.get('image_url')
filename = request.form.get('filename', image_url.split('/')[-1])
logger.info(f"从URL下载文件: {image_url}")
try:
response = requests.get(image_url, timeout=30, stream=True)
response.raise_for_status()
# 创建临时文件
temp_dir = tempfile.gettempdir()
temp_filename = f"{uuid.uuid4()}_{secure_filename(filename)}"
temp_file_path = os.path.join(temp_dir, temp_filename)
# 保存文件
with open(temp_file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logger.info(f"从URL下载完成: {temp_file_path}")
except Exception as e:
return create_response(
success=False,
error='URL_DOWNLOAD_ERROR',
message=f'从URL下载文件失败: {str(e)}'
), 400
else:
return create_response(
success=False,
error='MISSING_FILE',
message='未找到图片文件。请提供以下之一:\\n1. 上传image文件\\n2. 传递包含pic的JSON对象\\n3. 传递image_data和filename参数\\n4. 提供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
# 验证文件大小
file_size = os.path.getsize(temp_file_path)
if file_size == 0:
return create_response(
success=False,
error='EMPTY_FILE',
message='处理后的文件为空'
), 400
# 验证文件格式
try:
from PIL import Image
with Image.open(temp_file_path) as img:
img.verify() # 验证图片文件
logger.info("图片文件验证通过")
except Exception as e:
return create_response(
success=False,
error='INVALID_IMAGE',
message=f'不是有效的图片文件: {str(e)}'
), 400
# 提取图片信息
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}, 文件: {filename}, 大小: {file_size} bytes")
# 返回结果
return create_response(
success=True,
data=image_info,
message='图片信息提取成功'
)
except Exception as e:
logger.error(f"处理图片时发生错误: {str(e)}", exc_info=True)
return create_response(
success=False,
error='PROCESSING_ERROR',
message=f'处理图片时发生错误: {str(e)}'
), 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('/debug', methods=['POST'])
def debug_request():
"""
调试接口,显示接收到的请求信息
"""
try:
debug_info = {
'method': request.method,
'content_type': request.content_type,
'is_json': request.is_json,
'files': list(request.files.keys()),
'form_data': dict(request.form),
'json_data': request.get_json() if request.is_json else None,
'headers': dict(request.headers)
}
return create_response(
success=True,
message='请求调试信息',
data=debug_info
)
except Exception as e:
return create_response(
success=False,
error='DEBUG_ERROR',
message=f'调试失败: {str(e)}'
), 500
@app.route('/info', methods=['GET'])
def get_api_info():
"""获取API信息"""
return create_response(
success=True,
message='图片信息提取API',
data={
'name': '图片信息提取API',
'version': '1.2.0',
'description': '提取图片的EXIF信息,包括拍摄时间和GPS位置',
'supported_formats': {
'file_upload': ['multipart/form-data'],
'dify_object': ['application/json'],
'base64_data': ['application/x-www-form-urlencoded'],
'url_upload': ['application/x-www-form-urlencoded']
},
'dify_support': {
'file_objects': True,
'base64_data': True,
'url_download': True,
'direct_upload': True
},
'endpoints': {
'health': {
'method': 'GET',
'path': '/health',
'description': '健康检查'
},
'extract': {
'method': 'POST',
'path': '/extract',
'description': '提取图片信息(支持多种格式)',
'formats': [
'文件上传: image file',
'Dify对象: {"pic": {...}}',
'Base64数据: image_data=..., filename=...',
'URL参数: image_url=http://...'
]
},
'extract_dify': {
'method': 'POST',
'path': '/extract_dify',
'description': '专门处理Dify文件对象'
},
'debug': {
'method': 'POST',
'path': '/debug',
'description': '调试请求信息'
},
'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.content_type
content_length = request.content_length
logger.info(f"收到请求: {request.method} {request.path}")
logger.info(f"Content-Type: {content_type}, Content-Length: {content_length}")
logger.info(f"客户端IP: {client_ip}")
if content_type:
if content_type.startswith('multipart/form-data'):
logger.info(f"上传的文件字段: {list(request.files.keys())}")
elif content_type == 'application/json':
logger.info(f"JSON请求体: {request.get_json()}")
elif content_type == 'application/x-www-form-urlencoded':
logger.info(f"表单字段: {list(request.form.keys())}")
@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. Base64编码数据")
logger.info(" 4. URL文件下载")
logger.info("新增调试功能:")
logger.info(" - /debug 接口用于查看请求详情")
logger.info(" - 详细的请求日志记录")
logger.info(" - 多种Dify文件格式支持")
# 启动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
}
# 检查是否需要安装额外的依赖
check_dependencies() {
log_info "检查依赖包..."
cd "$APP_DIR"
source "$APP_DIR/image_extractor_env/bin/activate"
# 检查PIL是否已安装
python -c "from PIL import Image" 2>/dev/null
if [ $? -ne 0 ]; then
log_info "安装Pillow包..."
pip install Pillow
log_success "Pillow包安装完成"
else
log_success "Pillow包已存在"
fi
# 检查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 "服务健康检查通过"
echo "健康检查响应:"
echo "$response" | head -20
else
log_warning "服务健康检查失败,查看日志..."
if [[ -f "logs/app.log" ]]; then
echo "最近日志:"
tail -10 logs/app.log
fi
fi
}
# 测试调试接口
test_debug_interface() {
log_info "测试调试接口..."
# 创建测试数据
test_data='{
"pic": {
"dify_model_identity": "__dify__file__",
"id": null,
"type": "image",
"filename": "test.jpg",
"mime_type": "image/jpeg",
"size": 459691
}
}'
# 测试调试接口
response=$(curl -s -X POST \\
-H "Content-Type: application/json" \\
-d "$test_data" \\
http://localhost:5000/debug 2>/dev/null || echo "")
if [[ -n "$response" ]]; then
log_success "调试接口测试成功"
echo "调试信息:"
echo "$response"
else
log_warning "调试接口测试失败"
fi
}
# 主函数
main() {
echo
echo "========================================"
echo "修复Dify文件对象处理问题"
echo "========================================"
echo
# 进入项目目录
cd "$APP_DIR"
# 1. 检查依赖
check_dependencies
echo
# 2. 修复Dify文件对象处理逻辑
fix_dify_file_object
echo
# 3. 重启服务
restart_service
echo
# 4. 测试调试接口
test_debug_interface
echo
echo "========================================"
log_success "Dify文件对象处理修复完成!"
echo
echo "修复内容:"
echo "1. ✅ 正确处理Dify文件对象格式"
echo "2. ✅ 支持多种文件数据格式"
echo "3. ✅ 增强的错误处理和验证"
echo "4. ✅ 详细的调试功能"
echo "5. ✅ 图片文件验证"
echo "6. ✅ 完整的日志记录"
echo
echo "支持的Dify文件格式:"
echo "• 标准文件对象:{\\"pic\\": {\\"type\\": \\"image\\", \\"data\\": \\"base64...", \\"filename\\": \\"...\\"}}"
echo "• URL下载:{\\"pic\\": {\\"url\\": \\"http://...", \\"filename\\": \\"...\\"}}"
echo "• 直接数据:{\\"data\\": \\"base64...", \\"filename\\": \\"...\\"}"
echo
echo "新增调试功能:"
echo "• /debug 接口:查看请求详情"
echo "• 详细日志:记录所有请求信息"
echo "• 文件验证:自动验证图片格式"
echo "• 错误追踪:完整的错误信息"
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 "如果仍有问题,可以使用调试接口:"
echo "curl -X POST -H \\"Content-Type: application/json\\" -d '{\\"pic\\": {...}}' http://60.205.165.40:5000/debug"
echo "========================================"
}
# 执行主函数
main "$@"
'''
# 保存脚本
with open('/tmp/fix_dify_file_object.sh', 'w', encoding='utf-8') as f:
f.write(script_content)
print("✓ 已创建Dify文件对象处理修复脚本")
print(f"📁 脚本路径: /tmp/fix_dify_file_object.sh")
print("\n🚀 在服务器上执行以下命令:")
print("cat /tmp/fix_dify_file_object.sh > fix_dify_file_object.sh")
print("chmod +x fix_dify_file_object.sh")
print("./fix_dify_file_object.sh")
# 同时创建一个调试脚本
debug_script = '''#!/bin/bash
# 调试Dify请求
echo "调试Dify请求..."
# 使用您提供的实际数据
test_data='{
"pic": {
"dify_model_identity": "__dify__file__",
"id": null,
"tenant_id": "113bd31e-1e5b-47df-95e2-c1013ae008f7",
"type": "image",
"transfer_method": "local_file",
"remote_url": "/files/33333b03-1396-4fed-a520-e874a4782730/file-preview?timestamp=1764870269&nonce=093c14ac7b3f65917aa684fc2ee6d77e&sign=n98lkqzcOGAN2kSvLdhZGOMYPl4FtarbUGXXxJRVkf0%3D",
"related_id": "33333b03-1396-4fed-a520-e874a4782730",
"filename": "测试.jpg",
"extension": ".jpg",
"mime_type": "image/jpeg",
"size": 459691,
"url": "/files/33333b03-1396-4fed-a520-e874a4782730/file-preview?timestamp=1764871231&nonce=8fa6b33788615987a10dfdcc2e203d84&sign=P2P2U4AkirQKJ89IQYmEC4ru4zJUEYZdmXsKEQbwDg8%3D"
}
}'
echo "发送调试请求..."
curl -s -X POST \\
-H "Content-Type: application/json" \\
-d "$test_data" \\
http://60.205.165.40:5000/debug
echo
echo "如果调试接口返回了正确的请求信息,说明API能正确接收Dify的数据。"
echo "接下来可以尝试实际的提取接口:"
echo "curl -s -X POST -H \\"Content-Type: application/json\\" -d '$test_data' http://60.205.165.40:5000/extract"
'''
with open('/tmp/debug_dify_request.sh', 'w', encoding='utf-8') as f:
f.write(debug_script)
print("\n🔍 调试脚本也已创建:")
print("cat /tmp/debug_dify_request.sh > debug_dify_request.sh")
print("chmod +x debug_dify_request.sh")
print("./debug_dify_request.sh")
print("\n📋 问题分析总结:")
print("您说得对!Dify应该直接传递文件对象,而不是URL。")
print("新的修复脚本将:")
print("• 正确处理Dify的文件对象格式")
print("• 支持base64编码的文件数据")
print("• 如果有URL,则下载文件")
print("• 提供详细的调试信息")
print("• 增强的错误处理和验证")