yangtb24 commited on
Commit
61c5c21
·
verified ·
1 Parent(s): d9647ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -259
app.py CHANGED
@@ -840,274 +840,45 @@ def handsome_images_generations():
840
 
841
  response_data = {}
842
 
843
- if "stable-diffusion" in model_name:
 
 
844
  siliconflow_data = {
845
  "model": model_name,
846
  "prompt": data.get("prompt"),
847
- "image_size": data.get("size", "1024x1024"),
848
- "batch_size": data.get("n", 1),
849
- "num_inference_steps": data.get("steps", 20),
850
- "guidance_scale": data.get("guidance_scale", 7.5),
851
- "negative_prompt": data.get("negative_prompt"),
852
- "seed": data.get("seed"),
853
- "prompt_enhancement": False,
854
  }
855
 
856
- # Parameter validation and adjustments
857
- if siliconflow_data["batch_size"] < 1:
858
- siliconflow_data["batch_size"] = 1
859
- if siliconflow_data["batch_size"] > 4:
860
- siliconflow_data["batch_size"] = 4
861
-
862
- if siliconflow_data["num_inference_steps"] < 1:
863
- siliconflow_data["num_inference_steps"] = 1
864
- if siliconflow_data["num_inference_steps"] > 50:
865
- siliconflow_data["num_inference_steps"] = 50
866
-
867
- if siliconflow_data["guidance_scale"] < 0:
868
- siliconflow_data["guidance_scale"] = 0
869
- if siliconflow_data["guidance_scale"] > 100:
870
- siliconflow_data["guidance_scale"] = 100
871
 
872
- if siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024"]:
873
- siliconflow_data["image_size"] = "1024x1024"
874
-
875
- try:
876
- start_time = time.time()
877
- response = requests.post(
878
- "https://api.siliconflow.cn/v1/images/generations",
879
- headers=headers,
880
- json=siliconflow_data,
881
- timeout=120
882
- )
883
-
884
- if response.status_code == 429:
885
- return jsonify(response.json()), 429
886
-
887
- response.raise_for_status()
888
- end_time = time.time()
889
- response_json = response.json()
890
- total_time = end_time - start_time
891
-
892
- try:
893
- images = response_json.get("images", [])
894
- openai_images = []
895
- for item in images:
896
- if isinstance(item, dict) and "url" in item:
897
- image_url = item["url"]
898
- print(f"image_url: {image_url}")
899
- if data.get("response_format") == "b64_json":
900
- try:
901
- image_data = requests.get(image_url, stream=True).raw
902
- image = Image.open(image_data)
903
- buffered = io.BytesIO()
904
- image.save(buffered, format="PNG")
905
- img_str = base64.b64encode(buffered.getvalue()).decode()
906
- openai_images.append({"b64_json": img_str})
907
- except Exception as e:
908
- logging.error(f"图片转base64失败: {e}")
909
- openai_images.append({"url": image_url})
910
- else:
911
- openai_images.append({"url": image_url})
912
- else:
913
- logging.error(f"无效的图片数据: {item}")
914
- openai_images.append({"url": item})
915
-
916
-
917
- response_data = {
918
- "created": int(time.time()),
919
- "data": openai_images
920
- }
921
-
922
- except (KeyError, ValueError, IndexError) as e:
923
- logging.error(
924
- f"解析响应 JSON 失败: {e}, "
925
- f"完整内容: {response_json}"
926
- )
927
- response_data = {
928
- "created": int(time.time()),
929
- "data": []
930
- }
931
-
932
-
933
- logging.info(
934
- f"使用的key: {api_key}, "
935
- f"总共用时: {total_time:.4f}秒, "
936
- f"使用的模型: {model_name}"
937
- )
938
-
939
- with data_lock:
940
- request_timestamps.append(time.time())
941
- token_counts.append(0)
942
-
943
- return jsonify(response_data)
944
-
945
- except requests.exceptions.RequestException as e:
946
- logging.error(f"请求转发异常: {e}")
947
- return jsonify({"error": str(e)}), 500
948
- else:
949
- return jsonify({"error": "Unsupported model"}), 400
950
-
951
- @app.route('/handsome/v1/images/generations', methods=['POST'])
952
- def handsome_images_generations():
953
- if not check_authorization(request):
954
- return jsonify({"error": "Unauthorized"}), 401
955
-
956
- data = request.get_json()
957
- if not data or 'model' not in data:
958
- return jsonify({"error": "Invalid request data"}), 400
959
-
960
- model_name = data.get('model')
961
-
962
- request_type = determine_request_type(
963
- model_name,
964
- image_models,
965
- free_image_models
966
- )
967
-
968
- api_key = select_key(request_type, model_name)
969
 
970
- if not api_key:
971
- return jsonify(
972
- {
973
- "error": (
974
- "No available API key for this "
975
- "request type or all keys have "
976
- "reached their limits"
977
- )
978
- }
979
- ), 429
980
-
981
- headers = {
982
- "Authorization": f"Bearer {api_key}",
983
- "Content-Type": "application/json"
984
- }
985
-
986
- response_data = {}
987
-
988
- if model_name in ["black-forest-labs/FLUX.1-schnell", "Pro/black-forest-labs/FLUX.1-schnell"]:
989
- siliconflow_data = {
990
- "model": model_name,
991
- "prompt": data.get("prompt"),
992
- "image_size": data.get("image_size", "1024x1024"), # Use image_size directly
993
- "seed": data.get("seed"),
994
- "prompt_enhancement": data.get("prompt_enhancement", False),
995
- }
996
- # Parameter validation and adjustments
997
  if siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024"]:
998
  siliconflow_data["image_size"] = "1024x1024"
999
 
1000
- if siliconflow_data["seed"] is not None:
1001
- if not isinstance(siliconflow_data["seed"], int):
1002
- return jsonify({"error": "Invalid seed, must be integer"}), 400
1003
- if not (0 < siliconflow_data["seed"] < 9999999999):
1004
- return jsonify({"error": "Invalid seed, must be between 0 and 9999999999"}), 400
1005
-
1006
- try:
1007
- start_time = time.time()
1008
- response = requests.post(
1009
- "https://api.siliconflow.cn/v1/images/generations",
1010
- headers=headers,
1011
- json=siliconflow_data,
1012
- timeout=120
1013
- )
1014
-
1015
- if response.status_code == 429:
1016
- return jsonify(response.json()), 429
1017
-
1018
- response.raise_for_status()
1019
- end_time = time.time()
1020
- response_json = response.json()
1021
- total_time = end_time - start_time
1022
-
1023
- try:
1024
- images = response_json.get("images", [])
1025
- openai_images = []
1026
- for item in images:
1027
- if isinstance(item, dict) and "url" in item:
1028
- image_url = item["url"]
1029
- print(f"image_url: {image_url}")
1030
- if data.get("response_format") == "b64_json":
1031
- try:
1032
- image_data = requests.get(image_url, stream=True).raw
1033
- image = Image.open(image_data)
1034
- buffered = io.BytesIO()
1035
- image.save(buffered, format="PNG")
1036
- img_str = base64.b64encode(buffered.getvalue()).decode()
1037
- openai_images.append({"b64_json": img_str})
1038
- except Exception as e:
1039
- logging.error(f"图片转base64失败: {e}")
1040
- openai_images.append({"url": image_url})
1041
- else:
1042
- openai_images.append({"url": image_url})
1043
- else:
1044
- logging.error(f"无效的图片数据: {item}")
1045
- openai_images.append({"url": item})
1046
-
1047
-
1048
- response_data = {
1049
- "created": int(time.time()),
1050
- "data": openai_images
1051
- }
1052
-
1053
- except (KeyError, ValueError, IndexError) as e:
1054
- logging.error(
1055
- f"解析响应 JSON 失败: {e}, "
1056
- f"完整内容: {response_json}"
1057
- )
1058
- response_data = {
1059
- "created": int(time.time()),
1060
- "data": []
1061
- }
1062
-
1063
-
1064
- logging.info(
1065
- f"使用的key: {api_key}, "
1066
- f"总共用时: {total_time:.4f}秒, "
1067
- f"使用的模型: {model_name}"
1068
- )
1069
-
1070
- with data_lock:
1071
- request_timestamps.append(time.time())
1072
- token_counts.append(0)
1073
-
1074
- return jsonify(response_data)
1075
-
1076
- except requests.exceptions.RequestException as e:
1077
- logging.error(f"请求转发异常: {e}")
1078
- return jsonify({"error": str(e)}), 500
1079
- elif "stable-diffusion" in model_name:
1080
- siliconflow_data = {
1081
- "model": model_name,
1082
- "prompt": data.get("prompt"),
1083
- "image_size": data.get("size", "1024x1024"),
1084
- "batch_size": data.get("n", 1),
1085
- "num_inference_steps": data.get("steps", 20),
1086
- "guidance_scale": data.get("guidance_scale", 7.5),
1087
- "negative_prompt": data.get("negative_prompt"),
1088
- "seed": data.get("seed"),
1089
- "prompt_enhancement": data.get("prompt_enhancement", False),
1090
- }
1091
-
1092
- # Parameter validation and adjustments
1093
- if siliconflow_data["batch_size"] < 1:
1094
- siliconflow_data["batch_size"] = 1
1095
- if siliconflow_data["batch_size"] > 4:
1096
- siliconflow_data["batch_size"] = 4
1097
-
1098
- if siliconflow_data["num_inference_steps"] < 1:
1099
- siliconflow_data["num_inference_steps"] = 1
1100
- if siliconflow_data["num_inference_steps"] > 50:
1101
- siliconflow_data["num_inference_steps"] = 50
1102
-
1103
- if siliconflow_data["guidance_scale"] < 0:
1104
- siliconflow_data["guidance_scale"] = 0
1105
- if siliconflow_data["guidance_scale"] > 100:
1106
- siliconflow_data["guidance_scale"] = 100
1107
-
1108
- if siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024"]:
1109
- siliconflow_data["image_size"] = "1024x1024"
1110
-
1111
  try:
1112
  start_time = time.time()
1113
  response = requests.post(
@@ -1679,7 +1450,7 @@ def handsome_chat_completions():
1679
 
1680
  except requests.exceptions.RequestException as e:
1681
  logging.error(f"请求转发异常: {e}")
1682
- return jsonify({"error": str(e)}), 500
1683
 
1684
  if __name__ == '__main__':
1685
  import json
 
840
 
841
  response_data = {}
842
 
843
+ if "stable-diffusion" in model_name or model_name in ["black-forest-labs/FLUX.1-schnell", "Pro/black-forest-labs/FLUX.1-schnell"]:
844
+
845
+ # Initialize siliconflow_data with common parameters
846
  siliconflow_data = {
847
  "model": model_name,
848
  "prompt": data.get("prompt"),
849
+ "image_size": data.get("image_size", "1024x1024"), # Use 'image_size' directly
850
+ "prompt_enhancement": data.get("prompt_enhancement", False),
 
 
 
 
 
851
  }
852
 
853
+ # Add seed only if it's provided and valid
854
+ seed = data.get("seed")
855
+ if isinstance(seed, int) and 0 < seed < 9999999999:
856
+ siliconflow_data["seed"] = seed
 
 
 
 
 
 
 
 
 
 
 
857
 
858
+ if model_name not in ["black-forest-labs/FLUX.1-schnell", "Pro/black-forest-labs/FLUX.1-schnell"]:
859
+ siliconflow_data["batch_size"] = data.get("n", 1)
860
+ siliconflow_data["num_inference_steps"] = data.get("steps", 20)
861
+ siliconflow_data["guidance_scale"] = data.get("guidance_scale", 7.5)
862
+ siliconflow_data["negative_prompt"] = data.get("negative_prompt")
863
+ if siliconflow_data["batch_size"] < 1:
864
+ siliconflow_data["batch_size"] = 1
865
+ if siliconflow_data["batch_size"] > 4:
866
+ siliconflow_data["batch_size"] = 4
867
+
868
+ if siliconflow_data["num_inference_steps"] < 1:
869
+ siliconflow_data["num_inference_steps"] = 1
870
+ if siliconflow_data["num_inference_steps"] > 50:
871
+ siliconflow_data["num_inference_steps"] = 50
872
+
873
+ if siliconflow_data["guidance_scale"] < 0:
874
+ siliconflow_data["guidance_scale"] = 0
875
+ if siliconflow_data["guidance_scale"] > 100:
876
+ siliconflow_data["guidance_scale"] = 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
 
878
+ # Validate image_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
879
  if siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024"]:
880
  siliconflow_data["image_size"] = "1024x1024"
881
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
882
  try:
883
  start_time = time.time()
884
  response = requests.post(
 
1450
 
1451
  except requests.exceptions.RequestException as e:
1452
  logging.error(f"请求转发异常: {e}")
1453
+ return jsonify({"error": str(e)}), 500
1454
 
1455
  if __name__ == '__main__':
1456
  import json