code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.Task; import cn.bugstack.middleware.db.router.annotation.DBRouter; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description 任务表,发送MQ * @create 2024-04-03 15:57 */ @Mapper public interface ITaskDao { void insert(Task task); @DBRouter void updateTaskSendMessageCompleted(Task task); @DBRouter void updateTaskSendMessageFail(Task task); List<Task> queryNoSendMessageTaskList(); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/ITaskDao.java
Java
unknown
551
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.UserAwardRecord; import zack.project.infrastructure.persistent.po.UserCredit; import cn.bugstack.middleware.db.router.annotation.DBRouterStrategy; import org.apache.ibatis.annotations.Mapper; /** * @description 用户中奖记录表 * @create 2024-04-03 15:57 */ @Mapper @DBRouterStrategy(splitTable = true) public interface IUserAwardRecordDao { void insert(UserAwardRecord userAwardRecord); int updateAwardRecordCompletedState(UserCredit userAwardRecordReq); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/IUserAwardRecordDao.java
Java
unknown
580
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.UserBehaviorRebateOrder; import cn.bugstack.middleware.db.router.annotation.DBRouter; import cn.bugstack.middleware.db.router.annotation.DBRouterStrategy; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper @DBRouterStrategy(splitTable = true) public interface IUserBehaviorRebateOrderDao { void insert(UserBehaviorRebateOrder userBehaviorRebateOrder); @DBRouter List<UserBehaviorRebateOrder> queryOrderByOutBusinessNo(UserBehaviorRebateOrder userBehaviorRebateOrder); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/IUserBehaviorRebateOrderDao.java
Java
unknown
614
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.UserCreditAccount; import org.apache.ibatis.annotations.Mapper; /** * @author A1793 */ @Mapper public interface IUserCreditAccountDao { void insert(UserCreditAccount userCreditAccountReq); int updateAddAmount(UserCreditAccount userCreditAccountReq); UserCreditAccount queryUserCreditAccount(UserCreditAccount userCreditAccountReq); int updateSubtractionAmount(UserCreditAccount userCreditAccountReq); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/IUserCreditAccountDao.java
Java
unknown
529
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.UserCreditOrder; import cn.bugstack.middleware.db.router.annotation.DBRouterStrategy; import org.apache.ibatis.annotations.Mapper; @Mapper @DBRouterStrategy(splitTable = true) public interface IUserCreditOrderDao { void insert(UserCreditOrder userCreditOrderReq); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/IUserCreditOrderDao.java
Java
unknown
376
package zack.project.infrastructure.persistent.dao; import zack.project.infrastructure.persistent.po.UserRaffleOrder; import cn.bugstack.middleware.db.router.annotation.DBRouter; import cn.bugstack.middleware.db.router.annotation.DBRouterStrategy; import org.apache.ibatis.annotations.Mapper; /** * @description 用户抽奖订单表 * @create 2024-04-03 15:57 */ @Mapper @DBRouterStrategy(splitTable = true) public interface IUserRaffleOrderDao { @DBRouter UserRaffleOrder queryNoUsedRaffleOrder(UserRaffleOrder order); void insert(UserRaffleOrder build); int updateUserRaffleOrderStateUsed(UserRaffleOrder userRaffleOrderReq); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/dao/IUserRaffleOrderDao.java
Java
unknown
654
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; @Data public class Award { /** 自增ID*/ private Long id; /** 抽奖奖品ID - 内部流转使用*/ private Integer awardId; /** 奖品对接标识 - 每一个都是一个对应的发奖策略*/ private String awardKey; /** 奖品配置信息*/ private String awardConfig; /** */ private String awardDesc; /** 奖品内容描述*/ private Date createTime; /** 创建时间*/ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/Award.java
Java
unknown
557
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @author A1793 */ @Data public class DailyBehaviorRebate { //自增ID private Integer id; //行为类型(sign 签到、openai_pay 支付) private String behaviorType; //返利描述 private String rebateDesc; //返利类型(sku 活动库存充值商品、integral 用户活动积分) private String rebateType; //返利配置 private String rebateConfig; //状态(open 开启、close 关闭) private String state; //创建时间 private Date createTime; //更新时间 private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/DailyBehaviorRebate.java
Java
unknown
630
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @author A1793 * @description 抽奖活动表 持久化对象 * @create 2024-03-02 13:06 */ @Data public class RaffleActivity { /** * 自增ID */ private Long id; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; /** * 活动描述 */ private String activityDesc; /** * 开始时间 */ private Date beginDateTime; /** * 结束时间 */ private Date endDateTime; /** * 抽奖策略ID */ private Long strategyId; /** * 活动状态 */ private String state; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivity.java
Java
unknown
893
package zack.project.infrastructure.persistent.po; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author A1793 * @description 抽奖活动账户表 持久化对象 * @create 2024-03-02 13:15 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class RaffleActivityAccount { /** * 自增ID */ private Long id; /** * 用户ID */ private String userId; /** * 活动ID */ private Long activityId; /** * 总次数 */ private Integer totalCount; /** * 总次数-剩余 */ private Integer totalCountSurplus; /** * 日次数 */ private Integer dayCount; /** * 活动次数编号 */ private Long activityCountId; /** * 日次数-剩余 */ private Integer dayCountSurplus; /** * 月次数 */ private Integer monthCount; /** * 月次数-剩余 */ private Integer monthCountSurplus; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivityAccount.java
Java
unknown
1,206
package zack.project.infrastructure.persistent.po; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.text.SimpleDateFormat; import java.util.Date; /** * @description 抽奖活动账户表-日次数 * @create 2024-04-03 15:28 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class RaffleActivityAccountDay { private static final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd"); /** 自增ID */ private Long id; /** 用户ID */ private String userId; /** 活动ID */ private Long activityId; /** 日期(yyyy-mm-dd) */ private String day; /** 日次数 */ private Integer dayCount; /** 日次数-剩余 */ private Integer dayCountSurplus; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public static String curDay(){ return dateFormatDay.format(new Date()); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivityAccountDay.java
Java
unknown
1,006
package zack.project.infrastructure.persistent.po; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.text.SimpleDateFormat; import java.util.Date; /** * @description 抽奖活动账户表-月次数 * @create 2024-04-03 15:28 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class RaffleActivityAccountMonth { private static final SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM"); /** 自增ID */ private Long id; /** 用户ID */ private String userId; /** 活动ID */ private Long activityId; /** 月(yyyy-mm) */ private String month; /** 月次数 */ private Integer monthCount; /** 月次数-剩余 */ private Integer monthCountSurplus; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public static String currentMonth() { return dateFormatMonth.format(new Date()); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivityAccountMonth.java
Java
unknown
1,016
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @author A1793 * @description 抽奖活动次数配置表 持久化对象 * @create 2024-03-02 13:13 */ @Data public class RaffleActivityCount { /** * 自增ID */ private Long id; /** * 活动次数编号 */ private Long activityCountId; /** * 总次数 */ private Integer totalCount; /** * 日次数 */ private Integer dayCount; /** * 月次数 */ private Integer monthCount; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivityCount.java
Java
unknown
715
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author A1793 * @description 抽奖活动单 持久化对象 * @create 2024-03-02 13:21 */ @Data public class RaffleActivityOrder { /** * 自增ID */ private Long id; /** * 用户ID */ private String userId; private Long sku; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; /** * 抽奖策略ID */ private Long strategyId; /** * 订单ID */ private String orderId; /** * 下单时间 */ private Date orderTime; /** * 总次数 */ private Integer totalCount; /** * 日次数 */ private Integer dayCount; /** * 月次数 */ private Integer monthCount; /** * 订单状态(not_used、used、expire) */ private String state; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; private String outBusinessNo; private BigDecimal payAmount; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivityOrder.java
Java
unknown
1,225
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @description 抽奖活动sku持久化对象 * @create 2024-03-16 10:54 */ @Data public class RaffleActivitySku { private Long id; /** * 商品sku */ private Long sku; /** * 活动ID */ private Long activityId; /** * 活动个人参与次数ID */ private Long activityCountId; /** * 库存总量 */ private Integer stockCount; /** * 剩余库存 */ private Integer stockCountSurplus; private BigDecimal payAmount; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RaffleActivitySku.java
Java
unknown
783
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /**规则树 * @author A1793 */ @Data public class RuleTree { /** 自增ID */ private Long id; /** 规则树ID */ private String treeId; /** 规则树名称 */ private String treeName; /** 规则树描述 */ private String treeDesc; /** 规则根节点 */ private String treeRootRuleKey; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RuleTree.java
Java
unknown
538
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** 规则树节点 * @author A1793 */ @Data public class RuleTreeNode { /** 自增ID */ private Long id; /** 规则节点所属的规则树的ID */ private String treeId; /** 规则节点的Key */ private String ruleKey; /** 规则节点描述 */ private String ruleDesc; /** 规则节点比值 */ private String ruleValue; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RuleTreeNode.java
Java
unknown
575
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /**规则树节点连接关系 * @author A1793 */ @Data public class RuleTreeNodeLine { /** 自增ID */ private Long id; /** 规则树ID */ private String treeId; /** 规则Key节点 From */ private String ruleNodeFrom; /** 规则Key节点 To */ private String ruleNodeTo; /** 限定类型;1:=;2:>;3:<;4:>=;5<=;6:enum[枚举范围] */ private String ruleLimitType; /** 限定值(到下个节点),ALLOW 或 TAKEOVER */ private String ruleLimitValue; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/RuleTreeNodeLine.java
Java
unknown
709
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; @Data public class Strategy { /** 自增ID*/ private Long id; /** 抽奖策略ID*/ private Long strategyId; /** 抽奖策略描述*/ private String strategyDesc; /** 规则模型,rule配置的模型同步到此表,便于使用*/ private String ruleModels; /** 创建时间*/ private Date createTime; /** 更新时间*/ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/Strategy.java
Java
unknown
448
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class StrategyAward { /** 自增ID */ private Long id; /** 抽奖策略ID */ private Long strategyId; /** 抽奖奖品ID - 内部流转使用 */ private Integer awardId; /** 抽奖奖品标题 */ private String awardTitle; /** 抽奖奖品副标题 */ private String awardSubtitle; /** 奖品库存总量 */ private Integer awardCount; /** 奖品库存剩余 */ private Integer awardCountSurplus; /** 奖品中奖概率 */ private BigDecimal awardRate; /** 规则模型,rule配置的模型同步到此表,便于使用 */ private String ruleModels; /** 排序 */ private Integer sort; /** 创建时间 */ private Date createTime; /** 修改时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/StrategyAward.java
Java
unknown
916
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; @Data public class StrategyRule { /** 自增ID*/ private Long id; /** 抽奖策略ID*/ private Long strategyId; /** 抽奖奖品ID【规则类型为策略,则不需要奖品ID】*/ private Integer awardId; /** 抽象规则类型;1-策略规则、2-奖品规则*/ private Integer ruleType; /** 抽奖规则类型【rule_random - 随机值计算、rule_lock - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)】*/ private String ruleModel; /** 抽奖规则比值*/ private String ruleValue; /** 抽奖规则描述*/ private String ruleDesc; /** 创建时间*/ private Date createTime; /** 更新时间*/ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/StrategyRule.java
Java
unknown
821
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @description 任务表,发送MQ * @create 2024-04-03 15:30 */ @Data public class Task { /** 自增ID */ private String id; private String userId; /** 消息主题 */ private String topic; private String messageId; /** 消息主体 */ private String message; /** 任务状态;create-创建、completed-完成、fail-失败 */ private String state; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/Task.java
Java
unknown
610
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @description 用户中奖记录表 * @create 2024-04-03 15:30 */ @Data public class UserAwardRecord { /** 自增ID */ private String id; /** 用户ID */ private String userId; /** 活动ID */ private Long activityId; /** 抽奖策略ID */ private Long strategyId; /** 抽奖订单ID【作为幂等使用】 */ private String orderId; /** 奖品ID */ private Integer awardId; /** 奖品标题(名称) */ private String awardTitle; /** 中奖时间 */ private Date awardTime; /** 奖品状态;create-创建、completed-发奖完成 */ private String awardState; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserAwardRecord.java
Java
unknown
854
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @author A1793 */ @Data public class UserBehaviorRebateOrder { /** 自增ID */ private Long id; /** 用户ID */ private String userId; /** 订单ID */ private String orderId; /** 行为类型(sign 签到、openai_pay 支付) */ private String behaviorType; /** 返利描述 */ private String rebateDesc; /** 返利类型(sku 活动库存充值商品、integral 用户活动积分) */ private String rebateType; /** 返利配置【sku值,积分值】 */ private String rebateConfig; /** 业务ID - 拼接的唯一值 */ private String bizId; /** 业务仿重ID - 外部透传,方便查询使用 */ private String outBusinessNo; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserBehaviorRebateOrder.java
Java
unknown
927
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.util.Date; /** * @description 用户中奖记录表 * @create 2024-04-03 15:30 */ @Data public class UserCredit { /** 自增ID */ private String id; /** 用户ID */ private String userId; /** 活动ID */ private Long activityId; /** 抽奖策略ID */ private Long strategyId; /** 抽奖订单ID【作为幂等使用】 */ private String orderId; /** 奖品ID */ private Integer awardId; /** 奖品标题(名称) */ private String awardTitle; /** 中奖时间 */ private Date awardTime; /** 奖品状态;create-创建、completed-发奖完成 */ private String awardState; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserCredit.java
Java
unknown
849
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author A1793 */ @Data public class UserCreditAccount { /** 自增ID */ private Long id; /** 用户ID */ private String userId; /** 总积分,显示总账户值,记得一个人获得的总积分 */ private BigDecimal totalAmount; /** 可用积分,每次扣减的值 */ private BigDecimal availableAmount; /** 账户状态【open - 可用,close - 冻结】 */ private String accountStatus; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserCreditAccount.java
Java
unknown
682
package zack.project.infrastructure.persistent.po; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author A1793 */ @Data public class UserCreditOrder { /** 自增ID */ private Long id; /** 用户ID */ private String userId; /** 订单ID */ private String orderId; /** 交易名称 */ private String tradeName; /** 交易类型;交易类型;forward-正向、reverse-逆向 */ private String tradeType; /** 交易金额 */ private BigDecimal tradeAmount; /** 业务仿重ID - 外部透传。返利、行为等唯一标识 */ private String outBusinessNo; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserCreditOrder.java
Java
unknown
759
package zack.project.infrastructure.persistent.po; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @description 用户抽奖订单表 * @create 2024-04-03 15:30 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class UserRaffleOrder { /** 用户ID */ private String id; /** 活动ID */ private String userId; /** 活动名称 */ private Long activityId; /** 抽奖策略ID */ private String activityName; /** 订单ID */ private Long strategyId; /** 下单时间 */ private String orderId; /** 订单状态;create-创建、used-已使用、cancel-已作废 */ private Date orderTime; /** 创建时间 */ private String orderState; /** 更新时间 */ private Date createTime; /** */ private Date updateTime; }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/po/UserRaffleOrder.java
Java
unknown
906
package zack.project.infrastructure.persistent.redis; import org.redisson.api.*; import java.util.concurrent.TimeUnit; /** * Redis 服务 * */ public interface IRedisService { void setAtomicLong(String key, long value); Long getAtomicLong(String key); /** * 设置指定 key 的值 * * @param key 键 * @param value 值 */ <T> void setValue(String key, T value); /** * 设置指定 key 的值 * * @param key 键 * @param value 值 * @param expired 过期时间 */ <T> void setValue(String key, T value, long expired); /** * 获取指定 key 的值 * * @param key 键 * @return 值 */ <T> T getValue(String key); /** * 获取队列 * * @param key 键 * @param <T> 泛型 * @return 队列 */ <T> RQueue<T> getQueue(String key); /** * 加锁队列 * * @param key 键 * @param <T> 泛型 * @return 队列 */ <T> RBlockingQueue<T> getBlockingQueue(String key); /** * 延迟队列 * * @param rBlockingQueue 加锁队列 * @param <T> 泛型 * @return 队列 */ <T> RDelayedQueue<T> getDelayedQueue(RBlockingQueue<T> rBlockingQueue); /** * 自增 Key 的值;1、2、3、4 * * @param key 键 * @return 自增后的值 */ long incr(String key); /** * 指定值,自增 Key 的值;1、2、3、4 * * @param key 键 * @return 自增后的值 */ long incrBy(String key, long delta); /** * 自减 Key 的值;1、2、3、4 * * @param key 键 * @return 自增后的值 */ long decr(String key); /** * 指定值,自增 Key 的值;1、2、3、4 * * @param key 键 * @return 自增后的值 */ long decrBy(String key, long delta); /** * 移除指定 key 的值 * * @param key 键 */ void remove(String key); /** * 判断指定 key 的值是否存在 * * @param key 键 * @return true/false */ boolean isExists(String key); /** * 将指定的值添加到集合中 * * @param key 键 * @param value 值 */ void addToSet(String key, String value); /** * 判断指定的值是否是集合的成员 * * @param key 键 * @param value 值 * @return 如果是集合的成员返回 true,否则返回 false */ boolean isSetMember(String key, String value); /** * 将指定的值添加到列表中 * * @param key 键 * @param value 值 */ void addToList(String key, String value); /** * 获取列表中指定索引的值 * * @param key 键 * @param index 索引 * @return 值 */ String getFromList(String key, int index); /** * 获取Map * * @param key 键 * @return 值 */ <K, V> RMap<K, V> getMap(String key); /** * 将指定的键值对添加到哈希表中 * * @param key 键 * @param field 字段 * @param value 值 */ void addToMap(String key, String field, String value); /** * 获取哈希表中指定字段的值 * * @param key 键 * @param field 字段 * @return 值 */ String getFromMap(String key, String field); /** * 获取哈希表中指定字段的值 * * @param key 键 * @param field 字段 * @return 值 */ <K, V> V getFromMap(String key, K field); /** * 将指定的值添加到有序集合中 * * @param key 键 * @param value 值 */ void addToSortedSet(String key, String value); /** * 获取 Redis 锁(可重入锁) * * @param key 键 * @return Lock */ RLock getLock(String key); /** * 获取 Redis 锁(公平锁) * * @param key 键 * @return Lock */ RLock getFairLock(String key); /** * 获取 Redis 锁(读写锁) * * @param key 键 * @return RReadWriteLock */ RReadWriteLock getReadWriteLock(String key); /** * 获取 Redis 信号量 * * @param key 键 * @return RSemaphore */ RSemaphore getSemaphore(String key); /** * 获取 Redis 过期信号量 * <p> * 基于Redis的Redisson的分布式信号量(Semaphore)Java对象RSemaphore采用了与java.util.concurrent.Semaphore相似的接口和用法。 * 同时还提供了异步(Async)、反射式(Reactive)和RxJava2标准的接口。 * * @param key 键 * @return RPermitExpirableSemaphore */ RPermitExpirableSemaphore getPermitExpirableSemaphore(String key); /** * 闭锁 * * @param key 键 * @return RCountDownLatch */ RCountDownLatch getCountDownLatch(String key); /** * 布隆过滤器 * * @param key 键 * @param <T> 存放对象 * @return 返回结果 */ <T> RBloomFilter<T> getBloomFilter(String key); boolean setNx(String lockKey); boolean setNx(String lockKey, Long expire, TimeUnit timeUnit); }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/redis/IRedisService.java
Java
unknown
5,262
package zack.project.infrastructure.persistent.redis; import org.redisson.api.*; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.time.Duration; import java.util.concurrent.TimeUnit; /** * Redis 服务 - Redisson * */ @Service("redissonService") public class RedissonService implements IRedisService { @Resource private RedissonClient redissonClient; @Override public <T> void setValue(String key, T value) { redissonClient.<T>getBucket(key).set(value); } @Override public <T> void setValue(String key, T value, long expired) { RBucket<T> bucket = redissonClient.getBucket(key); bucket.set(value, Duration.ofMillis(expired)); } @Override public <T> T getValue(String key) { return redissonClient.<T>getBucket(key).get(); } @Override public <T> RQueue<T> getQueue(String key) { return redissonClient.getQueue(key); } @Override public <T> RBlockingQueue<T> getBlockingQueue(String key) { return redissonClient.getBlockingQueue(key); } @Override public <T> RDelayedQueue<T> getDelayedQueue(RBlockingQueue<T> rBlockingQueue) { return redissonClient.getDelayedQueue(rBlockingQueue); } @Override public void setAtomicLong(String key, long value) { redissonClient.getAtomicLong(key).set(value); } @Override public Long getAtomicLong(String key) { return redissonClient.getAtomicLong(key).get(); } @Override public long incr(String key) { return redissonClient.getAtomicLong(key).incrementAndGet(); } @Override public long incrBy(String key, long delta) { return redissonClient.getAtomicLong(key).addAndGet(delta); } @Override public long decr(String key) { return redissonClient.getAtomicLong(key).decrementAndGet(); } @Override public long decrBy(String key, long delta) { return redissonClient.getAtomicLong(key).addAndGet(-delta); } @Override public void remove(String key) { redissonClient.getBucket(key).delete(); } @Override public boolean isExists(String key) { return redissonClient.getBucket(key).isExists(); } @Override public void addToSet(String key, String value) { RSet<String> set = redissonClient.getSet(key); set.add(value); } @Override public boolean isSetMember(String key, String value) { RSet<String> set = redissonClient.getSet(key); return set.contains(value); } @Override public void addToList(String key, String value) { RList<String> list = redissonClient.getList(key); list.add(value); } @Override public String getFromList(String key, int index) { RList<String> list = redissonClient.getList(key); return list.get(index); } @Override public <K, V> RMap<K, V> getMap(String key) { return redissonClient.getMap(key); } @Override public void addToMap(String key, String field, String value) { RMap<String, String> map = redissonClient.getMap(key); map.put(field, value); } @Override public String getFromMap(String key, String field) { RMap<String, String> map = redissonClient.getMap(key); return map.get(field); } @Override public <K, V> V getFromMap(String key, K field) { return redissonClient.<K, V>getMap(key).get(field); } @Override public void addToSortedSet(String key, String value) { RSortedSet<String> sortedSet = redissonClient.getSortedSet(key); sortedSet.add(value); } @Override public RLock getLock(String key) { return redissonClient.getLock(key); } @Override public RLock getFairLock(String key) { return redissonClient.getFairLock(key); } @Override public RReadWriteLock getReadWriteLock(String key) { return redissonClient.getReadWriteLock(key); } @Override public RSemaphore getSemaphore(String key) { return redissonClient.getSemaphore(key); } @Override public RPermitExpirableSemaphore getPermitExpirableSemaphore(String key) { return redissonClient.getPermitExpirableSemaphore(key); } @Override public RCountDownLatch getCountDownLatch(String key) { return redissonClient.getCountDownLatch(key); } @Override public <T> RBloomFilter<T> getBloomFilter(String key) { return redissonClient.getBloomFilter(key); } @Override public boolean setNx(String key) { return redissonClient.getBucket(key).trySet("lock"); } @Override public boolean setNx(String lockKey, Long expire, TimeUnit timeUnit) { return redissonClient.getBucket(lockKey).trySet("lock", expire, timeUnit); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/redis/RedissonService.java
Java
unknown
4,887
package zack.project.infrastructure.persistent.repository; import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RBlockingQueue; import org.redisson.api.RDelayedQueue; import org.redisson.api.RLock; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionTemplate; import zack.project.domain.activity.adapter.repository.IActivityRepository; import zack.project.domain.activity.event.ActivitySkuStockZeroMessageEvent; import zack.project.domain.activity.model.aggregate.CreatePartakeOrderAggregate; import zack.project.domain.activity.model.aggregate.CreateQuotaOrderAggregate; import zack.project.domain.activity.model.entity.*; import zack.project.domain.activity.model.valobj.ActivitySkuStockKeyVO; import zack.project.domain.activity.model.valobj.ActivityStateVO; import zack.project.domain.activity.model.valobj.UserRaffleOrderStateVO; import zack.project.infrastructure.event.EventPublisher; import zack.project.infrastructure.persistent.dao.*; import zack.project.infrastructure.persistent.po.*; import zack.project.infrastructure.persistent.redis.IRedisService; import zack.project.types.common.Constants; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import javax.annotation.Resource; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author A1793 */ @Slf4j @Repository public class ActivityRepository implements IActivityRepository { @Resource private IRedisService redisService; @Resource private IRaffleActivitySkuDao activitySkuDao; @Resource private IRaffleActivityDao activityDao; @Resource private IRaffleActivityCountDao activityCountDao; @Resource private IRaffleActivityAccountDao activityAccountDao; @Resource private IRaffleActivityOrderDao activityOrderDao; @Resource private IUserRaffleOrderDao userRaffleOrderDao; @Resource private IRaffleActivityAccountDayDao activityAccountDayDao; @Resource private IRaffleActivityAccountMonthDao activityAccountMonthDao; @Resource private IUserCreditAccountDao userCreditAccountDao; @Resource private TransactionTemplate transactionTemplate; @Resource private IDBRouterStrategy dbRouter; @Resource private ActivitySkuStockZeroMessageEvent activitySkuStockZeroMessageEvent; @Resource private EventPublisher eventPublisher; @Override public ActivitySkuEntity queryActivitySku(Long sku) { RaffleActivitySku raffleActivitySku = activitySkuDao.queryActivitySku(sku); return ActivitySkuEntity.builder() .sku(raffleActivitySku.getSku()) .activityId(raffleActivitySku.getActivityId()) .activityCountId(raffleActivitySku.getActivityCountId()) .stockCount(raffleActivitySku.getStockCount()) .stockCountSurplus(raffleActivitySku.getStockCountSurplus()) .productAmount(raffleActivitySku.getPayAmount()) .build(); } @Override public ActivityEntity queryRaffleActivityByActivityId(Long activityId) { String cacheKey = Constants.RedisKey.ACTIVITY_KEY + activityId; ActivityEntity activityEntity = redisService.getValue(cacheKey); if (activityEntity != null) { return activityEntity; } RaffleActivity raffleActivity = activityDao.queryRaffleActivityByActivityId(activityId); ActivityEntity build = ActivityEntity.builder() .activityId(raffleActivity.getActivityId()) .activityName(raffleActivity.getActivityName()) .activityDesc(raffleActivity.getActivityDesc()) .beginDateTime(raffleActivity.getBeginDateTime()) .endDateTime(raffleActivity.getEndDateTime()) .strategyId(raffleActivity.getStrategyId()) .state(ActivityStateVO.valueOf(raffleActivity.getState())) .build(); redisService.setValue(cacheKey, build); return build; } @Override public ActivityCountEntity queryRaffleActivityCountByActivityCountId(Long activityCountId) { String cacheKey = Constants.RedisKey.ACTIVITY_COUNT_KEY + activityCountId; ActivityCountEntity activityCountEntity = redisService.getValue(cacheKey); if (activityCountEntity != null) { return activityCountEntity; } RaffleActivityCount raffleActivityCount = activityCountDao.queryRaffleActivityCountByActivityCountId(activityCountId); ActivityCountEntity build = ActivityCountEntity.builder() .activityCountId(raffleActivityCount.getActivityCountId()) .totalCount(raffleActivityCount.getTotalCount()) .dayCount(raffleActivityCount.getDayCount()) .monthCount(raffleActivityCount.getMonthCount()) .build(); redisService.setValue(cacheKey, build); return build; } @Override public void doSaveCreditPayOrder(CreateQuotaOrderAggregate createOrderAggregate) { try { // 创建交易订单 ActivityOrderEntity activityOrderEntity = createOrderAggregate.getActivityOrderEntity(); RaffleActivityOrder raffleActivityOrder = new RaffleActivityOrder(); raffleActivityOrder.setUserId(activityOrderEntity.getUserId()); raffleActivityOrder.setSku(activityOrderEntity.getSku()); raffleActivityOrder.setActivityId(activityOrderEntity.getActivityId()); raffleActivityOrder.setActivityName(activityOrderEntity.getActivityName()); raffleActivityOrder.setStrategyId(activityOrderEntity.getStrategyId()); raffleActivityOrder.setOrderId(activityOrderEntity.getOrderId()); raffleActivityOrder.setOrderTime(activityOrderEntity.getOrderTime()); //设置充值抽奖次数的配置 raffleActivityOrder.setTotalCount(activityOrderEntity.getTotalCount()); raffleActivityOrder.setDayCount(activityOrderEntity.getDayCount()); raffleActivityOrder.setMonthCount(activityOrderEntity.getMonthCount()); raffleActivityOrder.setTotalCount(createOrderAggregate.getTotalCount()); raffleActivityOrder.setDayCount(createOrderAggregate.getDayCount()); raffleActivityOrder.setMonthCount(createOrderAggregate.getMonthCount()); raffleActivityOrder.setPayAmount(activityOrderEntity.getPayAmount()); raffleActivityOrder.setState(activityOrderEntity.getState().getCode()); raffleActivityOrder.setOutBusinessNo(activityOrderEntity.getOutBusinessNo()); // 以用户ID作为切分键,通过 doRouter 设定路由【这样就保证了下面的操作,都是同一个链接下,也就保证了事务的特性】 dbRouter.doRouter(createOrderAggregate.getUserId()); // 编程式事务 transactionTemplate.execute(status -> { try { activityOrderDao.insert(raffleActivityOrder); return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("写入订单记录,唯一索引冲突 userId: {} activityId: {} sku: {}", activityOrderEntity.getUserId(), activityOrderEntity.getActivityId(), activityOrderEntity.getSku(), e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { dbRouter.clear(); } } @Override public void cacheActivitySkuStockCount(String cacheKey, Integer stockCount) { if (redisService.isExists(cacheKey)) { return; } redisService.setAtomicLong(cacheKey, stockCount); } @Override public boolean subtractionActivitySkuStock(Long sku, String cacheKey, Date endDateTime) { long surplus = redisService.decr(cacheKey); if (surplus < 0) { redisService.setAtomicLong(cacheKey, 0); return false; } //当sku商品库存为0时发一个ActivitySkuStockZeroMessageEvent消息, // ActivitySkuStockZeroCustomer监听并消息, // 将数据库表{raffle_activity_sku}中对应的商品调零并清空redis的中key为:"activity_sku_count_query_key"的消息队列清空 if (surplus == 0) { eventPublisher.publish(activitySkuStockZeroMessageEvent.topic(), activitySkuStockZeroMessageEvent.buildEventMessage(sku)); } String lockKey = cacheKey + Constants.UNDERLINE + surplus; Long exprTime = endDateTime.getTime() - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1); //加一个sku库存抢占锁 Boolean lock = redisService.setNx(lockKey, exprTime, TimeUnit.MILLISECONDS); if (!lock) { log.info("活动sku库存加锁失败 {}", lockKey); } return lock; } @Override public void activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO activitySkuStockKeyVO) { String cacheKey = Constants.RedisKey.ACTIVITY_SKU_COUNT_QUERY_KEY; RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey); RDelayedQueue<ActivitySkuStockKeyVO> delayedQueue = redisService.getDelayedQueue(blockingQueue); delayedQueue.offer(activitySkuStockKeyVO, 3, TimeUnit.SECONDS); } @Override public ActivitySkuStockKeyVO takeQueueValue() { String cacheKey = Constants.RedisKey.ACTIVITY_SKU_COUNT_QUERY_KEY; RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey); return blockingQueue.poll(); } /** * 当通过阻塞队列获得到延时3队列时,向延时队列添加数据; * 当要清空延时队列时先通过阻塞队列获得延时队列,先清除延时队列,再清除阻塞队列 */ @Override public void clearQueueValue() { String cacheKey = Constants.RedisKey.ACTIVITY_SKU_COUNT_QUERY_KEY; RBlockingQueue<Object> blockingQueue = redisService.getBlockingQueue(cacheKey); RDelayedQueue<Object> delayedQueue = redisService.getDelayedQueue(blockingQueue); delayedQueue.clear(); blockingQueue.clear(); } @Override public void updateActivitySkuStock(Long sku) { activitySkuDao.updateActivitySkuStock(sku); } @Override public void clearActivitySkuStock(Long sku) { activitySkuDao.clearActivitySkuStock(sku); } /** * 根据用户id和活动id查询{user_raffle_order}表是否对应的状态为create的抽奖单,没有则返回空 * * @param partakeRaffleActivityEntity * @return */ @Override public UserRaffleOrderEntity queryNoUsedRaffleOrder(PartakeRaffleActivityEntity partakeRaffleActivityEntity) { UserRaffleOrder userRaffleOrderReq = new UserRaffleOrder(); userRaffleOrderReq.setUserId(partakeRaffleActivityEntity.getUserId()); userRaffleOrderReq.setActivityId(partakeRaffleActivityEntity.getActivityId()); UserRaffleOrder userRaffleOrderRes = userRaffleOrderDao.queryNoUsedRaffleOrder(userRaffleOrderReq); if (null == userRaffleOrderRes) { return null; } return UserRaffleOrderEntity.builder().userId(userRaffleOrderRes.getUserId()).activityId(userRaffleOrderRes.getActivityId()).activityName(userRaffleOrderRes.getActivityName()).strategyId(userRaffleOrderRes.getStrategyId()).orderId(userRaffleOrderRes.getOrderId()).orderTime(userRaffleOrderRes.getOrderTime()).orderState(UserRaffleOrderStateVO.valueOf(userRaffleOrderRes.getOrderState())) .build(); } /** * 对user_raffle_order,account,account_day,account_month,activity_account表进行事务操作 * * @param createPartakeOrderAggregate */ @Override public void saveCreatePartakeOrderAggregate(CreatePartakeOrderAggregate createPartakeOrderAggregate) { try { //获取聚合对象里的所有内容用来后续一个事务内写入 String userId = createPartakeOrderAggregate.getUserId(); Long activityId = createPartakeOrderAggregate.getActivityId(); //获得账户相关实体 ActivityAccountDayEntity activityAccountDayEntity = createPartakeOrderAggregate.getActivityAccountDayEntity(); ActivityAccountMonthEntity activityAccountMonthEntity = createPartakeOrderAggregate.getActivityAccountMonthEntity(); ActivityAccountEntity activityAccountEntity = createPartakeOrderAggregate.getActivityAccountEntity(); //获得新生成的抽奖单 UserRaffleOrderEntity userRaffleOrderEntity = createPartakeOrderAggregate.getUserRaffleOrderEntity(); //获取路由,接下来的事务操作要在同一个路由下进行, // 因为经过分库分表后,用户的总账户,日账户,月账户应该在同一个数据库下,这样子方便后续存储和查询, // 所以需要给查询用户总账户的dao方法添加路由 dbRouter.doRouter(userId); transactionTemplate.execute(status -> { try { //扣减总账户的总抽奖次数余量 int totalCount = activityAccountDao.updateActivityAccountSubtractionQuota(RaffleActivityAccount.builder() .userId(userId) .activityId(activityId).build()); if (totalCount != 1) { status.setRollbackOnly(); log.warn("写入创建参与活动记录,更新总账户额度不足,异常 userId: {} activityId: {}", userId, activityId); throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo()); } /** * 日账户和月账户的更新逻辑: * 当不存在时,会将新生成的实体对象的余量-1再插入,因为该对象的余量是根据总对象的实体的余量获得的, * 它保存的是前一个月或前一天的余量 * 当存在时,会在对应的账户上直接扣减余量,走的是update */ //更新月账户,如果不存在月账户则新插入一个 if (createPartakeOrderAggregate.isExistAccountMonth()) { //数据库表{activity_account_month}存在该用户的月账户,扣减月账户次数余量 int monthCount = activityAccountMonthDao.updateActivityAccountMonthSubtractionQuota(RaffleActivityAccountMonth.builder() .userId(userId) .activityId(activityId) .month(activityAccountMonthEntity.getMonth()) .build()); if (monthCount != 1) { status.setRollbackOnly(); log.warn("写入创建参与活动记录,更新月账户额度不足,异常 userId: {} activityId: {} month: {}", userId, activityId, activityAccountMonthEntity.getMonth()); throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo()); } //先更新完表{activity_account_month}之后再更新总账户的库表{raffle_activity_account} activityAccountDao.updateActivityAccountMonthSubtractionQuota(RaffleActivityAccount.builder().activityId(activityId).userId(userId).build()); } else { //新建一个月账户 activityAccountMonthDao.insertActivityAccountMonth(RaffleActivityAccountMonth.builder() .userId(userId) .activityId(activityId) .month(activityAccountMonthEntity.getMonth()) .monthCount(activityAccountMonthEntity.getMonthCount()) .monthCountSurplus(activityAccountMonthEntity.getMonthCountSurplus() - 1).build()); //更新总账户的月额度镜像 activityAccountDao.updateActivityAccountMonthSurplusImageQuota(RaffleActivityAccount.builder() .userId(userId) .activityId(activityId) .monthCountSurplus(activityAccountEntity.getMonthCountSurplus()) .build()); } if (createPartakeOrderAggregate.isExistAccountDay()) { //先更新日账户表 int dayCount = activityAccountDayDao.updateActivityAccountDaySubtractionQuota(RaffleActivityAccountDay.builder().userId(userId).activityId(activityId).day(activityAccountDayEntity.getDay()).build()); if (dayCount != 1) { status.setRollbackOnly(); log.warn("写入创建参与活动记录,更新日账户额度不足,异常 userId: {} activityId: {} day: {}", userId, activityId, activityAccountDayEntity.getDay()); throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo()); } //日账户表更新成功后更新总账户表 activityAccountDao.updateActivityAccountDaySubtractionQuota(RaffleActivityAccount.builder().activityId(activityId).userId(userId).build()); } else { //新建一个日账户 activityAccountDayDao.insertActivityAccountDay(RaffleActivityAccountDay.builder() .userId(userId) .activityId(activityId) .day(activityAccountDayEntity.getDay()) .dayCount(activityAccountDayEntity.getDayCount()) .dayCountSurplus(activityAccountDayEntity.getDayCountSurplus() - 1).build()); //更新总账户的日额度镜像 activityAccountDao.updateActivityAccountDaySurplusImageQuota(RaffleActivityAccount.builder().userId(userId).activityId(activityId).dayCountSurplus(activityAccountEntity.getDayCountSurplus()).build()); } //账户余量全部更新完毕后,插入新的未被使用的抽奖单 userRaffleOrderDao.insert(UserRaffleOrder.builder() .userId(userRaffleOrderEntity.getUserId()) .activityId(userRaffleOrderEntity.getActivityId()) .activityName(userRaffleOrderEntity.getActivityName()) .strategyId(userRaffleOrderEntity.getStrategyId()) .orderId(userRaffleOrderEntity.getOrderId()) .orderTime(userRaffleOrderEntity.getOrderTime()) .orderState(userRaffleOrderEntity.getOrderState().getCode()) .build()); return 1; } catch (Exception e) { status.setRollbackOnly(); log.error("写入创建参与活动记录,唯一索引冲突 userId: {} activityId: {}", userId, activityId, e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { dbRouter.clear(); } } @Override public ActivityAccountEntity queryActivityAccountByUserId(String userId, Long activityId) { RaffleActivityAccount raffleActivityAccountReq = new RaffleActivityAccount(); raffleActivityAccountReq.setUserId(userId); raffleActivityAccountReq.setActivityId(activityId); RaffleActivityAccount activityAccount = activityAccountDao.queryActivityAccountByUserId(raffleActivityAccountReq); if (activityAccount == null) { return null; } return ActivityAccountEntity.builder() .userId(activityAccount.getUserId()) .activityId(activityAccount.getActivityId()) .totalCount(activityAccount.getTotalCount()). totalCountSurplus(activityAccount.getTotalCountSurplus()) .dayCount(activityAccount.getDayCount()) .dayCountSurplus(activityAccount.getDayCountSurplus()) .monthCount(activityAccount.getMonthCount()) .monthCountSurplus(activityAccount.getMonthCountSurplus()) .build(); } @Override public ActivityAccountMonthEntity queryActivityAccountMonthByUserId(String userId, Long activityId, String month) { RaffleActivityAccountMonth raffleActivityAccountMonthReq = new RaffleActivityAccountMonth(); raffleActivityAccountMonthReq.setUserId(userId); raffleActivityAccountMonthReq.setActivityId(activityId); raffleActivityAccountMonthReq.setMonth(month); RaffleActivityAccountMonth raffleActivityAccountMonthRes = activityAccountMonthDao.queryActivityAccountMonthByUserId(raffleActivityAccountMonthReq); if (null == raffleActivityAccountMonthRes) { return null; } // 2. 转换对象 return ActivityAccountMonthEntity.builder().userId(raffleActivityAccountMonthRes.getUserId()).activityId(raffleActivityAccountMonthRes.getActivityId()).month(raffleActivityAccountMonthRes.getMonth()).monthCount(raffleActivityAccountMonthRes.getMonthCount()).monthCountSurplus(raffleActivityAccountMonthRes.getMonthCountSurplus()).build(); } @Override public ActivityAccountDayEntity queryActivityAccountDayByUserId(String userId, Long activityId, String day) { // 1. 查询账户 RaffleActivityAccountDay raffleActivityAccountDayReq = new RaffleActivityAccountDay(); raffleActivityAccountDayReq.setUserId(userId); raffleActivityAccountDayReq.setActivityId(activityId); raffleActivityAccountDayReq.setDay(day); RaffleActivityAccountDay raffleActivityAccountDayRes = activityAccountDayDao.queryActivityAccountDayByUserId(raffleActivityAccountDayReq); if (null == raffleActivityAccountDayRes) { return null; } // 2. 转换对象 return ActivityAccountDayEntity.builder().userId(raffleActivityAccountDayRes.getUserId()).activityId(raffleActivityAccountDayRes.getActivityId()).day(raffleActivityAccountDayRes.getDay()).dayCount(raffleActivityAccountDayRes.getDayCount()).dayCountSurplus(raffleActivityAccountDayRes.getDayCountSurplus()).build(); } @Override public List<ActivitySkuEntity> queryActivitySkuListByActivityId(Long activityId) { List<RaffleActivitySku> skus = activitySkuDao.queryActivitySkuListByActivityId(activityId); List<ActivitySkuEntity> skuEntities = new ArrayList<ActivitySkuEntity>(skus.size()); for (RaffleActivitySku sku : skus) { ActivitySkuEntity activitySkuEntity = ActivitySkuEntity.builder() .sku(sku.getSku()) .activityId(sku.getActivityId()) .activityCountId(sku.getActivityCountId()) .stockCount(sku.getStockCount()) .stockCountSurplus(sku.getStockCountSurplus()) .productAmount(sku.getPayAmount()).build(); skuEntities.add(activitySkuEntity); } return skuEntities; } @Override public Integer queryRaffleActivityAccountDayPartakeCount(Long activityId, String userId) { RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay(); raffleActivityAccountDay.setUserId(userId); raffleActivityAccountDay.setActivityId(activityId); raffleActivityAccountDay.setDay(RaffleActivityAccountDay.curDay()); Integer count = activityAccountDayDao.queryRaffleActivityAccountDayPartakeCount(raffleActivityAccountDay); return count == null ? 0 : count; } @Override public ActivityAccountEntity queryActivityAccountEntity(String userId, Long activityId) { RaffleActivityAccount activityAccount = activityAccountDao.queryActivityAccountByUserId(RaffleActivityAccount.builder().userId(userId).activityId(activityId).build()); if (null == activityAccount) { return ActivityAccountEntity.builder().activityId(activityId).userId(userId).dayCount(0).dayCountSurplus(0).monthCount(0).monthCountSurplus(0).totalCount(0).totalCountSurplus(0).build(); } RaffleActivityAccountMonth raffleActivityAccountMonth = activityAccountMonthDao.queryActivityAccountMonthByUserId(RaffleActivityAccountMonth.builder().userId(userId).activityId(activityId).build()); RaffleActivityAccountDay raffleActivityAccountDay = activityAccountDayDao.queryActivityAccountDayByUserId(RaffleActivityAccountDay.builder().userId(userId).activityId(activityId).build()); ActivityAccountEntity activityAccountEntity = new ActivityAccountEntity(); activityAccountEntity.setUserId(userId); activityAccountEntity.setActivityId(activityId); activityAccountEntity.setTotalCount(activityAccount.getTotalCount()); activityAccountEntity.setTotalCountSurplus(activityAccount.getTotalCountSurplus()); if (raffleActivityAccountMonth == null) { activityAccountEntity.setMonthCount(activityAccount.getMonthCount()); activityAccountEntity.setMonthCountSurplus(activityAccount.getMonthCountSurplus()); } else { activityAccountEntity.setMonthCount(raffleActivityAccountMonth.getMonthCount()); activityAccountEntity.setMonthCountSurplus(raffleActivityAccountMonth.getMonthCountSurplus()); } if (raffleActivityAccountDay == null) { activityAccountEntity.setDayCount(activityAccount.getDayCount()); activityAccountEntity.setDayCountSurplus(activityAccount.getDayCountSurplus()); } else { activityAccountEntity.setDayCount(raffleActivityAccountDay.getDayCount()); activityAccountEntity.setDayCountSurplus(raffleActivityAccountDay.getDayCountSurplus()); } return activityAccountEntity; } @Override public Integer queryRaffleActivityAccountPartakeCount(Long activityId, String userId) { ; RaffleActivityAccount activityAccount = activityAccountDao.queryActivityAccountByUserId(RaffleActivityAccount.builder().userId(userId).activityId(activityId).build()); if (null == activityAccount) { return 0; } return activityAccount.getTotalCount() - activityAccount.getTotalCountSurplus(); } /** * 在成功获取锁("activity_account_lock_#{userId}_#{activityId}")之后,保存充值单({修改库表{raffle_activity_order}}) * 并修改用户的总,日,月账户的抽奖次数(修改库表{raffle_activity_account},{{raffle_activity_account_day},{raffle_activity_account_month}}) * * @param createQuotaOrderAggregate */ @Override public void doSaveNoPayOrder(CreateQuotaOrderAggregate createQuotaOrderAggregate) { //在给用户账户充值抽奖次数前先在缓存设置一个分布式锁 RLock lock = redisService.getLock(Constants.RedisKey.ACTIVITY_ACCOUNT_LOCK + createQuotaOrderAggregate.getUserId() + Constants.UNDERLINE + createQuotaOrderAggregate.getActivityId()); try { //抢占到锁的执行数据库修改逻辑 //未抢占到的会阻塞3秒,当锁释放后执行修改逻辑,如果上一个抢占到锁的应用修改数据库成功这里则会报错,未修改成功这里会重新修改。 lock.lock(3, TimeUnit.SECONDS); ActivityOrderEntity activityOrderEntity = createQuotaOrderAggregate.getActivityOrderEntity(); RaffleActivityOrder raffleActivityOrderReq = new RaffleActivityOrder(); raffleActivityOrderReq.setUserId(activityOrderEntity.getUserId()); raffleActivityOrderReq.setSku(activityOrderEntity.getSku()); raffleActivityOrderReq.setActivityId(activityOrderEntity.getActivityId()); raffleActivityOrderReq.setActivityName(activityOrderEntity.getActivityName()); raffleActivityOrderReq.setStrategyId(activityOrderEntity.getStrategyId()); raffleActivityOrderReq.setOrderId(activityOrderEntity.getOrderId()); raffleActivityOrderReq.setOrderTime(activityOrderEntity.getOrderTime()); raffleActivityOrderReq.setTotalCount(activityOrderEntity.getTotalCount()); raffleActivityOrderReq.setDayCount(activityOrderEntity.getDayCount()); raffleActivityOrderReq.setMonthCount(activityOrderEntity.getMonthCount()); raffleActivityOrderReq.setState(activityOrderEntity.getState().getCode()); raffleActivityOrderReq.setOutBusinessNo(activityOrderEntity.getOutBusinessNo()); RaffleActivityAccount activityAccountReq = new RaffleActivityAccount(); activityAccountReq.setUserId(activityOrderEntity.getUserId()); activityAccountReq.setActivityId(activityOrderEntity.getActivityId()); activityAccountReq.setTotalCount(activityOrderEntity.getTotalCount()); activityAccountReq.setTotalCountSurplus(activityOrderEntity.getTotalCount()); activityAccountReq.setDayCount(activityOrderEntity.getDayCount()); activityAccountReq.setDayCountSurplus(activityOrderEntity.getDayCount()); activityAccountReq.setMonthCount(activityOrderEntity.getMonthCount()); activityAccountReq.setMonthCountSurplus(activityOrderEntity.getMonthCount()); RaffleActivityAccountDay raffleActivityAccountDayReq = new RaffleActivityAccountDay(); raffleActivityAccountDayReq.setUserId(activityOrderEntity.getUserId()); raffleActivityAccountDayReq.setActivityId(activityOrderEntity.getActivityId()); raffleActivityAccountDayReq.setDayCount(activityOrderEntity.getDayCount()); raffleActivityAccountDayReq.setDayCountSurplus(activityOrderEntity.getDayCount()); RaffleActivityAccountMonth raffleActivityAccountMonthReq = new RaffleActivityAccountMonth(); raffleActivityAccountMonthReq.setUserId(activityOrderEntity.getUserId()); raffleActivityAccountMonthReq.setActivityId(activityOrderEntity.getActivityId()); raffleActivityAccountMonthReq.setMonthCount(activityOrderEntity.getMonthCount()); raffleActivityAccountMonthReq.setMonthCountSurplus(activityOrderEntity.getMonthCount()); dbRouter.doRouter(activityAccountReq.getUserId()); transactionTemplate.execute(status -> { try { //插入一笔新的活动订单记录 activityOrderDao.insert(raffleActivityOrderReq); //更新用户的总,月,日账户的抽奖次数 RaffleActivityAccount activityAccount = activityAccountDao.queryActivityAccountByUserId(activityAccountReq); if (null == activityAccount) { activityAccountDao.insert(activityAccountReq); } else { activityAccountDao.updateAccountQuota(activityAccountReq); } activityAccountDayDao.addAccountQuota(raffleActivityAccountDayReq); activityAccountMonthDao.addAccountQuota(raffleActivityAccountMonthReq); return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("写入订单记录,唯一索引冲突 userId: {} activityId: {} sku: {}", activityOrderEntity.getUserId(), activityOrderEntity.getActivityId(), activityOrderEntity.getSku(), e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { dbRouter.clear(); lock.unlock(); } } @Override public void updateOrder(DeliveryOrderEntity deliveryOrderEntity) { //再调整用户抽奖次数之前先在缓存中加一个锁:key(activity_account_update_lock_#{userId}) //mq消息执行要加一个分布式锁,防止消息被不同应用多次执行 RLock lock = redisService.getLock(Constants.RedisKey.ACTIVITY_ACCOUNT_UPDATE_LOCK + deliveryOrderEntity.getUserId()); try { lock.lock(3, TimeUnit.SECONDS); RaffleActivityOrder raffleActivityOrderReq = new RaffleActivityOrder(); raffleActivityOrderReq.setUserId(deliveryOrderEntity.getUserId()); raffleActivityOrderReq.setOutBusinessNo(deliveryOrderEntity.getOutBusinessNo()); RaffleActivityOrder raffleActivityOrderRes = activityOrderDao.queryRaffleActivityOrder(raffleActivityOrderReq); //如果此处为空说明是用户行为返利增加的积分调额成功的消息被CreditAdjustSuccessCustomer消费, //返利获得的积分在creditService中插入了积分订单和更新积分账户并发送积分调额成功的消息, // 没有操作raffle_activity_order if (null == raffleActivityOrderRes) { if (lock.isLocked()) { lock.unlock(); return; } } RaffleActivityAccount activityAccountReq = new RaffleActivityAccount(); activityAccountReq.setUserId(raffleActivityOrderRes.getUserId()); activityAccountReq.setActivityId(raffleActivityOrderRes.getActivityId()); activityAccountReq.setTotalCount(raffleActivityOrderRes.getTotalCount()); activityAccountReq.setDayCount(raffleActivityOrderRes.getDayCount()); activityAccountReq.setMonthCount(raffleActivityOrderRes.getMonthCount()); activityAccountReq.setTotalCountSurplus(raffleActivityOrderRes.getTotalCount()); activityAccountReq.setDayCountSurplus(raffleActivityOrderRes.getDayCount()); activityAccountReq.setMonthCountSurplus(raffleActivityOrderRes.getMonthCount()); RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay(); raffleActivityAccountDay.setUserId(raffleActivityOrderRes.getUserId()); raffleActivityAccountDay.setActivityId(raffleActivityOrderRes.getActivityId()); raffleActivityAccountDay.setDayCount(raffleActivityOrderRes.getDayCount()); raffleActivityAccountDay.setDayCountSurplus(raffleActivityOrderRes.getDayCount()); raffleActivityAccountDay.setDay(RaffleActivityAccountDay.curDay()); RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth(); raffleActivityAccountMonth.setUserId(raffleActivityOrderRes.getUserId()); raffleActivityAccountMonth.setActivityId(raffleActivityOrderRes.getActivityId()); raffleActivityAccountMonth.setMonth(RaffleActivityAccountMonth.currentMonth()); raffleActivityAccountMonth.setMonthCount(raffleActivityOrderRes.getMonthCount()); raffleActivityAccountMonth.setMonthCountSurplus(raffleActivityOrderRes.getMonthCount()); dbRouter.doRouter(deliveryOrderEntity.getUserId()); transactionTemplate.execute(status -> { try { //将{raffle_activity_order}中对用的记录更新为completed,标记着充值单被使用 int update = activityOrderDao.updateOrderCompleted(raffleActivityOrderReq); if (update != 1) { log.error("无法更新流水状态"); status.setRollbackOnly(); return 1; } //更新账户抽奖次数 RaffleActivityAccount activityAccount = activityAccountDao.queryActivityAccountByUserId(activityAccountReq); if (null == activityAccount) { activityAccountDao.insert(activityAccountReq); } else { activityAccountDao.updateAccountQuota(activityAccountReq); } activityAccountDayDao.addAccountQuota(raffleActivityAccountDay); activityAccountMonthDao.addAccountQuota(raffleActivityAccountMonth); return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("更新订单记录,完成态,唯一索引冲突 userId: {} outBusinessNo: {}", deliveryOrderEntity.getUserId(), deliveryOrderEntity.getOutBusinessNo(), e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { if (lock.isLocked()) { lock.unlock(); } dbRouter.clear(); } } @Override public List<SkuProductEntity> querySkuProductEntityListByActivityId(Long activityId) { List<RaffleActivitySku> raffleActivitySkus = activitySkuDao.queryActivitySkuListByActivityId(activityId); List<SkuProductEntity> skuProductEntityList = new ArrayList<>(raffleActivitySkus.size()); for (RaffleActivitySku raffleActivitySku : raffleActivitySkus) { //根据次数id去查找数据库表{raffle_activity_count}对应的次数配置 RaffleActivityCount raffleActivityCount = activityCountDao.queryRaffleActivityCountByActivityCountId(raffleActivitySku.getActivityCountId()); SkuProductEntity.ActivityCount activityCount = new SkuProductEntity.ActivityCount(); activityCount.setTotalCount(raffleActivityCount.getTotalCount()); activityCount.setDayCount(raffleActivityCount.getDayCount()); activityCount.setMonthCount(raffleActivityCount.getMonthCount()); skuProductEntityList.add(SkuProductEntity.builder(). activityCount(activityCount) .activityCountId(raffleActivityCount.getActivityCountId()). stockCount(raffleActivitySku.getStockCount()) .stockCountSurplus(raffleActivitySku.getStockCountSurplus()) .activityId(activityId) .payAmount(raffleActivitySku.getPayAmount()) .sku(raffleActivitySku.getSku()) .build()); } return skuProductEntityList; } @Override public UnpaidActivityOrderEntity queryUnpaidActivityOrder(SkuRechargeEntity skuRechargeEntity) { RaffleActivityOrder raffleActivityOrderReq = new RaffleActivityOrder(); raffleActivityOrderReq.setUserId(skuRechargeEntity.getUserId()); raffleActivityOrderReq.setSku(skuRechargeEntity.getSku()); RaffleActivityOrder raffleActivityOrderRes = activityOrderDao.queryUnpaidActivityOrder(raffleActivityOrderReq); if (null == raffleActivityOrderRes) { return null; } return UnpaidActivityOrderEntity.builder() .outBusinessNo(raffleActivityOrderRes.getOutBusinessNo()) .orderId(raffleActivityOrderRes.getOrderId()) .userId(raffleActivityOrderRes.getUserId()) .payAmount(raffleActivityOrderRes.getPayAmount()) .build(); } @Override public BigDecimal queryUserCreditAccountAmount(String userId) { try { dbRouter.doRouter(userId); UserCreditAccount userCreditAccountReq = new UserCreditAccount(); userCreditAccountReq.setUserId(userId); UserCreditAccount userCreditAccount = userCreditAccountDao.queryUserCreditAccount(userCreditAccountReq); if (null == userCreditAccount) { return BigDecimal.ZERO; } return userCreditAccount.getAvailableAmount(); } finally { dbRouter.clear(); } } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/ActivityRepository.java
Java
unknown
41,248
package zack.project.infrastructure.persistent.repository; import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RLock; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionTemplate; import zack.project.domain.award.adapter.repository.IAwardRepository; import zack.project.domain.award.model.aggregate.GiveOutPrizesAggregate; import zack.project.domain.award.model.aggregate.UserAwardRecordAggregate; import zack.project.domain.award.model.entity.TaskEntity; import zack.project.domain.award.model.entity.UserAwardRecordEntity; import zack.project.domain.award.model.entity.UserCreditAwardEntity; import zack.project.domain.award.model.valobj.AccountStatusVO; import zack.project.infrastructure.event.EventPublisher; import zack.project.infrastructure.persistent.dao.*; import zack.project.infrastructure.persistent.po.*; import zack.project.infrastructure.persistent.redis.IRedisService; import zack.project.types.common.Constants; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * @author A1793 */ @Repository @Slf4j public class AwardRepository implements IAwardRepository { @Resource private IUserAwardRecordDao userAwardRecordDao; @Resource private ITaskDao taskDao; @Resource private TransactionTemplate transactionTemplate; @Resource private IDBRouterStrategy dbRouter; @Resource private EventPublisher eventPublisher; @Resource private IUserRaffleOrderDao userRaffleOrderDao; @Resource private IUserCreditAccountDao userCreditAccountDao; @Resource private IAwardDao awardDao; @Resource private IRedisService redisService; /** * 保存中奖记录(更新数据库表{user_raffle_award})和发奖的任务(该任务是为了防止本方法中发送消息失败的补偿任务,更新数据库表{task}), * 更新抽奖单状态为used(更新库表{user_raffle_order}) 并 向SendAwardCustomer监听的消息队列投入发奖消息 * @param userAwardRecordAggregate */ @Override public void saveUserAwardRecord(UserAwardRecordAggregate userAwardRecordAggregate) { //获得用户的奖品信息 UserAwardRecordEntity userAwardRecordEntity = userAwardRecordAggregate.getUserAwardRecordEntity(); //获得任务实体 TaskEntity taskEntity = userAwardRecordAggregate.getTaskEntity(); String userId = userAwardRecordEntity.getUserId(); Long activityId = userAwardRecordEntity.getActivityId(); Integer awardId = userAwardRecordEntity.getAwardId(); //根据奖品信息构建中奖记录po对象 UserAwardRecord userAwardRecord = new UserAwardRecord(); userAwardRecord.setUserId(userAwardRecordEntity.getUserId()); userAwardRecord.setActivityId(userAwardRecordEntity.getActivityId()); userAwardRecord.setStrategyId(userAwardRecordEntity.getStrategyId()); userAwardRecord.setOrderId(userAwardRecordEntity.getOrderId()); userAwardRecord.setAwardId(userAwardRecordEntity.getAwardId()); userAwardRecord.setAwardTitle(userAwardRecordEntity.getAwardTitle()); userAwardRecord.setAwardTime(userAwardRecordEntity.getAwardTime()); userAwardRecord.setAwardState(userAwardRecordEntity.getAwardState().getCode()); Task task = new Task(); task.setUserId(taskEntity.getUserId()); task.setTopic(taskEntity.getTopic()); task.setMessageId(taskEntity.getMessageId()); task.setMessage(JSON.toJSONString(taskEntity.getMessage())); task.setState(taskEntity.getState().getCode()); //本次事务操作中,会完成中奖记录入库相关行为,所以需要将奖品对应的抽奖单状态设置为used, // 故先构建查询对象用来查询数据库表{user_raffle_order} UserRaffleOrder userRaffleOrderReq = new UserRaffleOrder(); userRaffleOrderReq.setUserId(userId); userRaffleOrderReq.setOrderId(userAwardRecordEntity.getOrderId()); try { //接下来的操作走同一个手动路由,因为一个事务操作要在同一个数据库下, // 操作结果该用户的本次中奖信息的补偿消息和中奖记录会在同一个数据库下 dbRouter.doRouter(userId); transactionTemplate.execute(status -> { try { // 写入记录 userAwardRecordDao.insert(userAwardRecord); // 写入任务 taskDao.insert(task); //更新抽奖单状态 int updated = userRaffleOrderDao.updateUserRaffleOrderStateUsed(userRaffleOrderReq); if (1 != updated) { status.setRollbackOnly(); log.error("写入中奖记录,用户抽奖单已使用过,不可重复抽奖 userId: {} activityId: {} awardId: {}", userId, activityId, awardId); throw new AppException(ResponseCode.ACTIVITY_ORDER_ERROR.getCode(), ResponseCode.ACTIVITY_ORDER_ERROR.getInfo()); } return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("写入中奖记录,唯一索引冲突 userId: {} activityId: {} awardId: {}", userId, activityId, awardId, e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { dbRouter.clear(); } //当事务写入一条task记录同时发出一条消息 try { //topic: send_award , message: EventMessage.<SendAwardMessage> //向消息队列中放入一个发奖消息,由trigger层下的SendAwardCustomer监听器监听并消费, // 开始执行发奖,更新{user_award_record}表中的UserAwardRecord的award_state状态为completed, // 并更新用户的积分账户{user_credit_account} eventPublisher.publish(taskEntity.getTopic(), task.getMessage()); taskDao.updateTaskSendMessageCompleted(task); log.info("写入中奖记录,发送MQ消息完成 userId: {} orderId:{} topic: {}", userId, userAwardRecordEntity.getOrderId(), task.getTopic()); } catch (Exception e) { log.error("写入中奖记录,发送MQ消息失败 userId: {} topic: {}", userId, task.getTopic()); taskDao.updateTaskSendMessageFail(task); } } /** * 更新用户积分账户(修改库表{user_credit_account})和中奖记录(修改库表{user_award_record}) * @param giveOutPrizesAggregate */ @Override public void saveGiveOutPrizesAggregate(GiveOutPrizesAggregate giveOutPrizesAggregate) { //获取中奖记录 UserAwardRecordEntity userAwardRecordEntity = giveOutPrizesAggregate.getUserAwardRecord(); //获取积分奖品实体 UserCreditAwardEntity userCreditAwardEntity = giveOutPrizesAggregate.getUserCreditAwardEntity(); String userId = giveOutPrizesAggregate.getUserId(); UserCreditAccount userCreditAccountReq = new UserCreditAccount(); userCreditAccountReq.setUserId(userId); userCreditAccountReq.setTotalAmount(userCreditAwardEntity.getCreditAmount()); userCreditAccountReq.setAvailableAmount(userCreditAwardEntity.getCreditAmount()); userCreditAccountReq.setAccountStatus(AccountStatusVO.open.getCode()); UserCredit userAwardRecord = new UserCredit(); userAwardRecord.setUserId(userId); userAwardRecord.setAwardState(userAwardRecordEntity.getAwardState().getCode()); userAwardRecord.setOrderId(userAwardRecordEntity.getOrderId()); //在修改用户积分和中奖单状态前先加锁 //防止发奖消息被多个应用同时监听而重复消费,这里加分布式锁,谁抢到谁消费 RLock lock = redisService.getLock(Constants.RedisKey.ACTIVITY_ACCOUNT_LOCK + userId); dbRouter.doRouter(userId); try { lock.lock(3, TimeUnit.SECONDS); transactionTemplate.execute(status -> { try { //查询用户的积分账户,如果没有则插入当前的积分账户实体,存在则在原来的基础上update UserCreditAccount userCreditAccount = userCreditAccountDao. queryUserCreditAccount(userCreditAccountReq); if(userCreditAccount == null){ userCreditAccountDao.insert(userCreditAccountReq); }else{ userCreditAccountDao.updateAddAmount(userCreditAccountReq); } //更新完用户积分账户之后再修改中奖记录的状态为completed int updateRecordCount = userAwardRecordDao.updateAwardRecordCompletedState(userAwardRecord); if (1 != updateRecordCount) { log.warn("更新中奖记录,重复更新拦截 userId:{} giveOutPrizesAggregate:{}", userId, JSON.toJSONString(giveOutPrizesAggregate)); status.setRollbackOnly(); } return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); throw new AppException(ResponseCode.INDEX_DUP.getCode(), e); } }); } finally { dbRouter.clear(); lock.unlock(); } } /** * 根据奖品id查询奖品的key * id award_key award_config award_desc * 1 101 user_credit_random 1,100 用户积分【优先透彻规则范围,如果没有则走配置】 2023-12-09 11:07:06 2023-12-09 11:21:31 * 2 102 openai_use_count 5 OpenAI 增加使用次数 2023-12-09 11:07:06 2023-12-09 11:12:59 * 3 103 openai_use_count 10 OpenAI 增加使用次数 2023-12-09 11:07:06 2023-12-09 11:12:59 * 4 104 openai_use_count 20 OpenAI 增加使用次数 2023-12-09 11:07:06 2023-12-09 11:12:58 * @param awardId * @return */ @Override public String queryAwardKey(Integer awardId) { return awardDao.queryAwardKeyByAwardId(awardId); } @Override public String queryAwardConfig(Integer awardId) { return awardDao.queryAwardConfigByAwardId(awardId); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/AwardRepository.java
Java
unknown
10,885
package zack.project.infrastructure.persistent.repository; import zack.project.domain.rebate.adapter.repository.IBehaviorRebateRepository; import zack.project.domain.rebate.model.aggregate.BehaviorRebateAggregate; import zack.project.domain.rebate.model.entity.BehaviorRebateOrderEntity; import zack.project.domain.rebate.model.entity.TaskEntity; import zack.project.domain.rebate.model.valobj.BehaviorTypeVO; import zack.project.domain.rebate.model.valobj.DailyBehaviorRebateVO; import zack.project.infrastructure.event.EventPublisher; import zack.project.infrastructure.persistent.dao.IDailyBehaviorRebateDao; import zack.project.infrastructure.persistent.dao.ITaskDao; import zack.project.infrastructure.persistent.dao.IUserBehaviorRebateOrderDao; import zack.project.infrastructure.persistent.po.DailyBehaviorRebate; import zack.project.infrastructure.persistent.po.Task; import zack.project.infrastructure.persistent.po.UserBehaviorRebateOrder; import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * @author A1793 */ @Repository @Slf4j public class BehaviorRebateRepository implements IBehaviorRebateRepository { @Resource private IDailyBehaviorRebateDao dailyBehaviorRebateDao; @Resource private IUserBehaviorRebateOrderDao userBehaviorRebateOrderDao; @Resource private ITaskDao taskDao; @Resource private TransactionTemplate transactionTemplate; @Resource private EventPublisher eventPublisher; @Resource private IDBRouterStrategy dbRouter; @Override public List<DailyBehaviorRebateVO> queryDailyBehaviorRebateConfig(BehaviorTypeVO behaviorTypeVO) { List<DailyBehaviorRebate> dailyBehaviorRebates = dailyBehaviorRebateDao. queryDailyBehaviorRebateByBehaviorType(behaviorTypeVO.getCode()); List<DailyBehaviorRebateVO> dailyBehaviorRebateVOS = new ArrayList<>(dailyBehaviorRebates.size()); for (DailyBehaviorRebate dailyBehaviorRebate : dailyBehaviorRebates) { dailyBehaviorRebateVOS.add(DailyBehaviorRebateVO.builder(). rebateConfig(dailyBehaviorRebate.getRebateConfig()). behaviorType(dailyBehaviorRebate.getBehaviorType()). rebateDesc(dailyBehaviorRebate.getRebateDesc()). rebateType(dailyBehaviorRebate.getRebateType()). build()); } return dailyBehaviorRebateVOS; } /** * 保存返利单和返利补偿任务 * 并向SendRebateMessageEvent.RebateMessage监听的消息队列发送返利消息 * @param userId * @param behaviorRebateAggregates */ @Override public void saveUserRebateRecord(String userId, List<BehaviorRebateAggregate> behaviorRebateAggregates) { try { dbRouter.doRouter(userId); transactionTemplate.execute(status -> { try { for (BehaviorRebateAggregate behaviorRebateAggregate : behaviorRebateAggregates) { //获取返利单 BehaviorRebateOrderEntity behaviorRebateOrderEntity = behaviorRebateAggregate. getBehaviorRebateOrderEntity(); //构建返利单的po对象,更新库表{user_behavior_rebate_order} UserBehaviorRebateOrder userBehaviorRebateOrder = new UserBehaviorRebateOrder(); userBehaviorRebateOrder.setUserId(behaviorRebateOrderEntity.getUserId()); userBehaviorRebateOrder.setOrderId(behaviorRebateOrderEntity.getOrderId()); userBehaviorRebateOrder.setBehaviorType(behaviorRebateOrderEntity.getBehaviorType()); userBehaviorRebateOrder.setRebateDesc(behaviorRebateOrderEntity.getRebateDesc()); userBehaviorRebateOrder.setRebateType(behaviorRebateOrderEntity.getRebateType()); userBehaviorRebateOrder.setRebateConfig(behaviorRebateOrderEntity.getRebateConfig()); userBehaviorRebateOrder.setBizId(behaviorRebateOrderEntity.getBizId()); userBehaviorRebateOrder.setOutBusinessNo(behaviorRebateOrderEntity.getOutBusinessNo()); userBehaviorRebateOrderDao.insert(userBehaviorRebateOrder); //构建返利补偿任务po对象 TaskEntity taskEntity = behaviorRebateAggregate.getTaskEntity(); Task task = new Task(); task.setUserId(taskEntity.getUserId()); task.setTopic(taskEntity.getTopic()); task.setMessageId(taskEntity.getMessageId()); task.setMessage(JSON.toJSONString(taskEntity.getMessage())); task.setState(taskEntity.getState().getCode()); taskDao.insert(task); } return 1; } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("写入返利记录,唯一索引冲突 userId: {}", userId, e); throw new AppException(ResponseCode.INDEX_DUP.getCode(), ResponseCode.INDEX_DUP.getInfo()); } }); } finally { dbRouter.clear(); } //一个聚合对象是由一笔返利单和对应返利补偿任务构成 for (BehaviorRebateAggregate behaviorRebateAggregate : behaviorRebateAggregates) { TaskEntity taskEntity = behaviorRebateAggregate.getTaskEntity(); Task task = new Task(); task.setUserId(taskEntity.getUserId()); task.setMessageId(taskEntity.getMessageId()); try { //发送返利消息 eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage()); //将返利任务状态设置为completed taskDao.updateTaskSendMessageCompleted(task); }catch (Exception e) { log.error("写入返利记录,发送MQ消息失败 userId: {} topic: {}", userId, task.getTopic()); taskDao.updateTaskSendMessageFail(task); } } } @Override public List<BehaviorRebateOrderEntity> queryOrderByOutBusinessNo(String userId, String outBusinessNo) { // 1. 请求对象 UserBehaviorRebateOrder userBehaviorRebateOrderReq = new UserBehaviorRebateOrder(); userBehaviorRebateOrderReq.setUserId(userId); userBehaviorRebateOrderReq.setOutBusinessNo(outBusinessNo); List<UserBehaviorRebateOrder> userBehaviorRebateOrders = userBehaviorRebateOrderDao.queryOrderByOutBusinessNo(userBehaviorRebateOrderReq); List<BehaviorRebateOrderEntity> behaviorRebateOrderEntities = new ArrayList<>(userBehaviorRebateOrders.size()); for(UserBehaviorRebateOrder userBehaviorRebateOrder :userBehaviorRebateOrders){ BehaviorRebateOrderEntity behaviorRebateOrderEntity = BehaviorRebateOrderEntity.builder() .userId(userBehaviorRebateOrder.getUserId()) .orderId(userBehaviorRebateOrder.getOrderId()) .behaviorType(userBehaviorRebateOrder.getBehaviorType()) .rebateDesc(userBehaviorRebateOrder.getRebateDesc()) .rebateType(userBehaviorRebateOrder.getRebateType()) .rebateConfig(userBehaviorRebateOrder.getRebateConfig()) .bizId(userBehaviorRebateOrder.getBizId()) .build(); behaviorRebateOrderEntities.add(behaviorRebateOrderEntity); } return behaviorRebateOrderEntities; } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/BehaviorRebateRepository.java
Java
unknown
8,235
package zack.project.infrastructure.persistent.repository; import zack.project.domain.award.model.valobj.AccountStatusVO; import zack.project.domain.credit.adapter.repository.ICreditRepository; import zack.project.domain.credit.model.aggregate.TradeAggregate; import zack.project.domain.credit.model.entity.CreditAccountEntity; import zack.project.domain.credit.model.entity.CreditOrderEntity; import zack.project.domain.credit.model.entity.TaskEntity; import zack.project.infrastructure.event.EventPublisher; import zack.project.infrastructure.persistent.dao.ITaskDao; import zack.project.infrastructure.persistent.dao.IUserCreditAccountDao; import zack.project.infrastructure.persistent.dao.IUserCreditOrderDao; import zack.project.infrastructure.persistent.po.Task; import zack.project.infrastructure.persistent.po.UserCreditAccount; import zack.project.infrastructure.persistent.po.UserCreditOrder; import zack.project.infrastructure.persistent.redis.IRedisService; import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy; import zack.project.types.common.Constants; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RLock; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Resource; import java.math.BigDecimal; import java.util.concurrent.TimeUnit; @Repository @Slf4j public class CreditRepository implements ICreditRepository { @Resource private IUserCreditAccountDao userCreditAccountDao; @Resource private IUserCreditOrderDao userCreditOrderDao; @Resource private ITaskDao taskDao; @Resource private IRedisService redisService; @Resource private TransactionTemplate transactionTemplate; @Resource private IDBRouterStrategy dbRouter; @Resource private EventPublisher eventPublisher; @Override public void saveUserCreditTradeOrder(TradeAggregate tradeAggregate) { //构建积分订单po对象,插入数据库表{user_credit_order} CreditOrderEntity orderEntity = tradeAggregate.getOrderEntity(); UserCreditOrder userCreditOrderReq = new UserCreditOrder(); userCreditOrderReq.setUserId(orderEntity.getUserId()); userCreditOrderReq.setOrderId(orderEntity.getOrderId()); userCreditOrderReq.setTradeAmount(orderEntity.getTradeAmount()); userCreditOrderReq.setTradeType(orderEntity.getTradeType().getCode()); userCreditOrderReq.setTradeName(orderEntity.getTradeName().getName()); userCreditOrderReq.setOutBusinessNo(orderEntity.getOutBusinessNo()); //构建积分账户po对象,修改数据库表{user_credit_account}, // 因为后续查询用户积分账户时,如果该该用户没有对用的积分账户时需要插入一个新的账户, // 故此时需要将totalAmount也设置上,防止入库的新账户出现字段不全的情况 CreditAccountEntity accountEntity = tradeAggregate.getAccountEntity(); UserCreditAccount userCreditAccountReq = new UserCreditAccount(); userCreditAccountReq.setUserId(accountEntity.getUserId()); userCreditAccountReq.setAvailableAmount(accountEntity.getAdjustAmount()); userCreditAccountReq.setTotalAmount(accountEntity.getAdjustAmount()); userCreditAccountReq.setAccountStatus(AccountStatusVO.open.getCode()); //构建积分调整补偿任务 TaskEntity taskEntity = tradeAggregate.getTaskEntity(); Task task = new Task(); task.setUserId(taskEntity.getUserId()); task.setTopic(taskEntity.getTopic()); task.setMessageId(taskEntity.getMessageId()); task.setMessage(JSON.toJSONString(taskEntity.getMessage())); task.setState(taskEntity.getState().getCode()); String userId = tradeAggregate.getUserId(); //在修改数据库表 {user_credit_account}用户的积分账户之前, // 在缓存中获取一个锁:cacheKey(user_credit_account_lock_#{userId}_#{ouBusinessNo}) RLock lock = redisService.getLock(Constants.RedisKey.USER_CREDIT_ACCOUNT_LOCK + userId + Constants.UNDERLINE + orderEntity.getOutBusinessNo()); try { lock.lock(3, TimeUnit.SECONDS); dbRouter.doRouter(userId); transactionTemplate.execute(status -> { try { //根据po对象的userId查询数据库表{user_credit_account}中对应的用户积分账户 UserCreditAccount userCreditAccount = userCreditAccountDao.queryUserCreditAccount(userCreditAccountReq); //如果没有积分账户则根据插入一个新的账户 if (userCreditAccount == null) { userCreditAccountDao.insert(userCreditAccountReq); } else { //存在新的账户则在原来的账户基础上更新积分值 BigDecimal availableAmount = userCreditAccountReq.getAvailableAmount(); //根据积分变更量是正或负来判断是走add还是subtraction if(availableAmount.compareTo(BigDecimal.ZERO) > 0){ userCreditAccountDao.updateAddAmount(userCreditAccountReq); }else{ int subtractionCount = userCreditAccountDao.updateSubtractionAmount(userCreditAccountReq); if (1 != subtractionCount) { status.setRollbackOnly(); throw new AppException(ResponseCode.USER_CREDIT_ACCOUNT_NO_AVAILABLE_AMOUNT.getCode(), ResponseCode.USER_CREDIT_ACCOUNT_NO_AVAILABLE_AMOUNT.getInfo()); } } } //在更新完用户积分账户之后再插入新的积分订单 userCreditOrderDao.insert(userCreditOrderReq); //插入积分调整的补偿任务 taskDao.insert(task); } catch (DuplicateKeyException e) { status.setRollbackOnly(); log.error("调整账户积分额度异常,唯一索引冲突 userId:{} orderId:{}", userId, orderEntity.getOrderId(), e); } catch (Exception e) { status.setRollbackOnly(); log.error("调整账户积分额度失败 userId:{} orderId:{}", userId, orderEntity.getOrderId(), e); } return 1; }); } finally { dbRouter.clear(); if(lock.isLocked()){ lock.unlock(); } } //在调整完用户的积分账户的积分,插入积分订单和补偿任务后,向CreditAdjustSuccessCustomer监听的消息队列投放一个积分调整成功的消息, //CreditAdjustSuccessCustomer监听并消费BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage>消息 //根据CreditAdjustSuccessMessage消息内容更新对应的数据库表{raffle_activity_order}充值单的状态为completed //并更新数据库表{raffle_activity_account},{raffle_activity_account_day},{raffle_activity_account_month}中对应的抽奖次数,完成充值 try { eventPublisher.publish(task.getTopic(), task.getMessage()); //如果积分调整消息被成功消息则将补偿任务设为completed taskDao.updateTaskSendMessageCompleted(task); log.info("调整账户积分记录,发送MQ消息完成 userId: {} orderId:{} topic: {}", userId, orderEntity.getOrderId(), task.getTopic()); } catch (Exception e) { log.error("调整账户积分记录,发送MQ消息失败 userId: {} topic: {}", userId, task.getTopic()); taskDao.updateTaskSendMessageFail(task); } } @Override public CreditAccountEntity queryUserCreditAccount(String userId) { UserCreditAccount userCreditAccountReq = new UserCreditAccount(); userCreditAccountReq.setUserId(userId); try { dbRouter.doRouter(userId); UserCreditAccount userCreditAccount = userCreditAccountDao.queryUserCreditAccount(userCreditAccountReq); BigDecimal availableAmount = BigDecimal.ZERO; if (null != userCreditAccount) { availableAmount = userCreditAccount.getAvailableAmount(); } return CreditAccountEntity.builder().userId(userId).adjustAmount(availableAmount).build(); } finally { dbRouter.clear(); } } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/CreditRepository.java
Java
unknown
8,949
package zack.project.infrastructure.persistent.repository; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RBlockingQueue; import org.redisson.api.RDelayedQueue; import org.redisson.api.RMap; import org.springframework.stereotype.Repository; import zack.project.domain.strategy.adapter.repository.IStrategyRepository; import zack.project.domain.strategy.model.entity.StrategyAwardEntity; import zack.project.domain.strategy.model.entity.StrategyEntity; import zack.project.domain.strategy.model.entity.StrategyRuleEntity; import zack.project.domain.strategy.model.valobj.*; import zack.project.domain.strategy.service.rule.chain.factory.DefaultChainFactory; import zack.project.infrastructure.persistent.dao.*; import zack.project.infrastructure.persistent.po.*; import zack.project.infrastructure.persistent.redis.RedissonService; import zack.project.types.common.Constants; import zack.project.types.exception.AppException; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.TimeUnit; import static zack.project.types.enums.ResponseCode.UN_ASSEMBLED_STRATEGY_ARMORY; @Slf4j @Repository public class StrategyRepository implements IStrategyRepository { @Resource private IStrategyAwardDao strategyAwardDao; @Resource private RedissonService redissonService; @Resource private IStrategyDao strategyDao; @Resource private IStrategyRuleDao strategyRuleDao; @Resource private IRuleTreeDao ruleTreeDao; @Resource private IRuleTreeNodeDao ruleTreeNodeDao; @Resource private IRuleTreeNodeLineDao ruleTreeNodeLineDao; @Resource private IRaffleActivityDao raffleActivityDao; @Resource private IRaffleActivityAccountDayDao raffleActivityAccountDayDao; @Resource private IRaffleActivityAccountDao raffleActivityAccountDao; //查询属于strategyId的奖品列表 // 先在redis缓存中查再从数据库查 @Override public List<StrategyAwardEntity> queryStrategyAwardList(Long strategyId) { //预热strategyId的奖品列表 String cacheKey = Constants.RedisKey.STRATEGY_AWARD_LIST_KEY + strategyId; List<StrategyAwardEntity> strategyAwardEntityList = redissonService.getValue(cacheKey); if (null != strategyAwardEntityList && !strategyAwardEntityList.isEmpty()) { return strategyAwardEntityList; } //查询数据库表{strategy_award}中属于strategyId 的 StrategyAward列表 List<StrategyAward> strategyAwards = strategyAwardDao.queryStrategyAwardListByStrategyId(strategyId); strategyAwardEntityList = new ArrayList<>(strategyAwards.size()); for (StrategyAward strategyAward : strategyAwards) { StrategyAwardEntity strategyAwardEntity = StrategyAwardEntity.builder() .strategyId(strategyAward.getStrategyId()) .awardId(strategyAward.getAwardId()) .awardCount(strategyAward.getAwardCount()) .awardCountSurplus(strategyAward.getAwardCountSurplus()) .awardRate(strategyAward.getAwardRate()) .awardSubtitle(strategyAward.getAwardSubtitle()) .awardTitle(strategyAward.getAwardTitle()) .sort(strategyAward.getSort()) .ruleModels(strategyAward.getRuleModels()) .build(); strategyAwardEntityList.add(strategyAwardEntity); } //存入缓存 redissonService.setValue(cacheKey, strategyAwardEntityList); return strategyAwardEntityList; } /** * 存储总坑位树和抽奖的概率配置 * @param key * @param rateRange * @param strategyAwardSearchRateTable */ @Override public void storeStrategyAwardSearchRateTable(String key, Integer rateRange, Map<Integer, Integer> strategyAwardSearchRateTable) { //往redis里存raterange方便生成一个在raterange范围内的随机数, // 当raterange=1000时,就生成0-1000以内的随机数进行抽奖 //如果是分布式集群,别的节点可以读取raterange进行抽奖操作 redissonService.setValue(Constants.RedisKey.STRATEGY_RATE_RANGE_KEY + key, rateRange); RMap<Integer, Integer> map = redissonService.getMap(Constants.RedisKey.STRATEGY_RATE_TABLE_KEY + key); map.putAll(strategyAwardSearchRateTable); } @Override public int getRateRange(Long strategyId) { return getRateRange(String.valueOf(strategyId)); } @Override public int getRateRange(String key) { String cacheKey = Constants.RedisKey.STRATEGY_RATE_RANGE_KEY + key; if (!redissonService.isExists(cacheKey)) { throw new AppException(UN_ASSEMBLED_STRATEGY_ARMORY.getCode(), cacheKey + Constants.COLON + UN_ASSEMBLED_STRATEGY_ARMORY.getInfo()); } return redissonService.getValue(cacheKey); } @Override public Integer getStrategyAwardAssemble(String key, Integer random) { return redissonService.getFromMap(Constants.RedisKey.STRATEGY_RATE_TABLE_KEY + key, random); } @Override public StrategyEntity queryStrategyEntityByStrategyId(Long strategyId) { String cacheKey = Constants.RedisKey.STRATEGY_KEY + strategyId; StrategyEntity strategyEntity = redissonService.getValue(cacheKey); if (strategyEntity != null) { return strategyEntity; } Strategy strategy = strategyDao.queryStrategyByStrategyId(strategyId); if (strategy == null) { return StrategyEntity.builder().build(); } strategyEntity = StrategyEntity.builder() .strategyId(strategy.getStrategyId()) .strategyDesc(strategy.getStrategyDesc()) .ruleModels(strategy.getRuleModels()) .build(); redissonService.setValue(cacheKey, strategyEntity); return strategyEntity; } @Override public StrategyRuleEntity queryStrategyRule(Long strategyId, String ruleModel) { StrategyRule strategyRuleReq = new StrategyRule(); strategyRuleReq.setStrategyId(strategyId); strategyRuleReq.setRuleModel(ruleModel); StrategyRule strategyRuleRes = strategyRuleDao.queryStrategyRule(strategyRuleReq); return StrategyRuleEntity.builder() .strategyId(strategyRuleRes.getStrategyId()) .awardId(strategyRuleRes.getAwardId()) .ruleType(strategyRuleRes.getRuleType()) .ruleModel(strategyRuleRes.getRuleModel()) .ruleValue(strategyRuleRes.getRuleValue()) .ruleDesc(strategyRuleRes.getRuleDesc()) .build(); } @Override public String queryStrategyRuleValue(Long strategyId, Integer awardId, String ruleModel) { StrategyRule strategyRule = new StrategyRule(); strategyRule.setStrategyId(strategyId); strategyRule.setAwardId(awardId); strategyRule.setRuleModel(ruleModel); String s = strategyRuleDao.queryStrategyRuleValue(strategyRule); return s; } @Override public String queryStrategyRuleValue(Long strategyId, String ruleModel) { return queryStrategyRuleValue(strategyId, null, ruleModel); } @Override public StrategyAwardRuleModelVO queryStrategyAwardRuleModelVO(Long strategyId, Integer randomAwardId) { StrategyAward strategyAward = new StrategyAward(); strategyAward.setStrategyId(strategyId); strategyAward.setAwardId(randomAwardId); String ruleModel = strategyAwardDao.queryStrategyAwardRuleModels(strategyAward); if (ruleModel == null) { return null; } return StrategyAwardRuleModelVO.builder().ruleModel(ruleModel).build(); } /** * 根据在数据库表{strategy_award}查找到的rule_models(决策树id)去配置对应的决策时 * @param treeId * @return */ @Override public RuleTreeVO queryRuleTreeVOByTreeId(String treeId) { //先在缓存中查找是否有已经装配好的决策树 String cacheKey = Constants.RedisKey.RULE_TREE_VO_KEY + treeId; RuleTreeVO ruleTreeVOCache = redissonService.getValue(cacheKey); if (ruleTreeVOCache != null) { return ruleTreeVOCache; } //在数据库表{rule_tree}中查找tree配置 // ,如{treeId:tree_luck_award treeName:规则树-兜底奖励 treeDesc规则树-兜底奖励 treeNodeRuleKey:rule_stock} RuleTree ruleTree = ruleTreeDao.queryRuleTreeByTreeId(treeId); //根据treeId在数据库表{rule_tree_node}中查找该id对应的决策树下的所有节点 List<RuleTreeNode> ruleTreeNodes = ruleTreeNodeDao.queryRuleTreeNodeListByTreeId(treeId); //根据treeId在数据库表{rule_tree_node_line}中查找节点的连接关系和放行与否 List<RuleTreeNodeLine> ruleTreeNodeLines = ruleTreeNodeLineDao. queryRuleTreeNodeLineListByTreeId(treeId); //构建(from节点名,List<RuleTreeNodeLineVO>)的map, // map的一条链表上,key是from节点名,value是(from节点名,to节点名,···)的list Map<String, List<RuleTreeNodeLineVO>> ruleTreeNodeLineVOHashMap = new HashMap<>(); for (RuleTreeNodeLine ruleTreeNodeLine : ruleTreeNodeLines) { RuleTreeNodeLineVO ruleTreeNodeLineVO = RuleTreeNodeLineVO.builder() .treeId(ruleTreeNodeLine.getTreeId()) .ruleNodeFrom(ruleTreeNodeLine.getRuleNodeFrom()) .ruleNodeTo(ruleTreeNodeLine.getRuleNodeTo()) .ruleLimitType(RuleLimitTypeVO.valueOf(ruleTreeNodeLine.getRuleLimitType())) .ruleLimitValue(RuleLogicCheckTypeVO.valueOf(ruleTreeNodeLine.getRuleLimitValue())) .build(); ruleTreeNodeLineVOHashMap.computeIfAbsent(ruleTreeNodeLine.getRuleNodeFrom(), k -> new ArrayList<RuleTreeNodeLineVO>()).add(ruleTreeNodeLineVO); } //构建节点表 Map<String, RuleTreeNodeVO> ruleTreeNodeVOHashMap = new HashMap<String, RuleTreeNodeVO>(); for (RuleTreeNode ruleTreeNode : ruleTreeNodes) { RuleTreeNodeVO ruleTreeNodeVO = RuleTreeNodeVO.builder() .treeId(ruleTreeNode.getTreeId()) .ruleKey(ruleTreeNode.getRuleKey()) .ruleDesc(ruleTreeNode.getRuleDesc()) .ruleValue(ruleTreeNode.getRuleValue()) .treeNodeLineVOList(ruleTreeNodeLineVOHashMap.get(ruleTreeNode.getRuleKey())) .build(); ruleTreeNodeVOHashMap.put(ruleTreeNode.getRuleKey(), ruleTreeNodeVO); } RuleTreeVO resultRuleTreeVO = RuleTreeVO.builder() .treeId(treeId) .treeDesc(ruleTree.getTreeDesc()) .treeName(ruleTree.getTreeName()) .treeRootRuleNode(ruleTree.getTreeRootRuleKey()) .treeNodeMap(ruleTreeNodeVOHashMap) .build(); redissonService.setValue(cacheKey, resultRuleTreeVO); return resultRuleTreeVO; } @Override public void cacheStrategyAwardCount(String cacheKey, Integer awardCount) { if (redissonService.isExists(cacheKey)) { return; } redissonService.setAtomicLong(cacheKey, awardCount); } @Override public boolean subtractionAwardStock(String cacheKey) { return subtractionAwardStock(cacheKey, null); } @Override public Boolean subtractionAwardStock(String cacheKey, Date endDateTime) { long surplus = redissonService.decr(cacheKey); if (surplus < 0) { redissonService.setAtomicLong(cacheKey, 0); return false; } String lockKey = cacheKey + Constants.UNDERLINE + surplus; boolean lock = false; if (endDateTime != null) { long expireMillis = endDateTime.getTime() - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1); lock = redissonService.setNx(lockKey, expireMillis, TimeUnit.MILLISECONDS); } else { lock = redissonService.setNx(lockKey); } if (!lock) { log.info("策略奖品库存加锁失败 {}", lockKey); } return lock; } @Override public void awardStockConsumeSendQueue(StrategyAwardStockKeyVO strategyAwardStockKeyVO) { String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_QUERY_KEY; RBlockingQueue<StrategyAwardStockKeyVO> blockingQueue = redissonService.getBlockingQueue(cacheKey); RDelayedQueue<StrategyAwardStockKeyVO> delayedQueue = redissonService.getDelayedQueue(blockingQueue); delayedQueue.offer(strategyAwardStockKeyVO, 3, TimeUnit.SECONDS); } /** * 消费阻塞队列消息 * @return */ @Override public StrategyAwardStockKeyVO takeQueueValue() { String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_QUERY_KEY; RBlockingQueue<StrategyAwardStockKeyVO> blockingQueue = redissonService.getBlockingQueue(cacheKey); return blockingQueue.poll(); } @Override public void updateStrategyAwardStock(Long strategyId, Integer awardId) { StrategyAward strategyAward = new StrategyAward(); strategyAward.setStrategyId(strategyId); strategyAward.setAwardId(awardId); strategyAwardDao.updateStrategyAwardStock(strategyAward); } @Override public StrategyAwardEntity queryStrategyEntity(Long strategyId, Integer awardId) { String cacheKey = Constants.RedisKey.STRATEGY_AWARD_KEY + strategyId + Constants.UNDERLINE + awardId; StrategyAwardEntity strategyAwardEntity = redissonService.getValue(cacheKey); if (strategyAwardEntity != null) { return strategyAwardEntity; } StrategyAward strategyAwardReq = new StrategyAward(); strategyAwardReq.setStrategyId(strategyId); strategyAwardReq.setAwardId(awardId); StrategyAward strategyAwardRes = strategyAwardDao.queryStrategyAward(strategyAwardReq); strategyAwardEntity = StrategyAwardEntity.builder() .strategyId(strategyAwardRes.getStrategyId()) .awardId(strategyAwardRes.getAwardId()) .awardCount(strategyAwardRes.getAwardCount()) .awardCountSurplus(strategyAwardRes.getAwardCountSurplus()) .awardRate(strategyAwardRes.getAwardRate()) .awardTitle(strategyAwardRes.getAwardTitle()) .awardSubtitle(strategyAwardRes.getAwardSubtitle()) .sort(strategyAwardRes.getSort()) .ruleModels(strategyAwardRes.getRuleModels()) .build(); redissonService.setValue(cacheKey, strategyAwardEntity); return strategyAwardEntity; } @Override public Long queryStrategyIdByActivityId(Long activityId) { return raffleActivityDao.queryStrategyIdByActivityId(activityId); } @Override public Integer queryTodayUserRaffleCount(String userId, Long strategyId) { Long activityId = raffleActivityDao.queryActivityIdByStrategyId(strategyId); RaffleActivityAccountDay raffleActivityAccountDayReq = new RaffleActivityAccountDay(); raffleActivityAccountDayReq.setUserId(userId); raffleActivityAccountDayReq.setActivityId(activityId); raffleActivityAccountDayReq.setDay(raffleActivityAccountDayReq.curDay()); RaffleActivityAccountDay raffleActivityAccountDay = raffleActivityAccountDayDao.queryActivityAccountDayByUserId(raffleActivityAccountDayReq); if (raffleActivityAccountDay == null) { return null; } return raffleActivityAccountDay.getDayCount() - raffleActivityAccountDay.getDayCountSurplus(); } @Override public Map<String, Integer> queryAwardRuleLockCount(String[] treeIds) { if (treeIds == null || treeIds.length == 0) { return new HashMap<>(); } List<RuleTreeNode> ruleTreeNodes = ruleTreeNodeDao.queryRuleLocks(treeIds); HashMap<String, Integer> resultMap = new HashMap<>(); for (RuleTreeNode ruleTreeNode : ruleTreeNodes) { String treeId = ruleTreeNode.getTreeId(); Integer count = Integer.parseInt(ruleTreeNode.getRuleValue()); resultMap.put(treeId, count); } return resultMap; } @Override public List<RuleWeightVO> queryAwardRuleWeight(Long strategyId) { String cacheKey = Constants.RedisKey.STRATEGY_RULE_WEIGHT_KEY + strategyId; List<RuleWeightVO> ruleWeightVOS = redissonService.getValue(cacheKey); if (ruleWeightVOS != null) { return ruleWeightVOS; } ruleWeightVOS = new ArrayList<>(); StrategyRule strategyRuleReq = new StrategyRule(); strategyRuleReq.setStrategyId(strategyId); strategyRuleReq.setRuleModel(DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode()); String ruleValue = strategyRuleDao.queryStrategyRuleValue(strategyRuleReq); StrategyRuleEntity strategyRuleEntity = new StrategyRuleEntity(); strategyRuleEntity.setRuleValue(ruleValue); strategyRuleEntity.setRuleModel(DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode()); Map<String, List<Integer>> ruleWeightValues = strategyRuleEntity.getRuleWeightValues(); Set<String> ruleWeightKeys = ruleWeightValues.keySet(); for (String ruleWeightKey : ruleWeightKeys) { List<Integer> awardIds = ruleWeightValues.get(ruleWeightKey); ArrayList<RuleWeightVO.Award> awards = new ArrayList<>(); for (Integer awardId : awardIds) { StrategyAward strategyAwardReq = new StrategyAward(); strategyAwardReq.setStrategyId(strategyId); strategyAwardReq.setAwardId(awardId); StrategyAward strategyAward = strategyAwardDao.queryStrategyAward(strategyAwardReq); awards.add(RuleWeightVO.Award.builder() .awardId(strategyAward.getAwardId()) .awardTitle(strategyAward.getAwardTitle()) .build()); } ruleWeightVOS.add(RuleWeightVO.builder() .ruleValue(ruleValue) .weight(Integer.valueOf(ruleWeightKey.split(Constants.COLON)[0])) .awardIds(awardIds) .awardList(awards) .build()); } redissonService.setValue(cacheKey, ruleWeightVOS); return ruleWeightVOS; } @Override public Integer queryActivityAccountTotalUseCount(String userId, Long strategyId) { Long activityId = raffleActivityDao.queryActivityIdByStrategyId(strategyId); RaffleActivityAccount activityAccount = raffleActivityAccountDao.queryActivityAccountByUserId(RaffleActivityAccount.builder().userId(userId).activityId(activityId).build()); //活动配置的总次数-可用剩余次数即用户已经抽奖次数 return activityAccount.getTotalCount() - activityAccount.getTotalCountSurplus(); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/StrategyRepository.java
Java
unknown
19,406
package zack.project.infrastructure.persistent.repository; import zack.project.domain.task.adapter.repository.ITaskRepository; import zack.project.domain.task.model.entity.TaskEntity; import zack.project.infrastructure.event.EventPublisher; import zack.project.infrastructure.persistent.dao.ITaskDao; import zack.project.infrastructure.persistent.po.Task; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * @author A1793 */ @Repository public class TaskRepository implements ITaskRepository { @Resource private ITaskDao taskDao; @Resource private EventPublisher eventPublisher; @Override public List<TaskEntity> queryNoSendMessageTaskList() { List<Task> taskList = taskDao.queryNoSendMessageTaskList(); ArrayList<TaskEntity> taskEntities = new ArrayList<>(taskList.size()); for (Task task : taskList) { TaskEntity taskEntity = TaskEntity.builder() .userId(task.getUserId()) .topic(task.getTopic()) .messageId(task.getMessageId()) .message(task.getMessage()) .build(); taskEntities.add(taskEntity); } return taskEntities; } @Override public void sendMessage(TaskEntity taskEntity) { eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage()); } @Override public void updateTaskSendMessageCompleted(String userId, String messageId) { Task task = new Task(); task.setUserId(userId); task.setMessageId(messageId); taskDao.updateTaskSendMessageCompleted(task); } @Override public void updateTaskSendMessageFail(String userId, String messageId) { Task task = new Task(); task.setUserId(userId); task.setMessageId(messageId); taskDao.updateTaskSendMessageCompleted(task); } }
2301_82000044/big-market-z
bigmarket-infrastructure/src/main/java/zack/project/infrastructure/persistent/repository/TaskRepository.java
Java
unknown
2,002
package zack.project.trigger.http; import zack.project.trigger.api.IDCCService; import zack.project.trigger.api.response.Response; import zack.project.types.enums.ResponseCode; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.data.Stat; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.nio.charset.StandardCharsets; @Slf4j @RestController() @CrossOrigin("${app.config.cross-origin}") @RequestMapping("/api/${app.config.api-version}/raffle/dcc/") public class DCCController implements IDCCService { @Resource private CuratorFramework client; private static final String BASE_CONFIG_PATH = "/big-market-dcc"; private static final String BASE_CONFIG_PATH_CONFIG = BASE_CONFIG_PATH + "/config"; @RequestMapping(value = "update_config", method = RequestMethod.GET) @Override public Response<Boolean> updateConfig(@RequestParam String key, @RequestParam String value) { try { log.info("DCC 动态配置值变更开始 key:{} value:{}", key, value); //设置要变更值的key路径 String keyPath = BASE_CONFIG_PATH_CONFIG + key; if (null == client.checkExists().forPath(keyPath)) { client.create().creatingParentsIfNeeded().forPath(keyPath); log.info("DCC 节点监听 base node {} not absent create new done!", keyPath); } Stat stat = client.setData().forPath(keyPath, value.getBytes(StandardCharsets.UTF_8)); log.info("DCC 动态配置值变更完成 key:{} value:{} time:{}", key, value, stat.getCtime()); return Response.<Boolean>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(true).build(); } catch (Exception e) { log.error("DCC 动态配置值变更失败 key:{} value:{}", key, value, e); return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data(false).build(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/http/DCCController.java
Java
unknown
2,110
package zack.project.trigger.http; import com.alibaba.fastjson.JSON; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.Service; import org.springframework.web.bind.annotation.*; import zack.project.domain.activity.model.entity.*; import zack.project.domain.activity.model.valobj.OrderTradeTypeVO; import zack.project.domain.activity.service.IRaffleActivityAccountQuotaService; import zack.project.domain.activity.service.IRaffleActivityPartakeService; import zack.project.domain.activity.service.IRaffleActivitySkuProductService; import zack.project.domain.activity.service.armory.IActivityArmory; import zack.project.domain.award.model.entity.UserAwardRecordEntity; import zack.project.domain.award.model.valobj.AwardStateVO; import zack.project.domain.award.service.IAwardService; import zack.project.domain.credit.model.entity.CreditAccountEntity; import zack.project.domain.credit.model.entity.TradeEntity; import zack.project.domain.credit.model.valobj.TradeNameVO; import zack.project.domain.credit.model.valobj.TradeTypeVO; import zack.project.domain.credit.service.ICreditAdjustService; import zack.project.domain.rebate.model.entity.BehaviorEntity; import zack.project.domain.rebate.model.entity.BehaviorRebateOrderEntity; import zack.project.domain.rebate.model.valobj.BehaviorTypeVO; import zack.project.domain.rebate.service.IBehaviorRebateService; import zack.project.domain.strategy.model.entity.RaffleAwardEntity; import zack.project.domain.strategy.model.entity.RaffleFactorEntity; import zack.project.domain.strategy.service.IRaffleStrategy; import zack.project.domain.strategy.service.armory.IStrategyArmory; import zack.project.trigger.api.IRaffleActivityService; import zack.project.trigger.api.dto.*; import zack.project.trigger.api.response.Response; import zack.project.types.annotation.DCCValue; import zack.project.types.annotation.RateLimiterAccessInterceptor; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import javax.annotation.Resource; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author A1793 */ @Slf4j @RestController() @CrossOrigin("${app.config.cross-origin}") @RequestMapping("/api/${app.config.api-version}/raffle/activity/") @Service(version = "1.0") public class RaffleActivityController implements IRaffleActivityService { private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyyMMdd"); @Resource private IRaffleActivityPartakeService partakeService; @Resource private IRaffleStrategy raffleStrategy; @Resource private IAwardService awardService; @Resource private IActivityArmory activityArmory; @Resource private IStrategyArmory strategyArmory; @Resource private IBehaviorRebateService rebateService; @Resource private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService; @Resource private IRaffleActivitySkuProductService raffleActivitySkuProductService; @Resource private ICreditAdjustService creditAdjustService; // dcc 统一配置中心动态配置降级开关 @DCCValue("degradeSwitch:close") private String degradeSwitch; @RequestMapping(value = "armory", method = RequestMethod.GET) @Override public Response<Boolean> armory(@RequestParam Long activityId) { try { log.info("活动装配,数据预热,开始 activityId:{}", activityId); //根据活动id装配活动余额, activityArmory.assembleActivitySkuByActivityId(activityId); //根据活动id装配抽奖策略 strategyArmory.assembleLotteryStrategyByActivityId(activityId); Response<Boolean> response = new Response<>(); response.setCode(ResponseCode.SUCCESS.getCode()); response.setInfo(ResponseCode.SUCCESS.getInfo()); log.info("活动装配,数据预热,完成 activityId:{}", activityId); return response; } catch (Exception e) { log.error("活动装配,数据预热,失败 activityId:{}", activityId, e); Response<Boolean> response = new Response<>(); response.setCode(ResponseCode.UN_ERROR.getCode()); response.setInfo(ResponseCode.UN_ERROR.getInfo()); return response; } } /** * 获取一笔抽奖单() * @param request 请求对象 * @return */ @RateLimiterAccessInterceptor(key = "userId", fallbackMethod = "drawRateLimiterError", permitsPerSecond = 1.0d, blacklistCount = 1) @HystrixCommand(commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "150") }, fallbackMethod = "drawHystrixError" ) @RequestMapping(value = "draw", method = RequestMethod.POST) @Override public Response<ActivityDrawResponseDTO> draw(@RequestBody ActivityDrawRequestDTO request) { try { log.info("活动抽奖 userId:{} activityId:{}", request.getUserId(), request.getActivityId()); if (StringUtils.isNotBlank(degradeSwitch) && "open".equals(degradeSwitch)) { return Response.<ActivityDrawResponseDTO>builder() .code(ResponseCode.DEGRADE_SWITCH.getCode()) .info(ResponseCode.DEGRADE_SWITCH.getInfo()) .build(); } Long activityId = request.getActivityId(); String userId = request.getUserId(); //参数校验 if (activityId == null || userId == null) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } //用户消耗参与抽奖活动的次数(数据库表{raffle_activity_account}, // raffle_activity_account_month},raffle_activity_account_day}),生成一笔抽奖单 UserRaffleOrderEntity orderEntity = partakeService. createOrder(PartakeRaffleActivityEntity.builder().activityId(activityId).userId(userId).build()); log.info("活动抽奖,创建订单 userId:{} activityId:{} orderId:{}", request.getUserId(), request.getActivityId(), orderEntity.getOrderId()); //进行抽奖 RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder() .strategyId(orderEntity.getStrategyId()) .userId(userId) .endTime(orderEntity.getEndTime()) .build()); //构建中奖实体,设置活动信息,奖品信息,抽奖单单号 UserAwardRecordEntity userAwardRecordEntity = new UserAwardRecordEntity(); userAwardRecordEntity.setUserId(userId); userAwardRecordEntity.setActivityId(activityId); userAwardRecordEntity.setStrategyId(orderEntity.getStrategyId()); //用户中奖记录的orderId是用户的抽奖单的orderId userAwardRecordEntity.setOrderId(orderEntity.getOrderId()); userAwardRecordEntity.setAwardId(raffleAwardEntity.getAwardId()); userAwardRecordEntity.setAwardTitle(raffleAwardEntity.getAwardTitle()); userAwardRecordEntity.setAwardTime(new Date()); userAwardRecordEntity.setAwardState(AwardStateVO.create); userAwardRecordEntity.setAwardConfig(raffleAwardEntity.getAwardConfig()); //保存中奖信息,更新抽奖单状态,保存发奖补偿任务,发送发奖消息 awardService.saveUserAwardRecord(userAwardRecordEntity); ActivityDrawResponseDTO activityDrawResponseDTO = new ActivityDrawResponseDTO(); activityDrawResponseDTO.setAwardId(raffleAwardEntity.getAwardId()); activityDrawResponseDTO.setAwardTitle(raffleAwardEntity.getAwardTitle()); activityDrawResponseDTO.setAwardIndex(raffleAwardEntity.getSort()); return Response.<ActivityDrawResponseDTO>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(activityDrawResponseDTO).build(); } catch (AppException e) { log.error("活动抽奖失败 userId:{} activityId:{}", request.getUserId(), request.getActivityId(), e); return Response.<ActivityDrawResponseDTO>builder().code(e.getCode()).info(e.getInfo()).build(); } catch (Exception e) { log.error("活动抽奖失败 userId:{} activityId:{}", request.getUserId(), request.getActivityId(), e); return Response.<ActivityDrawResponseDTO>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).build(); } } public Response<ActivityDrawResponseDTO> drawRateLimiterError(@RequestBody ActivityDrawRequestDTO request) { log.info("活动抽奖限流 userId:{} activityId:{}", request.getUserId(), request.getActivityId()); return Response.<ActivityDrawResponseDTO>builder().code(ResponseCode.RATE_LIMITER.getCode()).info(ResponseCode.RATE_LIMITER.getInfo()).build(); } public Response<ActivityDrawResponseDTO> drawHystrixError(@RequestBody ActivityDrawRequestDTO request) { log.info("活动抽奖熔断 userId:{} activityId:{}", request.getUserId(), request.getActivityId()); return Response.<ActivityDrawResponseDTO>builder().code(ResponseCode.HYSTRIX.getCode()).info(ResponseCode.HYSTRIX.getInfo()).build(); } @RequestMapping(value = "calendar_sign_rebate", method = RequestMethod.POST) @Override public Response<Boolean> calendarSignRebate(@RequestParam String userId) { try { log.info("日历签到返利开始 userId:{}", userId); //创建行为实体 BehaviorEntity behaviorEntity = new BehaviorEntity(); behaviorEntity.setUserId(userId); behaviorEntity.setBehaviorTypeVO(BehaviorTypeVO.SIGN); //用当前日期作为外部单号 behaviorEntity.setOutBusinessNo(dateFormatDay.format(new Date())); List<String> orderIds = rebateService.createOrder(behaviorEntity); log.info("日历签到返利完成 userId:{} orderIds: {}", userId, JSON.toJSONString(orderIds)); return Response.<Boolean>builder(). code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()). data(true).build(); } catch (AppException e) { log.error("日历签到返利异常 userId:{} ", userId, e); return Response.<Boolean>builder().code(e.getCode()).info(e.getInfo()).data(false).build(); } catch (Exception e) { log.error("日历签到返利失败 userId:{}", userId); return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data(false).build(); } } @RequestMapping(value = "is_calendar_sign_rebate", method = RequestMethod.POST) @Override public Response<Boolean> isCalendarSignRebate(@RequestParam String userId) { try { log.info("查询用户是否完成日历签到返利开始 userId:{}", userId); String outBusinessNo = dateFormatDay.format(new Date()); List<BehaviorRebateOrderEntity> behaviorRebateOrderEntities = rebateService.queryOrderByOutBusinessNo(userId, outBusinessNo); log.info("查询用户是否完成日历签到返利完成 userId:{} orders.size:{}", userId, behaviorRebateOrderEntities.size()); return Response.<Boolean>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(!behaviorRebateOrderEntities.isEmpty()) .build(); } catch (Exception e) { log.error("查询用户是否完成日历签到返利失败 userId:{}", userId, e); return Response.<Boolean>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .data(false) .build(); } } @RequestMapping(value = "query_user_activity_account", method = RequestMethod.POST) @Override public Response<UserActivityAccountResponseDTO> queryUserActivityAccount(@RequestBody UserActivityAccountRequestDTO request) { try { log.info("查询用户活动账户开始 userId:{} activityId:{}", request.getUserId(), request.getActivityId()); //参数判断 if (StringUtils.isBlank(request.getUserId()) || request.getActivityId() == null) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } ActivityAccountEntity activityAccountEntity = raffleActivityAccountQuotaService.queryActivityAccountEntity(request.getUserId(), request.getActivityId()); UserActivityAccountResponseDTO userActivityAccountResponseDTO = UserActivityAccountResponseDTO.builder() .totalCount(activityAccountEntity.getTotalCount()) .totalCountSurplus(activityAccountEntity.getTotalCountSurplus()) .dayCount(activityAccountEntity.getDayCount()) .dayCountSurplus(activityAccountEntity.getDayCountSurplus()) .monthCount(activityAccountEntity.getMonthCount()) .monthCountSurplus(activityAccountEntity.getMonthCountSurplus()) .build(); log.info("查询用户活动账户完成 userId:{} activityId:{} dto:{}", request.getUserId(), request.getActivityId(), JSON.toJSONString(userActivityAccountResponseDTO)); return Response.<UserActivityAccountResponseDTO>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(userActivityAccountResponseDTO) .build(); } catch (Exception e) { log.error("查询用户活动账户失败 userId:{} activityId:{}", request.getUserId(), request.getActivityId(), e); return Response.<UserActivityAccountResponseDTO>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } @RequestMapping(value = "query_sku_product_list_by_activity_id", method = RequestMethod.POST) @Override public Response<List<SkuProductResponseDTO>> querySkuProductListByActivityId(Long activityId) { try { List<SkuProductEntity> skuProductEntities = raffleActivitySkuProductService.querySkuProductEntityListByActivityId(activityId); ArrayList<SkuProductResponseDTO> skuProductResponseDTOS = new ArrayList<>(skuProductEntities.size()); for (SkuProductEntity skuProductEntity : skuProductEntities) { SkuProductResponseDTO.ActivityCount activityCount = new SkuProductResponseDTO.ActivityCount(); activityCount.setDayCount(skuProductEntity.getActivityCount().getDayCount()); activityCount.setMonthCount(skuProductEntity.getActivityCount().getMonthCount()); activityCount.setTotalCount(skuProductEntity.getActivityCount().getTotalCount()); SkuProductResponseDTO skuProductResponseDTO = SkuProductResponseDTO.builder() .sku(skuProductEntity.getSku()) .activityId(skuProductEntity.getActivityId()) .activityCountId(skuProductEntity.getActivityCountId()) .productAmount(skuProductEntity.getPayAmount()) .stockCount(skuProductEntity.getStockCount()) .stockCountSurplus(skuProductEntity.getStockCountSurplus()) .activityCount(activityCount) .build(); skuProductResponseDTOS.add(skuProductResponseDTO); } log.info("查询sku商品集合完成 activityId:{} skuProductResponseDTOS:{}", activityId, JSON.toJSONString(skuProductResponseDTOS)); return Response.<List<SkuProductResponseDTO>>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(skuProductResponseDTOS) .build(); } catch (Exception e) { log.error("查询sku商品集合失败 activityId:{}", activityId, e); return Response.<List<SkuProductResponseDTO>>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } @RequestMapping(value = "query_user_credit_account", method = RequestMethod.POST) @Override public Response<BigDecimal> queryUserCreditAccount(String userId) { try { log.info("查询用户积分值开始 userId:{}", userId); CreditAccountEntity creditAccountEntity = creditAdjustService.queryUserCreditAccount(userId); log.info("查询用户积分值完成 userId:{} adjustAmount:{}", userId, creditAccountEntity.getAdjustAmount()); return Response.<BigDecimal>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(creditAccountEntity.getAdjustAmount()) .build(); } catch (Exception e) { log.error("查询用户积分值失败 userId:{}", userId, e); return Response.<BigDecimal>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } /** * 积分兑换sku商品增加抽奖次数 * 调额领域先创建一笔活动参与单(根据不同的tradeType获取不同的tradePolicy), * 根据参与单的outTradeNo,sku商品的价格去调整用户积分(扣减积分,并发送积分调整成功消息,异步将参与单状态改为完成并增加用户抽奖次数) * @param request 请求对象「用户ID、商品ID」 * @return */ @RequestMapping(value = "credit_pay_exchange_sku", method = RequestMethod.POST) @Override public Response<Boolean> creditPayExchangeSku(@RequestBody SkuProductShopCartRequestDTO request) { try { log.info("积分兑换商品开始 userId:{} sku:{}", request.getUserId(), request.getSku()); //需要支付的充值单则扣减sku库存并插入一条参与单(raffle_activity_order) UnpaidActivityOrderEntity unpaidActivityOrderEntity = raffleActivityAccountQuotaService.createOrder(SkuRechargeEntity.builder() .sku(request.getSku()) .userId(request.getUserId()) .outBusinessNo(RandomStringUtils.randomNumeric(12)) .orderTradeTypeVO(OrderTradeTypeVO.credit_pay_trade) .build()); log.info("积分兑换商品,创建订单完成 userId:{} sku:{} outBusinessNo:{}", request.getUserId(), request.getSku(), unpaidActivityOrderEntity.getOutBusinessNo()); //根据对应的sku商品生成的未支付的参与单订单创建交易实体实体,进行交易,如果是积分交易若成功则会发送一个积分调额成功的消息 String orderId = creditAdjustService.createOrder(TradeEntity.builder() .userId(unpaidActivityOrderEntity.getUserId()) //外部订单id,这里是上面生成的未支付的参与单 .outBusinessNo(unpaidActivityOrderEntity.getOutBusinessNo()) .amount(unpaidActivityOrderEntity.getPayAmount().negate()) //对积分的调整有两种,一种是兑换抽奖次数的扣减,一种用户行为返利奖励积分 .tradeNameVO(TradeNameVO.CONVERT_SKU) .tradeTypeVO(TradeTypeVO.REVERSE) .build()); log.info("积分兑换商品,支付订单完成 userId:{} sku:{} orderId:{}", request.getUserId(), request.getSku(), orderId); return Response.<Boolean>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(true) .build(); } catch (Exception e) { log.error("积分兑换商品失败 userId:{} sku:{}", request.getUserId(), request.getSku(), e); return Response.<Boolean>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .data(false) .build(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/http/RaffleActivityController.java
Java
unknown
21,484
package zack.project.trigger.http; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.Service; import org.springframework.web.bind.annotation.*; import zack.project.domain.activity.service.IRaffleActivityAccountQuotaService; import zack.project.domain.strategy.model.entity.RaffleAwardEntity; import zack.project.domain.strategy.model.entity.RaffleFactorEntity; import zack.project.domain.strategy.model.entity.StrategyAwardEntity; import zack.project.domain.strategy.model.valobj.RuleWeightVO; import zack.project.domain.strategy.service.IRaffleAward; import zack.project.domain.strategy.service.IRaffleRule; import zack.project.domain.strategy.service.IRaffleStrategy; import zack.project.domain.strategy.service.armory.IStrategyArmory; import zack.project.trigger.api.IRaffleStrategyService; import zack.project.trigger.api.dto.*; import zack.project.trigger.api.response.Response; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author A1793 */ @Slf4j @RestController() @CrossOrigin("${app.config.cross-origin}") @RequestMapping("/api/${app.config.api-version}/raffle/strategy/") @Service(version = "1.0") public class RaffleStrategyController implements IRaffleStrategyService { @Resource IRaffleAward raffleAward; @Resource IStrategyArmory strategyArmory; @Resource IRaffleStrategy raffleStrategy; @Resource IRaffleRule raffleRule; @Resource IRaffleActivityAccountQuotaService activityAccountQuotaService; @RequestMapping(value = "query_raffle_award_list", method = RequestMethod.POST) @Override public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO request) { log.info("查询抽奖奖品列表配开始 userId:{} activityId:{}", request.getUserId(), request.getActivityId()); try { //参数校验 if (StringUtils.isBlank(request.getUserId()) || request.getActivityId() == null) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } //查询奖品配置 List<StrategyAwardEntity> strategyAwardEntityList = raffleAward. queryRaffleStrategyAwardListByActivityId(request.getActivityId()); //查询具体配置 String[] treeIds = strategyAwardEntityList.stream() .map(StrategyAwardEntity::getRuleModels) .filter(ruleModel -> ruleModel != null && !ruleModel.isEmpty()) .toArray(String[]::new); Map<String, Integer> ruleLockCountMap = raffleRule.queryAwardRuleLockCount(treeIds); Integer partakeCount = activityAccountQuotaService. queryRaffleActivityAccountDayPartakeCount(request.getActivityId(), request.getUserId()); List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>(strategyAwardEntityList.size()); // 5. 查询抽奖次数 - 用户已经参与的抽奖次数 for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntityList) { Integer awardLockCount = ruleLockCountMap.get(strategyAwardEntity.getRuleModels()); RaffleAwardListResponseDTO raffleAwardListResponseDTO = RaffleAwardListResponseDTO.builder() .awardId(strategyAwardEntity.getAwardId()) .awardTitle(strategyAwardEntity.getAwardTitle()) .awardSubtitle(strategyAwardEntity.getAwardSubtitle() == null ? "" : strategyAwardEntity.getAwardSubtitle()) .sort(strategyAwardEntity.getSort()) .awardRuleLockCount(awardLockCount == null ? 0 : awardLockCount) .isAwardUnlock(awardLockCount == null || partakeCount >= awardLockCount) .waitUnLockCount(awardLockCount == null || partakeCount >= awardLockCount ? 0 : awardLockCount - partakeCount) .build(); raffleAwardListResponseDTOS.add(raffleAwardListResponseDTO); } Response<List<RaffleAwardListResponseDTO>> response = Response.<List<RaffleAwardListResponseDTO>>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(raffleAwardListResponseDTOS) .build(); log.info("查询抽奖奖品列表配置完成 userId:{} activityId:{} response: {}", request.getUserId(), request.getActivityId(), JSON.toJSONString(response)); return response; } catch (Exception e) { log.error("查询抽奖奖品列表配置失败 userId:{} activityId:{}", request.getUserId(), request.getActivityId(), e); return Response.<List<RaffleAwardListResponseDTO>>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } @RequestMapping(value = "strategy_armory", method = RequestMethod.GET) @Override public Response<Boolean> strategyArmory(@RequestParam Long strategyId) { try { log.info("抽奖策略装配开始 strategyId:{}", strategyId); boolean armoryStatus = strategyArmory.assembleLotteryStrategy(strategyId); Response<Boolean> response = Response.<Boolean>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(armoryStatus) .build(); log.info("抽奖策略装配完成 strategyId:{} response: {}", strategyId, JSON.toJSONString(response)); return response; } catch (Exception e) { log.error("抽奖策略装配失败 strategyId:{}", strategyId, e); return Response.<Boolean>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } @RequestMapping(value = "random_raffle", method = RequestMethod.POST) @Override public Response<RaffleStrategyResponseDTO> randomRaffle(@RequestBody RaffleStrategyRequestDTO requestDTO) { try { log.info("随机抽奖开始 strategyId: {}", requestDTO.getStrategyId()); RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder() .strategyId(requestDTO.getStrategyId()) .userId("system").build()); RaffleStrategyResponseDTO raffleResponseDTO = RaffleStrategyResponseDTO.builder() .awardId(raffleAwardEntity.getAwardId()) .awardIndex(raffleAwardEntity.getSort()) .build(); Response<RaffleStrategyResponseDTO> build = Response.<RaffleStrategyResponseDTO>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(raffleResponseDTO).build(); log.info("随机抽奖完成 strategyId: {} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(build)); return build; } catch (AppException e) { log.error("随机抽奖失败 strategyId:{} {}", requestDTO.getStrategyId(), e.getInfo()); return Response.<RaffleStrategyResponseDTO>builder() .code(e.getCode()) .info(e.getInfo()) .build(); } catch (Exception e) { log.error("随机抽奖失败 strategyId:{}", requestDTO.getStrategyId(), e); return Response.<RaffleStrategyResponseDTO>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } @RequestMapping(value = "query_raffle_strategy_rule_weight", method = RequestMethod.POST) @Override public Response<List<RaffleStrategyRuleWeightResponseDTO>> queryRaffleStrategyRuleWeight(@RequestBody RaffleStrategyRuleWeightRequestDTO request) { try { //参数判断 if (StringUtils.isBlank(request.getUserId()) || request.getActivityId() == null) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } Integer totalCount = activityAccountQuotaService.queryRaffleActivityAccountPartakeCount(request.getActivityId(), request.getUserId()); List<RuleWeightVO> ruleWeightVOS = raffleRule.queryAwardRuleWeightByActivityId(request.getActivityId()); List<RaffleStrategyRuleWeightResponseDTO> raffleStrategyRuleWeightList = new ArrayList<>(); for (RuleWeightVO ruleWeightVO : ruleWeightVOS) { List<RaffleStrategyRuleWeightResponseDTO.StrategyAward> strategyAwards = new ArrayList<>(); List<RuleWeightVO.Award> awardList = ruleWeightVO.getAwardList(); for (RuleWeightVO.Award award : awardList) { RaffleStrategyRuleWeightResponseDTO.StrategyAward strategyAward = new RaffleStrategyRuleWeightResponseDTO.StrategyAward(); strategyAward.setAwardId(award.getAwardId()); strategyAward.setAwardTitle(award.getAwardTitle()); strategyAwards.add(strategyAward); } RaffleStrategyRuleWeightResponseDTO raffleStrategyRuleWeightResponseDTO = new RaffleStrategyRuleWeightResponseDTO(); raffleStrategyRuleWeightResponseDTO.setRuleWeightCount(ruleWeightVO.getWeight()); raffleStrategyRuleWeightResponseDTO.setAwardList(strategyAwards); raffleStrategyRuleWeightResponseDTO.setUserActivityAccountTotalUseCount(totalCount); raffleStrategyRuleWeightList.add(raffleStrategyRuleWeightResponseDTO); } return Response.<List<RaffleStrategyRuleWeightResponseDTO>>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(raffleStrategyRuleWeightList) .build(); } catch (Exception e) { return Response.<List<RaffleStrategyRuleWeightResponseDTO>>builder() .code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()) .build(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/http/RaffleStrategyController.java
Java
unknown
10,935
package zack.project.trigger.job; import zack.project.domain.task.model.entity.TaskEntity; import zack.project.domain.task.service.ITaskService; import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; import java.util.concurrent.ThreadPoolExecutor; /** * @author A1793 * @description 发送MQ消息任务队列 * @create 2024-04-06 10:47 */ @Slf4j @Component() public class SendMessageTaskJob { @Resource private ITaskService taskService; @Resource private ThreadPoolExecutor executor; @Resource private IDBRouterStrategy dbRouter; @Scheduled(cron = "0/5 * * * * ?") public void exec_db01() { try { // 设置库表 dbRouter.setDBKey(1); dbRouter.setTBKey(0); // 查询未发送的任务 List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList(); if (taskEntities.isEmpty()) { return; } // 发送MQ消息 for (TaskEntity taskEntity : taskEntities) { try { taskService.sendMessage(taskEntity); taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId()); } catch (Exception e) { log.error("定时任务,发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic()); taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId()); } } } catch (Exception e) { log.error("定时任务,扫描MQ任务表发送消息失败。", e); } finally { dbRouter.clear(); } } @Scheduled(cron = "0/5 * * * * ?") public void exec_db02() { try { // 设置库表 dbRouter.setDBKey(2); dbRouter.setTBKey(0); // 查询未发送的任务 List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList(); if (taskEntities.isEmpty()) { return; } // 发送MQ消息 for (TaskEntity taskEntity : taskEntities) { try { taskService.sendMessage(taskEntity); taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId()); } catch (Exception e) { log.error("定时任务,发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic()); taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId()); } } } catch (Exception e) { log.error("定时任务,扫描MQ任务表发送消息失败。", e); } finally { dbRouter.clear(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/job/SendMessageTaskJob.java
Java
unknown
3,115
package zack.project.trigger.job; import zack.project.domain.activity.model.valobj.ActivitySkuStockKeyVO; import zack.project.domain.activity.service.IRaffleActivitySkuStockService; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; /**更新数据库表{raffle_activity_sku}的sku商品库存 * @author A1793 */ @Slf4j @Component public class UpdateActivitySkuStockJob { @Resource private IRaffleActivitySkuStockService skuStock; @Scheduled(cron = "0/5 * * * * ?") public void exec() { try{ log.info("定时任务,更新活动sku库存【延迟队列获取,降低对数据库的更新频次,不要产生竞争】"); ActivitySkuStockKeyVO activitySkuStockKeyVO = skuStock.takeQueueValue(); if(activitySkuStockKeyVO == null) { return; } log.info("定时任务,更新活动sku库存 sku:{} activityId:{}", activitySkuStockKeyVO.getSku(), activitySkuStockKeyVO.getActivityId()); skuStock.updateActivitySkuStock(activitySkuStockKeyVO.getSku()); }catch (Exception e){ log.error("定时任务,更新活动sku库存失败", e); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/job/UpdateActivitySkuStockJob.java
Java
unknown
1,317
package zack.project.trigger.job; import zack.project.domain.strategy.model.valobj.StrategyAwardStockKeyVO; import zack.project.domain.strategy.service.IRaffleStock; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Slf4j @Component public class UpdateAwardStockJob { @Resource public IRaffleStock raffleStock; @Scheduled(cron = "0/5 * * * * ?") public void exec(){ try { log.info("定时任务,更新奖品消耗库存【延迟队列获取,降低对数据库的更新频次,不要产生竞争】"); StrategyAwardStockKeyVO strategyAwardStockKeyVO = raffleStock.takeQueueValue(); if(strategyAwardStockKeyVO == null){ return ; } log.info("定时任务,更新奖品消耗库存 strategyId:{} awardId:{}", strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId()); raffleStock.updateStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId()); }catch (Exception e){ log.error("定时任务,更新奖品消耗库存失败", e); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/job/UpdateAwardStockJob.java
Java
unknown
1,308
package zack.project.trigger.listener; import zack.project.domain.activity.service.IRaffleActivitySkuStockService; import zack.project.types.event.BaseEvent; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.TypeReference; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @author A1793 */ @Slf4j @Component public class ActivitySkuStockZeroCustomer { @Value("${spring.rabbitmq.topic.activity_sku_stock_zero}") private String topic; @Resource private IRaffleActivitySkuStockService skuStock; @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.activity_sku_stock_zero}")) public void listener(String message) { try{ log.info("监听活动sku库存消耗为0消息 topic: {} message: {}", topic, message); BaseEvent.EventMessage<Long> longEventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<Long>>(){}.getType()); Long sku = longEventMessage.getData(); skuStock.clearActivitySkuStock(sku); skuStock.clearQueueValue(); }catch (Exception e){ log.error("监听活动sku库存消耗为0消息,消费失败 topic: {} message: {}", topic, message); throw e; } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/listener/ActivitySkuStockZeroCustomer.java
Java
unknown
1,550
package zack.project.trigger.listener; import zack.project.domain.activity.model.entity.DeliveryOrderEntity; import zack.project.domain.activity.service.IRaffleActivityAccountQuotaService; import zack.project.domain.credit.event.CreditAdjustSuccessMessageEvent; import zack.project.types.enums.ResponseCode; import zack.project.types.event.BaseEvent; import zack.project.types.exception.AppException; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.TypeReference; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Slf4j @Component public class CreditAdjustSuccessCustomer { @Value("${spring.rabbitmq.topic.credit_adjust_success}") private String topic; @Resource private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService; /** * 监听CreditRepository.saveUserCreditTradeOrder发送的消息 * @param message */ @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.credit_adjust_success}")) public void listener(String message) { try { BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage>>() { }.getType()); //获取积分调额成功的消息内容 CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage creditAdjustSuccessMessage = eventMessage.getData(); //积分兑换sku消耗的积分扣减对该账户的积分账户的积分调整成功, // 需要将兑换抽奖次数或行为返利产生的充值单(对应数据库表{raffle_activity_order})的状态调整为completed // 并调整用户抽奖次数(对应数据库表{raffle_activity_account},{raffle_activity_account_day}, // {raffle_activity_account_month}) DeliveryOrderEntity deliveryOrderEntity = new DeliveryOrderEntity(); deliveryOrderEntity.setUserId(creditAdjustSuccessMessage.getUserId()); deliveryOrderEntity.setOutBusinessNo(creditAdjustSuccessMessage.getOutBusinessNo()); raffleActivityAccountQuotaService.updateOrder(deliveryOrderEntity); log.info("监听积分账户调整成功消息,交易商品发货完成 topic: {} message: {}", topic, message); } catch (AppException e) { if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) { log.warn("监听积分账户调整成功消息,进行交易商品发货,消费重复 topic: {} message: {}", topic, message, e); return; } throw e; } catch (Exception e) { log.error("监听积分账户调整成功消息,进行交易商品发货失败 topic: {} message: {}", topic, message, e); throw e; } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/listener/CreditAdjustSuccessCustomer.java
Java
unknown
3,176
package zack.project.trigger.listener; import zack.project.domain.activity.model.entity.SkuRechargeEntity; import zack.project.domain.activity.model.valobj.OrderTradeTypeVO; import zack.project.domain.activity.service.IRaffleActivityAccountQuotaService; import zack.project.domain.credit.model.entity.TradeEntity; import zack.project.domain.credit.model.valobj.TradeNameVO; import zack.project.domain.credit.model.valobj.TradeTypeVO; import zack.project.domain.credit.service.ICreditAdjustService; import zack.project.domain.rebate.event.SendRebateMessageEvent; import zack.project.types.enums.ResponseCode; import zack.project.types.event.BaseEvent; import zack.project.types.exception.AppException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.math.BigDecimal; /**返利消息消费者 * @author A1793 */ @Slf4j @Component public class RebateMessageCustomer { @Value("${spring.rabbitmq.topic.send_rebate}") private String topic; @Resource private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService; @Resource private ICreditAdjustService creditService; @RabbitListener(queuesToDeclare = @Queue("${spring.rabbitmq.topic.send_rebate}")) public void listener(String message) { try { BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> messageEventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage>>() { }.getType()); //获得返利消息内容 SendRebateMessageEvent.RebateMessage eventMessageData = messageEventMessage.getData(); //解析接收到的返利的返利消息,根据返利消息中配置的返利类型进行不同处理 switch (eventMessageData.getRebateType()) { //sku抽奖次数充值 // id behavior_type rebate_desc rebate_type rebate_config state // 1 sign 签到返利-sku额度 sku 9014 open 2024-04-30 09:32:46 2024-06-22 09:52:39 case "sku": { SkuRechargeEntity skuRechargeEntity = new SkuRechargeEntity(); //设置要充值的sku商品 //id sku activity_id activity_count_id total_count total_surplus_count pay_amount //1 9011 100301 11101 100000 99887 200.00 2024-03-16 11:41:09 2024-06-22 08:49:32 //2 9012 100301 11102 100000 99885 100.00 2024-03-16 11:41:09 2024-06-22 11:46:15 //3 9013 100301 11103 100000 99884 20.00 2024-03-16 11:41:09 2024-06-22 11:45:55 //4 9014 100301 11104 100000 99866 5.00 2024-03-16 11:41:09 2024-06-22 11:45:50 //四种sku商品有四种抽奖次数配置 skuRechargeEntity.setSku(Long.valueOf(eventMessageData.getRebateConfig())); skuRechargeEntity.setUserId(eventMessageData.getUserId()); skuRechargeEntity.setOutBusinessNo(eventMessageData.getBizId()); //将充值类型设置为不需要支付(数据库表{raffle_activity_order}存储的是对用户活动账户{raffle_activity_account}抽奖次数充值的记录) //当需要用积分兑换sku商品的时候,orderTradeType就是"credit_pay_trade"类型的 skuRechargeEntity.setOrderTradeTypeVO(OrderTradeTypeVO.rebate_no_pay_trade); //走活动账户调额服务 raffleActivityAccountQuotaService.createOrder(skuRechargeEntity); log.info("监听用户行为返利消息,sku返利成功 userId:{}", eventMessageData.getUserId()); } break; //积分充值 case "integral": { TradeEntity tradeEntity = new TradeEntity(); tradeEntity.setUserId(eventMessageData.getUserId()); tradeEntity.setOutBusinessNo(eventMessageData.getBizId()); tradeEntity.setTradeTypeVO(TradeTypeVO.FORWARD); tradeEntity.setTradeNameVO(TradeNameVO.REBATE); tradeEntity.setAmount(new BigDecimal(eventMessageData.getRebateConfig())); creditService.createOrder(tradeEntity); log.info("监听用户行为返利消息,积分返利成功 userId:{}", eventMessageData.getUserId()); } break; } } catch (AppException e) { //如果该行为已经有返利了则捕获唯一索引冲突(可能是因为该消息再别的应用被消费),不抛出错误不让mq重新投递消息或本地重试 if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) { log.warn("监听用户行为返利消息,消费重复 topic: {} message: {}", topic, message, e); return; } //如果是参数错误则捕获该错误不抛出异常,不让mq重新投递或在本地重试 else if(ResponseCode.ILLEGAL_PARAMETER.getCode().equals(e.getCode())) { log.warn("参数错误 topic: {} message: {}", topic, message, e); return; } throw e; } catch (Exception e) { log.error("监听用户行为返利消息,消费失败 topic: {} message: {}", topic, message, e); throw e; } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/listener/RebateMessageCustomer.java
Java
unknown
6,004
package zack.project.trigger.listener; import zack.project.domain.award.event.SendAwardMessageEvent; import zack.project.domain.award.model.entity.DistributeAwardEntity; import zack.project.domain.award.service.IAwardService; import zack.project.types.event.BaseEvent; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @author A1793 * 接收消息 */ @Slf4j @Component public class SendAwardCustomer { @Value("${spring.rabbitmq.topic.send_award}") private String topic; @Resource private IAwardService awardService; @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_award}")) public void listen(String message) { try { log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message); BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() { }.getType()); SendAwardMessageEvent.SendAwardMessage data = eventMessage.getData(); //构建发奖实体 DistributeAwardEntity distributeAwardEntity = new DistributeAwardEntity(); distributeAwardEntity.setAwardConfig(data.getAwardConfig()); distributeAwardEntity.setAwardId(data.getAwardId()); distributeAwardEntity.setUserId(data.getUserId()); distributeAwardEntity.setOrderId(data.getOrderId()); awardService.distributeAward(distributeAwardEntity); } catch (Exception e) { log.error("监听用户奖品发送消息,消费失败 topic: {} message: {}", topic, message); // throw e; } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/listener/SendAwardCustomer.java
Java
unknown
2,117
package zack.project.trigger.rpc; import zack.project.domain.award.service.IAwardService; import zack.project.domain.strategy.model.entity.RaffleAwardEntity; import zack.project.domain.strategy.model.entity.RaffleFactorEntity; import zack.project.domain.strategy.service.IRaffleStrategy; import zack.project.trigger.api.ILotteryService; import zack.project.trigger.api.dto.LotteryBaseRequestDTO; import zack.project.trigger.api.dto.LotteryResponseDTO; import zack.project.trigger.api.request.Request; import zack.project.trigger.api.response.Response; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.Service; import javax.annotation.Resource; /** * @author A1793 */ @Service(version = "1.0") public class LotteryService implements ILotteryService { @Resource IRaffleStrategy raffleStrategy; @Resource IAwardService awardService; @Override public Response<LotteryResponseDTO> lottery(Request<LotteryBaseRequestDTO> request) { try { if (request == null || StringUtils.isBlank(request.getAppToken()) || StringUtils.isBlank(request.getAppId()) || request.getData() == null ) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } LotteryBaseRequestDTO lotteryRequestDTO = request.getData(); if (lotteryRequestDTO.getStrategyId() == null) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder() .strategyId(lotteryRequestDTO.getStrategyId()) .userId("system") .build()); String awardConfig = awardService.queryAwardConfig(raffleAwardEntity.getAwardId()); return Response.<LotteryResponseDTO>builder() .code(ResponseCode.SUCCESS.getCode()) .info(ResponseCode.SUCCESS.getInfo()) .data(LotteryResponseDTO.builder() .awardResult(awardConfig) .build()) .build(); } catch (AppException e) { return Response.<LotteryResponseDTO>builder() .code(e.getCode()) .info(e.getInfo()) .data(null) .build(); } catch (Exception e) { return Response.<LotteryResponseDTO>builder().code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()).data(null).build(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/rpc/LotteryService.java
Java
unknown
2,935
package zack.project.trigger.rpc; import zack.project.domain.rebate.model.entity.BehaviorEntity; import zack.project.domain.rebate.model.valobj.BehaviorTypeVO; import zack.project.domain.rebate.service.IBehaviorRebateService; import zack.project.trigger.api.IRebateService; import zack.project.trigger.api.dto.RebateBehaviorDTO; import zack.project.trigger.api.request.Request; import zack.project.trigger.api.response.Response; import zack.project.types.enums.ResponseCode; import zack.project.types.exception.AppException; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.Service; import javax.annotation.Resource; import java.util.List; /** * 行为返利的rpc接口实现 * * @author A1793 */ @Slf4j @Service(version = "1.0") public class RebateServiceRpc implements IRebateService { @Resource IBehaviorRebateService rebateService; @Override public Response<Boolean> sendRebate(Request<RebateBehaviorDTO> request) { RebateBehaviorDTO rebateBehaviorDTO = request.getData(); log.info("返利操作开始 userId:{} request:{}", rebateBehaviorDTO.getUserId(), JSON.toJSONString(rebateBehaviorDTO)); try { if (StringUtils.isBlank(rebateBehaviorDTO.getUserId()) || StringUtils.isBlank(rebateBehaviorDTO.getBehaviorType()) || StringUtils.isBlank(rebateBehaviorDTO.getOutTradeNo()) || StringUtils.isBlank(request.getAppId()) || StringUtils.isBlank(request.getAppToken()) ) { throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo()); } BehaviorEntity behaviorEntity = new BehaviorEntity(); behaviorEntity.setUserId(rebateBehaviorDTO.getUserId()); behaviorEntity.setBehaviorTypeVO(BehaviorTypeVO.GROUP); behaviorEntity.setOutBusinessNo(rebateBehaviorDTO.getOutTradeNo()); List<String> orderIds = rebateService.createOrder(behaviorEntity); log.info("用户行为返利完成 userId: {} orderId: {}", rebateBehaviorDTO.getUserId(), orderIds); return Response.<Boolean>builder().code(ResponseCode.SUCCESS.getCode()).data(true).build(); } catch (AppException e) { return Response.<Boolean>builder() .code(e.getCode()) .info(e.getInfo()) .data(false) .build(); } catch (Exception e) { return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()) .info(ResponseCode.UN_ERROR.getInfo()).data(false).build(); } } }
2301_82000044/big-market-z
bigmarket-trigger/src/main/java/zack/project/trigger/rpc/RebateServiceRpc.java
Java
unknown
2,789
package zack.project.types.annotation; import java.lang.annotation.*; /** * @author A1793 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @Documented public @interface DCCValue { public String value() default ""; }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/annotation/DCCValue.java
Java
unknown
243
package zack.project.types.annotation; import java.lang.annotation.*; /** * @author A1793 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface RateLimiterAccessInterceptor { public String key() default "all"; public double permitsPerSecond(); public double blacklistCount() default 0; public String fallbackMethod(); }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/annotation/RateLimiterAccessInterceptor.java
Java
unknown
388
package zack.project.types.common; public class Constants { public final static String SPLIT = ","; public final static String COLON = ":"; public final static String SPACE = " "; public final static String UNDERLINE = "_"; public static final String RULE_TREE_VO ="rule_tree_vo_key_" ; public static class RedisKey { public static String ACTIVITY_ACCOUNT_LOCK = "activity_account_lock_" ; public static String ACTIVITY_KEY = "big_market_activity_key_"; public static String ACTIVITY_SKU_KEY = "big_market_activity_sku_key_"; public static String ACTIVITY_COUNT_KEY = "big_market_activity_count_key_"; public static String STRATEGY_KEY = "big_market_strategy_key_"; public static String STRATEGY_AWARD_KEY = "big_market_strategy_award_key_"; public static String STRATEGY_AWARD_LIST_KEY = "big_market_strategy_award_list_key_"; public static String STRATEGY_RATE_TABLE_KEY = "big_market_strategy_rate_table_key_"; public static String STRATEGY_RATE_RANGE_KEY = "big_market_strategy_rate_range_key_"; public static String STRATEGY_RULE_WEIGHT_KEY = "strategy_rule_weight_key_"; public static String RULE_TREE_VO_KEY = "rule_tree_vo_key_"; public static String STRATEGY_AWARD_COUNT_KEY = "strategy_award_count_key_"; public static String STRATEGY_AWARD_COUNT_QUERY_KEY = "strategy_award_count_query_key"; public static String ACTIVITY_SKU_COUNT_QUERY_KEY = "activity_sku_count_query_key"; public static String ACTIVITY_SKU_STOCK_COUNT_KEY = "activity_sku_stock_count_key_"; public static String ACTIVITY_ACCOUNT_UPDATE_LOCK = "activity_account_update_lock_"; public static String USER_CREDIT_ACCOUNT_LOCK = "user_credit_account_lock_"; } }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/common/Constants.java
Java
unknown
1,812
package zack.project.types.enums; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Getter public enum ResponseCode { SUCCESS("0000", "调用成功"), UN_ERROR("0001", "调用失败"), ILLEGAL_PARAMETER("0002", "非法参数"), INDEX_DUP("0003", "唯一索引冲突"), DEGRADE_SWITCH("0004", "活动已降级"), RATE_LIMITER("0005", "访问限流拦截"), HYSTRIX("0006", "访问熔断拦截"), STRATEGY_RULE_WEIGHT_IS_NULL("ERR_BIZ_001", "业务异常,策略规则中 rule_weight 权重规则已适用但未配置"), UN_ASSEMBLED_STRATEGY_ARMORY("ERR_BIZ_002", "抽奖策略配置未装配,请通过IStrategyArmory完成装配"), ACTIVITY_STATE_ERROR("ERR_BIZ_003", "活动未开启(非open状态)"), ACTIVITY_DATE_ERROR("ERR_BIZ_004", "非活动日期范围"), ACTIVITY_SKU_STOCK_ERROR("ERR_BIZ_005", "活动库存不足"), ACCOUNT_QUOTA_ERROR("ERR_BIZ_006", "账户总额度不足"), ACCOUNT_MONTH_QUOTA_ERROR("ERR_BIZ_007", "账户月额度不足"), ACCOUNT_DAY_QUOTA_ERROR("ERR_BIZ_008", "账户日额度不足"), ACTIVITY_ORDER_ERROR("ERR_BIZ_009", "该抽奖单已被使用,不可重复使用"), USER_CREDIT_ACCOUNT_NO_AVAILABLE_AMOUNT("ERR_CREDIT_001", "用户积分账户额度不足"), ; private String code; private String info; }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/enums/ResponseCode.java
Java
unknown
1,417
package zack.project.types.event; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author A1793 */ public abstract class BaseEvent<T> { public abstract String topic(); public abstract EventMessage<T> buildEventMessage(T data); @Data @Builder @AllArgsConstructor @NoArgsConstructor public static class EventMessage<T>{ private String id; private Date timestamp; private T data; } }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/event/BaseEvent.java
Java
unknown
536
package zack.project.types.exception; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data public class AppException extends RuntimeException { private static final long serialVersionUID = 5317680961212299217L; /** 异常码 */ private String code; /** 异常信息 */ private String info; public AppException(String code) { this.code = code; } public AppException(String code, Throwable cause) { this.code = code; super.initCause(cause); } public AppException(String code, String message) { this.code = code; this.info = message; super.initCause(new Throwable(message)); } public AppException(String code, String message, Throwable cause) { this.code = code; this.info = message; super.initCause(cause); } @Override public String toString() { return "exception.types.project.zack.AppException{" + "code='" + code + '\'' + ", info='" + info + '\'' + '}'; } }
2301_82000044/big-market-z
bigmarket-types/src/main/java/zack/project/types/exception/AppException.java
Java
unknown
1,108
CONTAINER_NAME=big-market IMAGE_NAME=fuzhengwei/big-market-app:1.0 PORT=8091 echo "容器部署开始 ${CONTAINER_NAME}" # 停止容器 docker stop ${CONTAINER_NAME} # 删除容器 docker rm ${CONTAINER_NAME} # 启动容器 docker run --name ${CONTAINER_NAME} \ -p ${PORT}:${PORT} \ -d ${IMAGE_NAME} echo "容器部署成功 ${CONTAINER_NAME}" docker logs -f ${CONTAINER_NAME}
2301_82000044/big-market-z
docs/dev-ops/start.sh
Shell
unknown
382
docker stop big-market-app
2301_82000044/big-market-z
docs/dev-ops/stop.sh
Shell
unknown
26
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "ComfyUI"), [string]$PyTorchMirrorType, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithUpdateNode, [switch]$BuildWithLaunch, [int]$BuildWithTorch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [switch]$NoPreDownloadNode, [switch]$NoPreDownloadModel, [string]$PyTorchPackage, [string]$xFormersPackage, [switch]$InstallHanamizuki, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [switch]$UseCustomHuggingFaceMirror, [string]$LaunchArg, [switch]$EnableShortcut, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("core", "ComfyUI", "comfyui", "ComfyUI-aki-v1.0", "ComfyUI-aki-v1.1", "ComfyUI-aki-v1.2", "ComfyUI-aki-v1.3", "ComfyUI-aki-v1.4", "ComfyUI-aki-v1.5", "ComfyUI-aki-v1.6", "ComfyUI-aki-v1.7", "ComfyUI-aki-v2") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "core" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # ComfyUI Installer 版本和检查更新间隔 $COMFYUI_INSTALLER_VERSION = 286 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_ADDR } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_FIND_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121/torch_stable.html" $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # Github 镜像源列表 $GITHUB_MIRROR_LIST = @( "https://ghfast.top/https://github.com", "https://mirror.ghproxy.com/https://github.com", "https://ghproxy.net/https://github.com", "https://gh.api.99988866.xyz/https://github.com", "https://gh-proxy.com/https://github.com", "https://ghps.cc/https://github.com", "https://gh.idayer.com/https://github.com", "https://ghproxy.1888866.xyz/github.com", "https://slink.ltd/https://github.com", "https://github.boki.moe/github.com", "https://github.moeyy.xyz/https://github.com", "https://gh-proxy.net/https://github.com", "https://gh-proxy.ygxz.in/https://github.com", "https://wget.la/https://github.com", "https://kkgithub.com", "https://gitclone.com/github.com" ) # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # ComfyUI 仓库地址 $COMFYUI_REPO = "https://github.com/comfyanonymous/ComfyUI" # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $PYTHON_SCRIPTS_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $GIT_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/git/bin" $Env:PATH = "$PYTHON_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_EXTRA_PATH$([System.IO.Path]::PathSeparator)$GIT_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" $Env:COMFYUI_PATH = "$InstallPath/$Env:CORE_PREFIX" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[ComfyUI Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { $ver = $([string]$COMFYUI_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "ComfyUI Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # Github 镜像测试 function Set-Github-Mirror { $Env:GIT_CONFIG_GLOBAL = "$InstallPath/.gitconfig" # 设置 Git 配置文件路径 if (Test-Path "$InstallPath/.gitconfig") { Remove-Item -Path "$InstallPath/.gitconfig" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory "*" git config --global core.longpaths true if ((Test-Path "$PSScriptRoot/disable_gh_mirror.txt") -or ($DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg "检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源" return } # 使用自定义 Github 镜像源 if ((Test-Path "$PSScriptRoot/gh_mirror.txt") -or ($UseCustomGithubMirror)) { if ($UseCustomGithubMirror) { $github_mirror = $UseCustomGithubMirror } else { $github_mirror = Get-Content "$PSScriptRoot/gh_mirror.txt" } git config --global url."$github_mirror".insteadOf "https://github.com" Print-Msg "检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源" return } # 自动检测可用镜像源并使用 $status = 0 ForEach($i in $GITHUB_MIRROR_LIST) { Print-Msg "测试 Github 镜像源: $i" if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } git clone "$i/licyk/empty" "$Env:CACHE_HOME/github-mirror-test" --quiet if ($?) { Print-Msg "该 Github 镜像源可用" $github_mirror = $i $status = 1 break } else { Print-Msg "镜像源不可用, 更换镜像源进行测试" } } if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } if ($status -eq 0) { Print-Msg "无可用 Github 镜像源, 取消使用 Github 镜像源" } else { Print-Msg "设置 Github 镜像源" git config --global url."$github_mirror".insteadOf "https://github.com" } } # Git 仓库下载 function Git-CLone { param ( [String]$url, [String]$path ) $name = [System.IO.Path]::GetFileNameWithoutExtension("$url") $folder_name = [System.IO.Path]::GetFileName("$path") Print-Msg "检测 $name 是否已安装" $status = 0 if (!(Test-Path "$path")) { $status = 1 } else { $items = Get-ChildItem "$path" if ($items.Count -eq 0) { $status = 1 } } if ($status -eq 1) { Print-Msg "正在下载 $name" $cache_path = "$Env:CACHE_HOME/${folder_name}_tmp" # 清理缓存路径 if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } git clone --recurse-submodules $url "$cache_path" if ($?) { # 检测是否下载成功 # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Print-Msg "$name 安装成功" } else { Print-Msg "$name 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "$name 已安装" } } # 设置 PyTorch 镜像源 function Get-PyTorch-Mirror ($pytorch_package) { # 获取 PyTorch 的版本 $torch_part = @($pytorch_package -split ' ' | Where-Object { $_ -like "torch==*" })[0] if ($PyTorchMirrorType) { Print-Msg "使用指定的 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } elseif ($torch_part) { # 获取 PyTorch 镜像源类型 if ($torch_part.split("+") -eq $torch_part) { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' if __name__ == '__main__': print(get_pytorch_mirror_type('$torch_part', use_xpu=True)) ".Trim() $mirror_type = $(python -c "$content") } else { $mirror_type = $torch_part.Split("+")[-1] } Print-Msg "PyTorch 镜像源类型: $mirror_type" } else { Print-Msg "未获取到 PyTorch 版本, 无法确定镜像源类型, 可能导致 PyTorch 安装失败" $mirror_type = "null" } # 设置对应的镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 为 PyTorch 获取合适的 CUDA 版本类型 function Get-Appropriate-CUDA-Version-Type { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def select_avaliable_type() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() if compare_versions(cuda_support_ver, '13.0') >= 0: return 'cu130' elif compare_versions(cuda_support_ver, '12.9') >= 0: return 'cu129' elif compare_versions(cuda_support_ver, '12.8') >= 0: return 'cu128' elif compare_versions(cuda_support_ver, '12.6') >= 0: return 'cu126' elif compare_versions(cuda_support_ver, '12.4') >= 0: return 'cu124' elif compare_versions(cuda_support_ver, '12.1') >= 0: return 'cu121' elif compare_versions(cuda_support_ver, '11.8') >= 0: return 'cu118' elif compare_versions(cuda_comp_cap, '10.0') > 0: return 'cu128' # RTX 50xx elif compare_versions(cuda_comp_cap, '0.0') > 0: return 'cu118' # 其他 Nvidia 显卡 else: gpus = get_gpu_list() if any([ x for x in gpus if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): return 'xpu' if any([ x for x in gpus if 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): return 'cu118' return 'cpu' if __name__ == '__main__': print(select_avaliable_type()) ".Trim() return $(python -c "$content") } # 获取合适的 PyTorch / xFormers 版本 function Get-PyTorch-And-xFormers-Package { Print-Msg "设置 PyTorch 和 xFormers 版本" if ($PyTorchPackage) { # 使用自定义的 PyTorch / xFormers 版本 if ($xFormersPackage){ return $PyTorchPackage, $xFormersPackage } else { return $PyTorchPackage, $null } } if ($PyTorchMirrorType) { Print-Msg "根据 $PyTorchMirrorType 类型的 PyTorch 镜像源配置 PyTorch 组合" $appropriate_cuda_version = $PyTorchMirrorType } else { $appropriate_cuda_version = Get-Appropriate-CUDA-Version-Type } switch ($appropriate_cuda_version) { cu130 { $pytorch_package = "torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130" $xformers_package = "xformers==0.0.33" break } cu129 { $pytorch_package = "torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129" $xformers_package = "xformers==0.0.32.post2" break } cu128 { $pytorch_package = "torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128" $xformers_package = "xformers==0.0.33" break } cu126 { $pytorch_package = "torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126" $xformers_package = "xformers==0.0.33" break } cu124 { $pytorch_package = "torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124" $xformers_package = "xformers==0.0.29.post3" break } cu121 { $pytorch_package = "torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121" $xformers_package = "xformers===0.0.27" break } cu118 { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } xpu { $pytorch_package = "torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu" $xformers_package = $null break } cpu { $pytorch_package = "torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu" $xformers_package = $null break } Default { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } } return $pytorch_package, $xformers_package } # 安装 PyTorch function Install-PyTorch { $pytorch_package, $xformers_package = Get-PyTorch-And-xFormers-Package $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror $pytorch_package # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch: $pytorch_package" Print-Msg "将要安装的 xFormers: $xformers_package" Print-Msg "检测是否需要安装 PyTorch" python -m pip show torch --quiet 2> $null if (!($?)) { Print-Msg "安装 PyTorch 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() } } else { python -m pip install $pytorch_package.ToString().Split() } if ($?) { Print-Msg "PyTorch 安装成功" } else { Print-Msg "PyTorch 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch 已安装, 无需再次安装" } Print-Msg "检测是否需要安装 xFormers" python -m pip show xformers --quiet 2> $null if (!($?)) { if ($xformers_package) { Print-Msg "安装 xFormers 中" if ($USE_UV) { uv pip install $xformers_package.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $xformers_package.ToString().Split() --no-deps } } else { python -m pip install $xformers_package.ToString().Split() --no-deps } if ($?) { Print-Msg "xFormers 安装成功" } else { Print-Msg "xFormers 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg "xFormers 已安装, 无需再次安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 ComfyUI 依赖 function Install-ComfyUI-Dependence { # 记录脚本所在路径 $current_path = $(Get-Location).ToString() Set-Location "$InstallPath/$Env:CORE_PREFIX" Print-Msg "安装 ComfyUI 依赖中" if ($USE_UV) { uv pip install -r requirements.txt if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install -r requirements.txt } } else { python -m pip install -r requirements.txt } if ($?) { Print-Msg "ComfyUI 依赖安装成功" } else { Print-Msg "ComfyUI 依赖安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } Set-Location "$current_path" } # 安装 function Check-Install { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null Print-Msg "检测是否安装 Python" if ((Test-Path "$InstallPath/python/python.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } # 切换 uv 指定的 Python if (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe") { $Env:UV_PYTHON = "$InstallPath/$Env:CORE_PREFIX/python/python.exe" } Print-Msg "检测是否安装 Git" if ((Test-Path "$InstallPath/git/bin/git.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if ((Test-Path "$InstallPath/git/bin/aria2c.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/aria2c.exe")) { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Set-Github-Mirror $comfyui_path = "$InstallPath/$Env:CORE_PREFIX" $custom_node_path = "$comfyui_path/custom_nodes" Git-CLone "$COMFYUI_REPO" "$comfyui_path" if ($NoPreDownloadNode) { Print-Msg "检测到 -NoPreDownloadNode 命令行参数, 跳过安装 ComfyUI 扩展" } else { # ComfyUI 扩展 Git-CLone "https://github.com/Comfy-Org/ComfyUI-Manager" "$custom_node_path/ComfyUI-Manager" Git-CLone "https://github.com/Fannovel16/comfyui_controlnet_aux" "$custom_node_path/comfyui_controlnet_aux" Git-CLone "https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet" "$custom_node_path/ComfyUI-Advanced-ControlNet" Git-CLone "https://github.com/cubiq/ComfyUI_IPAdapter_plus" "$custom_node_path/ComfyUI_IPAdapter_plus" Git-CLone "https://github.com/kijai/ComfyUI-Marigold" "$custom_node_path/ComfyUI-Marigold" Git-CLone "https://github.com/pythongosssss/ComfyUI-WD14-Tagger" "$custom_node_path/ComfyUI-WD14-Tagger" Git-CLone "https://github.com/BlenderNeko/ComfyUI_TiledKSampler" "$custom_node_path/ComfyUI_TiledKSampler" Git-CLone "https://github.com/pythongosssss/ComfyUI-Custom-Scripts" "$custom_node_path/ComfyUI-Custom-Scripts" Git-CLone "https://github.com/LEv145/images-grid-comfy-plugin" "$custom_node_path/images-grid-comfy-plugin" Git-CLone "https://github.com/ssitu/ComfyUI_UltimateSDUpscale" "$custom_node_path/ComfyUI_UltimateSDUpscale" Git-CLone "https://github.com/AlekPet/ComfyUI_Custom_Nodes_AlekPet" "$custom_node_path/ComfyUI_Custom_Nodes_AlekPet" Git-CLone "https://github.com/talesofai/comfyui-browser" "$custom_node_path/comfyui-browser" Git-CLone "https://github.com/ltdrdata/ComfyUI-Inspire-Pack" "$custom_node_path/ComfyUI-Inspire-Pack" Git-CLone "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes" "$custom_node_path/ComfyUI_Comfyroll_CustomNodes" Git-CLone "https://github.com/crystian/ComfyUI-Crystools" "$custom_node_path/ComfyUI-Crystools" Git-CLone "https://github.com/shiimizu/ComfyUI-TiledDiffusion" "$custom_node_path/ComfyUI-TiledDiffusion" Git-CLone "https://github.com/huchenlei/ComfyUI-openpose-editor" "$custom_node_path/ComfyUI-openpose-editor" Git-CLone "https://github.com/licyk/ComfyUI-Restart-Sampler" "$custom_node_path/ComfyUI-Restart-Sampler" Git-CLone "https://github.com/weilin9999/WeiLin-ComfyUI-prompt-all-in-one" "$custom_node_path/WeiLin-ComfyUI-prompt-all-in-one" Git-CLone "https://github.com/licyk/ComfyUI-HakuImg" "$custom_node_path/ComfyUI-HakuImg" Git-CLone "https://github.com/yolain/ComfyUI-Easy-Use" "$custom_node_path/ComfyUI-Easy-Use" Git-CLone "https://github.com/rgthree/rgthree-comfy" "$custom_node_path/rgthree-comfy" } Install-PyTorch Install-ComfyUI-Dependence if (!(Test-Path "$InstallPath/launch_args.txt")) { Print-Msg "设置默认 ComfyUI 启动参数" $content = "--auto-launch --preview-method auto --disable-cuda-malloc" Set-Content -Encoding UTF8 -Path "$InstallPath/launch_args.txt" -Value $content } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/user/default/comfy.settings.json")) { Print-Msg "设置默认 ComfyUI 设置" $json_content = @{ "Comfy.Settings.ExtensionPanel" = $true "DZ.Debug.enabled" = $true "Comfy.UseNewMenu" = "Top" "Comfy.Locale" = "zh" "Comfy.RerouteBeta" = $true } $json_content = $json_content | ConvertTo-Json -Depth 4 New-Item -ItemType Directory -Path "$InstallPath/$Env:CORE_PREFIX/user/default" -Force > $null # 创建一个不带 BOM 的 UTF-8 编码器 $utf8_encoding = New-Object System.Text.UTF8Encoding($false) # 使用 StreamWriter 来写入文件 $stream_writer = [System.IO.StreamWriter]::new("$InstallPath/$Env:CORE_PREFIX/user/default/comfy.settings.json", $false, $utf8_encoding) $stream_writer.Write($json_content) $stream_writer.Close() } if ($NoPreDownloadModel) { Print-Msg "检测到 -NoPreDownloadModel 命令行参数, 跳过下载模型" } else { $checkpoint_path = "$InstallPath/$Env:CORE_PREFIX/models/checkpoints" $url = "https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors" $name = Split-Path -Path $url -Leaf if ((!(Get-ChildItem -Path $checkpoint_path -Include "*.safetensors", "*.pth", "*.ckpt" -Recurse)) -or (Test-Path "$checkpoint_path/${name}.aria2")) { Print-Msg "预下载模型中" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M $url -d "$checkpoint_path" -o "$name" if ($?) { Print-Msg "下载 $name 模型成功" } else { Print-Msg "下载 $name 模型失败" } } } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 启动脚本 function Write-Launch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [switch]`$UseCustomHuggingFaceMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableUV, [string]`$LaunchArg, [switch]`$EnableShortcut, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableUV] [-LaunchArg <ComfyUI 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 ComfyUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 ComfyUI Installer 更新检查 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableGithubMirror 禁用 ComfyUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableUV 禁用 ComfyUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -LaunchArg <ComfyUI 启动参数> 设置 ComfyUI 自定义启动参数, 如启用 --fast 和 --auto-launch, 则使用 -LaunchArg ```"--fast --auto-launch```" 进行启用 -EnableShortcut 创建 ComfyUI 启动快捷方式 -DisableCUDAMalloc 禁用 ComfyUI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 ComfyUI Installer 检查 ComfyUI 运行环境中存在的问题, 禁用后可能会导致 ComfyUI 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # ComfyUI Installer 更新检测 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 ComfyUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -le `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 ComfyUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 ComfyUI Installer 更新`" return } } else { Print-Msg `"检测到 ComfyUI Installer 有新版本可用`" } Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # ComfyUI 启动参数 function Get-ComfyUI-Launch-Args { `$arguments = New-Object System.Collections.ArrayList if ((Test-Path `"`$PSScriptRoot/launch_args.txt`") -or (`$LaunchArg)) { if (`$LaunchArg) { `$launch_args = `$LaunchArg } else { `$launch_args = Get-Content `"`$PSScriptRoot/launch_args.txt`" } if (`$launch_args.Trim().Split().Length -le 1) { `$arguments = `$launch_args.Trim().Split() } else { `$arguments = [regex]::Matches(`$launch_args, '(`"[^`"]*`"|''[^'']*''|\S+)') | ForEach-Object { `$_.Value -replace '^[`"'']|[`"'']`$', '' } } Print-Msg `"检测到本地存在 launch_args.txt 启动参数配置文件 / -LaunchArg 命令行参数, 已读取该启动参数配置文件并应用启动参数`" Print-Msg `"使用的启动参数: `$arguments`" } return `$arguments } # 设置 ComfyUI 的快捷启动方式 function Create-ComfyUI-Shortcut { `$filename = `"ComfyUI`" `$url = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/comfyui_icon.ico`" `$shortcut_icon = `"`$PSScriptRoot/comfyui_icon.ico`" if ((!(Test-Path `"`$PSScriptRoot/enable_shortcut.txt`")) -and (!(`$EnableShortcut))) { return } Print-Msg `"检测到 enable_shortcut.txt 配置文件 / -EnableShortcut 命令行参数, 开始检查 ComfyUI 快捷启动方式中`" if (!(Test-Path `"`$shortcut_icon`")) { Print-Msg `"获取 ComfyUI 图标中`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/comfyui_icon.ico`" if (!(`$?)) { Print-Msg `"获取 ComfyUI 图标失败, 无法创建 ComfyUI 快捷启动方式`" return } } Print-Msg `"更新 ComfyUI 快捷启动方式`" `$shell = New-Object -ComObject WScript.Shell `$desktop = [System.Environment]::GetFolderPath(`"Desktop`") `$shortcut_path = `"`$desktop\`$filename.lnk`" `$shortcut = `$shell.CreateShortcut(`$shortcut_path) `$shortcut.TargetPath = `"`$PSHome\powershell.exe`" `$launch_script_path = `$(Get-Item `"`$PSScriptRoot/launch.ps1`").FullName `$shortcut.Arguments = `"-ExecutionPolicy Bypass -File ```"`$launch_script_path```"`" `$shortcut.IconLocation = `$shortcut_icon # 保存到桌面 `$shortcut.Save() `$start_menu_path = `"`$Env:APPDATA/Microsoft/Windows/Start Menu/Programs`" `$taskbar_path = `"`$Env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar`" # 保存到开始菜单 Copy-Item -Path `"`$shortcut_path`" -Destination `"`$start_menu_path`" -Force # 固定到任务栏 # Copy-Item -Path `"`$shortcut_path`" -Destination `"`$taskbar_path`" -Force # `$shell = New-Object -ComObject Shell.Application # `$shell.Namespace([System.IO.Path]::GetFullPath(`$taskbar_path)).ParseName((Get-Item `$shortcut_path).Name).InvokeVerb('taskbarpin') } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 检查 ComfyUI 依赖完整性 function Check-ComfyUI-Requirements { `$content = `" import inspect import platform import re import os import sys import copy import logging import argparse import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--requirement-path```", type=_normalized_filepath, default=None, help=```"依赖文件路径```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"Requirement Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True def validate_requirements(requirement_path: str | Path) -> bool: ```"```"```"检测环境依赖是否完整 Args: requirement_path (str | Path): 依赖文件路径 Returns: bool: 如果有缺失依赖则返回````False```` ```"```"```" origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) for package in requires: if not is_package_installed(package): return False return True def main() -> None: requirement_path = COMMAND_ARGS.requirement_path if not os.path.isfile(requirement_path): logger.error(```"依赖文件未找到, 无法检查运行环境```") sys.exit(1) logger.debug(```"检测运行环境中```") print(validate_requirements(requirement_path)) logger.debug(```"环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 ComfyUI 内核依赖完整性中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_comfyui_requirement.py`" -Value `$content `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements_versions.txt`" if (!(Test-Path `"`$dep_path`")) { `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements.txt`" } if (!(Test-Path `"`$dep_path`")) { Print-Msg `"未检测到 ComfyUI 依赖文件, 跳过依赖完整性检查`" return } `$status = `$(python `"`$Env:CACHE_HOME/check_comfyui_requirement.py`" --requirement-path `"`$dep_path`") if (`$status -eq `"False`") { Print-Msg `"检测到 ComfyUI 内核有依赖缺失, 安装 ComfyUI 依赖中`" if (`$USE_UV) { uv pip install -r `"`$dep_path`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$dep_path`" } } else { python -m pip install -r `"`$dep_path`" } if (`$?) { Print-Msg `"ComfyUI 依赖安装成功`" } else { Print-Msg `"ComfyUI 依赖安装失败, 这将会导致 ComfyUI 缺失依赖无法正常运行`" } } else { Print-Msg `"ComfyUI 无缺失依赖`" } } # 检查 ComfyUI 环境中组件依赖 function Check-ComfyUI-Env-Requirements { `$content = `" import argparse import platform import sys import os import re import copy import inspect import logging import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple, TypedDict def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"ComfyUI 运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--comfyui-path```", type=_normalized_filepath, default=None, help=```"ComfyUI 路径```" ) parser.add_argument( ```"--conflict-depend-notice-path```", type=_normalized_filepath, default=None, help=```"保存 ComfyUI 扩展依赖冲突信息的文件路径```", ) parser.add_argument( ```"--requirement-list-path```", type=_normalized_filepath, default=None, help=```"保存 ComfyUI 需要安装扩展依赖的路径列表```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"ComfyUI Env Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) def remove_duplicate_object_from_list(origin: list[Any]) -> list[Any]: ```"```"```"对````list````进行去重 例如: [1, 2, 3, 2] -> [1, 2, 3] Args: origin (list[Any]): 原始的````list```` Returns: list[Any]: 去重后的````list```` ```"```"```" return list(set(origin)) def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] class ComponentEnvironmentDetails(TypedDict): ```"```"```"ComfyUI 组件的环境信息结构 Attributes: requirement_path (str): 依赖文件路径 is_disabled (bool): 组件是否禁用 requires (list[str]): 需要的依赖列表 has_missing_requires (bool): 是否存在缺失依赖 missing_requires (list[str]): 具体缺失的依赖项 has_conflict_requires (bool): 是否存在冲突依赖 conflict_requires (list[str]): 具体冲突的依赖项 ```"```"```" requirement_path: str ```"```"```"依赖文件路径```"```"```" is_disabled: bool ```"```"```"组件是否禁用```"```"```" requires: list[str] ```"```"```"需要的依赖列表```"```"```" has_missing_requires: bool ```"```"```"是否存在缺失依赖```"```"```" missing_requires: list[str] ```"```"```"具体缺失的依赖项```"```"```" has_conflict_requires: bool ```"```"```"是否存在冲突依赖```"```"```" conflict_requires: list[str] ```"```"```"具体冲突的依赖项```"```"```" ComfyUIEnvironmentComponent = dict[str, ComponentEnvironmentDetails] ```"```"```"ComfyUI 环境组件表字典```"```"```" def create_comfyui_environment_dict( comfyui_path: str | Path, ) -> ComfyUIEnvironmentComponent: ```"```"```"创建 ComfyUI 环境组件表字典 Args: comfyui_path (str | Path): ComfyUI 根路径 Returns: ComfyUIEnvironmentComponent: ComfyUI 环境组件表字典 ```"```"```" comfyui_path = ( Path(comfyui_path) if not isinstance(comfyui_path, Path) and comfyui_path is not None else comfyui_path ) comfyui_env_data: ComfyUIEnvironmentComponent = { ```"ComfyUI```": { ```"requirement_path```": (comfyui_path / ```"requirements.txt```").as_posix(), ```"is_disabled```": False, ```"requires```": [], ```"has_missing_requires```": False, ```"missing_requires```": [], ```"has_conflict_requires```": False, ```"conflict_requires```": [], }, } custom_nodes_path = comfyui_path / ```"custom_nodes```" for custom_node in custom_nodes_path.iterdir(): if custom_node.is_file(): continue custom_node_requirement_path = custom_node / ```"requirements.txt```" custom_node_is_disabled = ( True if custom_node.parent.as_posix().endswith(```".disabled```") else False ) comfyui_env_data[custom_node.name] = { ```"requirement_path```": ( custom_node_requirement_path.as_posix() if custom_node_requirement_path.exists() else None ), ```"is_disabled```": custom_node_is_disabled, ```"requires```": [], ```"has_missing_requires```": False, ```"missing_requires```": [], ```"has_conflict_requires```": False, ```"conflict_requires```": [], } return comfyui_env_data def update_comfyui_environment_dict( env_data: ComfyUIEnvironmentComponent, component_name: str, requirement_path: str | None = None, is_disabled: bool | None = None, requires: list[str] | None = None, has_missing_requires: bool | None = None, missing_requires: list[str] | None = None, has_conflict_requires: bool | None = None, conflict_requires: list[str] | None = None, ) -> None: ```"```"```"更新 ComfyUI 环境组件表字典 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 component_name (str): ComfyUI 组件名称 requirement_path (str | None): ComfyUI 组件依赖文件路径 is_disabled (bool | None): ComfyUI 组件是否被禁用 requires (list[str] | None): ComfyUI 组件需要的依赖列表 has_missing_requires (bool | None): ComfyUI 组件是否存在缺失依赖 missing_requires (list[str] | None): ComfyUI 组件缺失依赖列表 has_conflict_requires (bool | None): ComfyUI 组件是否存在冲突依赖 conflict_requires (list[str] | None): ComfyUI 组件冲突依赖列表 ```"```"```" env_data[component_name] = { ```"requirement_path```": ( requirement_path if requirement_path else env_data.get(component_name).get(```"requirement_path```") ), ```"is_disabled```": ( is_disabled if is_disabled else env_data.get(component_name).get(```"is_disabled```") ), ```"requires```": ( requires if requires else env_data.get(component_name).get(```"requires```") ), ```"has_missing_requires```": ( has_missing_requires if has_missing_requires else env_data.get(component_name).get(```"has_missing_requires```") ), ```"missing_requires```": ( missing_requires if missing_requires else env_data.get(component_name).get(```"missing_requires```") ), ```"has_conflict_requires```": ( has_conflict_requires if has_conflict_requires else env_data.get(component_name).get(```"has_conflict_requires```") ), ```"conflict_requires```": ( conflict_requires if conflict_requires else env_data.get(component_name).get(```"conflict_requires```") ), } def update_comfyui_component_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> None: ```"```"```"更新 ComfyUI 环境组件表字典, 根据字典中的 requirement_path 确定 Python 软件包版本声明文件, 并解析后写入 requires 字段 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 ```"```"```" for component_name, details in env_data.items(): if details.get(```"is_disabled```"): continue requirement_path = details.get(```"requirement_path```") if requirement_path is None: continue origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, requires=requires, ) def update_comfyui_component_missing_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> None: ```"```"```"更新 ComfyUI 环境组件表字典, 根据字典中的 requires 检查缺失的 Python 软件包, 并保存到 missing_requires 字段和设置 has_missing_requires 状态 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 ```"```"```" for component_name, details in env_data.items(): if details.get(```"is_disabled```"): continue requires = details.get(```"requires```") has_missing_requires = False missing_requires = [] for package in requires: if not is_package_installed(package): has_missing_requires = True missing_requires.append(package) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, has_missing_requires=has_missing_requires, missing_requires=missing_requires, ) def update_comfyui_component_conflict_requires_list( env_data: ComfyUIEnvironmentComponent, conflict_package_list: list[str] ) -> None: ```"```"```"更新 ComfyUI 环境组件表字典, 根据 conflicconflict_package_listt_package 检查 ComfyUI 组件冲突的 Python 软件包, 并保存到 conflict_requires 字段和设置 has_conflict_requires 状态 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 conflict_package_list (list[str]): 冲突的 Python 软件包列表 ```"```"```" for component_name, details in env_data.items(): if details.get(```"is_disabled```"): continue requires = details.get(```"requires```") has_conflict_requires = False conflict_requires: list[str] = [] for conflict_package in conflict_package_list: for package in requires: if is_package_has_version(package) and get_package_name( conflict_package ) == get_package_name(package): has_conflict_requires = True conflict_requires.append(package) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, has_conflict_requires=has_conflict_requires, conflict_requires=conflict_requires, ) def get_comfyui_component_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> list[str]: ```"```"```"从 ComfyUI 环境组件表字典读取所有组件的 requires Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: list[str]: ComfyUI 环境组件的 Python 软件包列表 ```"```"```" package_list = [] for _, details in env_data.items(): if details.get(```"is_disabled```"): continue package_list += details.get(```"requires```") return remove_duplicate_object_from_list(package_list) def statistical_need_install_require_component( env_data: ComfyUIEnvironmentComponent, ) -> list[str]: ```"```"```"根据 ComfyUI 环境组件表字典中的 has_missing_requires 和 has_conflict_requires 字段确认需要安装依赖的列表 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: list[str]: ComfyUI 环境组件的依赖文件路径列表 ```"```"```" requirement_list = [] for _, details in env_data.items(): if details.get(```"has_missing_requires```") or details.get(```"has_conflict_requires```"): requirement_list.append(Path(details.get(```"requirement_path```")).as_posix()) return requirement_list def statistical_has_conflict_component( env_data: ComfyUIEnvironmentComponent, conflict_package_list: list[str] ) -> str: ```"```"```"根据 ComfyUI 环境组件表字典中的 conflict_requires 字段统计冲突的组件信息 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: str: ComfyUI 环境冲突的组件信息列表 ```"```"```" content = [] # 统一成下划线 conflict_package_list = remove_duplicate_object_from_list( [x.replace(```"-```", ```"_```") for x in conflict_package_list] ) for conflict_package in conflict_package_list: content.append(get_package_name(f```"{conflict_package}:```")) for component_name, details in env_data.items(): for conflict_component_package in details.get(```"conflict_requires```"): # 将中划线统一成下划线再对比 conflict_component_package_format = get_package_name( conflict_component_package ).replace(```"-```", ```"_```") conflict_package_format = conflict_package.replace(```"-```", ```"_```") if conflict_component_package_format == conflict_package_format: content.append(f```" - {component_name}: {conflict_component_package}```") content.append(```"```") return ```"\n```".join( [ str(x) for x in ( content[:-1] if len(content) > 0 and content[-1] == ```"```" else content ) ] ) def fitter_has_version_package(package_list: list[str]) -> list[str]: ```"```"```"过滤不包含版本的 Python 软件包, 仅保留包含版本号声明的 Python 软件包 Args: package_list (list[str]): Python 软件包列表 Returns: list[str]: 仅包含版本号的 Python 软件包列表 ```"```"```" return [p for p in package_list if is_package_has_version(p)] def detect_conflict_package(pkg1: str, pkg2: str) -> bool: ```"```"```"检测 Python 软件包版本号声明是否存在冲突 Args: pkg1 (str): 第 1 个 Python 软件包名称 pkg2 (str): 第 2 个 Python 软件包名称 Returns: bool: 如果 Python 软件包版本声明出现冲突则返回````True```` ```"```"```" # 进行 2 次循环, 第 2 次循环时交换版本后再进行判断 for i in range(2): if i == 1: if pkg1 == pkg2: break else: pkg1, pkg2 = pkg2, pkg1 ver1 = get_package_version(pkg1) ver2 = get_package_version(pkg2) logger.debug( ```"冲突依赖检测: pkg1: %s, pkg2: %s, ver1: %s, ver2: %s```", pkg1, pkg2, ver1, ver2, ) # >=, <= if ```">=```" in pkg1 and ```"<=```" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s > %s```", pkg1, pkg2, ver1, ver2 ) return True # >=, < if ```">=```" in pkg1 and ```"<```" in pkg2 and ```"=```" not in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s >= %s```", pkg1, pkg2, ver1, ver2 ) return True # >, <= if ```">```" in pkg1 and ```"=```" not in pkg1 and ```"<=```" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s >= %s```", pkg1, pkg2, ver1, ver2 ) return True # >, < if ```">```" in pkg1 and ```"=```" not in pkg1 and ```"<```" in pkg2 and ```"=```" not in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s >= %s```", pkg1, pkg2, ver1, ver2 ) return True # >, == if ```">```" in pkg1 and ```"=```" not in pkg1 and ```"==```" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s >= %s```", pkg1, pkg2, ver1, ver2 ) return True # >=, == if ```">=```" in pkg1 and ```"==```" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s > %s```", pkg1, pkg2, ver1, ver2 ) return True # <, == if ```"<```" in pkg1 and ```"=```" not in pkg1 and ```"==```" in pkg2: if PyWhlVersionComparison(ver1) <= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s <= %s```", pkg1, pkg2, ver1, ver2 ) return True # <=, == if ```"<=```" in pkg1 and ```"==```" in pkg2: if PyWhlVersionComparison(ver1) < PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s < %s```", pkg1, pkg2, ver1, ver2 ) return True # !=, == if ```"!=```" in pkg1 and ```"==```" in pkg2: if PyWhlVersionComparison(ver1) == PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s == %s```", pkg1, pkg2, ver1, ver2 ) return True # >, ~= if ```">```" in pkg1 and ```"=```" not in pkg1 and ```"~=```" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s >= %s```", pkg1, pkg2, ver1, ver2 ) return True # >=, ~= if ```">=```" in pkg1 and ```"~=```" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s > %s```", pkg1, pkg2, ver1, ver2 ) return True # <, ~= if ```"<```" in pkg1 and ```"=```" not in pkg1 and ```"~=```" in pkg2: if PyWhlVersionComparison(ver1) <= PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s <= %s```", pkg1, pkg2, ver1, ver2 ) return True # <=, ~= if ```"<=```" in pkg1 and ```"~=```" in pkg2: if PyWhlVersionComparison(ver1) < PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s < %s```", pkg1, pkg2, ver1, ver2 ) return True # !=, ~= # 这个也没什么必要 # if '!=' in pkg1 and '~=' in pkg2: # if is_v1_c_eq_v2(ver1, ver2): # logger.debug( # '冲突依赖: %s, %s, 版本冲突: %s ~= %s', # pkg1, pkg2, ver1, ver2) # return True # ~=, == / ~=, === if (```"~=```" in pkg1 and ```"==```" in pkg2) or (```"~=```" in pkg1 and ```"===```" in pkg2): if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s > %s```", pkg1, pkg2, ver1, ver2 ) return True # ~=, ~= # ~= 类似 >= V.N, == V.*, 所以该部分的比较没必要使用 # if '~=' in pkg1 and '~=' in pkg2: # if not is_v1_c_eq_v2(ver1, ver2): # logger.debug( # '冲突依赖: %s, %s, 版本冲突: %s !~= %s', # pkg1, pkg2, ver1, ver2) # return True # ==, == / ===, === if (```"==```" in pkg1 and ```"==```" in pkg2) or (```"===```" in pkg1 and ```"===```" in pkg2): if PyWhlVersionComparison(ver1) != PyWhlVersionComparison(ver2): logger.debug( ```"冲突依赖: %s, %s, 版本冲突: %s != %s```", pkg1, pkg2, ver1, ver2 ) return True return False def detect_conflict_package_from_list(package_list: list[str]) -> list[str]: ```"```"```"检测 Python 软件包版本声明列表中存在冲突的软件包 Args: package_list (list[str]): Python 软件包版本声明列表 Returns: list[str]: 冲突的 Python 软件包列表 ```"```"```" conflict_package = [] for i in package_list: for j in package_list: # 截取包名并将包名中的中划线统一成下划线 pkg1 = get_package_name(i).replace(```"-```", ```"_```") pkg2 = get_package_name(j).replace(```"-```", ```"_```") if pkg1 == pkg2 and detect_conflict_package(i, j): conflict_package.append(get_package_name(i)) return remove_duplicate_object_from_list(conflict_package) def display_comfyui_environment_dict( env_data: ComfyUIEnvironmentComponent, ) -> None: ```"```"```"列出 ComfyUI 环境组件字典内容 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 ```"```"```" logger.debug(```"ComfyUI 环境组件表```") for component_name, details in env_data.items(): logger.debug(```"Component: %s```", component_name) logger.debug(```" - requirement_path: %s```", details[```"requirement_path```"]) logger.debug(```" - is_disabled: %s```", details[```"is_disabled```"]) logger.debug(```" - requires: %s```", details[```"requires```"]) logger.debug(```" - has_missing_requires: %s```", details[```"has_missing_requires```"]) logger.debug(```" - missing_requires: %s```", details[```"missing_requires```"]) logger.debug(```" - has_conflict_requires: %s```", details[```"has_conflict_requires```"]) logger.debug(```" - conflict_requires: %s```", details[```"conflict_requires```"]) print() def display_check_result(requirement_list: list[str], conflict_result: str) -> None: ```"```"```"显示 ComfyUI 运行环境检查结果 Args: requirement_list (list[str]): ComfyUI 组件依赖文件路径列表 conflict_result (str): 冲突组件统计信息 ```"```"```" if len(requirement_list) > 0: logger.debug(```"需要安装 ComfyUI 组件列表```") for requirement in requirement_list: component_name = requirement.split(```"/```")[-2] logger.debug(```"%s:```", component_name) logger.debug(```" - %s```", requirement) print() if len(conflict_result) > 0: logger.debug(```"ComfyUI 冲突组件: \n%s```", conflict_result) def process_comfyui_env_analysis( comfyui_root_path: Path | str, ) -> ( tuple[dict[str, ComponentEnvironmentDetails], list[str], str] | tuple[None, None, None] ): ```"```"```"分析 ComfyUI 环境 Args: comfyui_root_path (Path | str): ComfyUI 根目录 Returns: (tuple[dict[str, ComponentEnvironmentDetails], list[str], str] | tuple[None, None, None]): ComfyUI 环境组件信息, 缺失依赖的依赖表, 冲突组件信息 ```"```"```" comfyui_root_path = ( Path(comfyui_root_path) if not isinstance(comfyui_root_path, Path) and comfyui_root_path is not None else comfyui_root_path ) if not (comfyui_root_path / ```"requirements.txt```").exists(): logger.error(```"ComfyUI 依赖文件缺失, 请检查 ComfyUI 是否安装完整```") return None, None, None if not (comfyui_root_path / ```"custom_nodes```").exists(): logger.error(```"ComfyUI 自定义节点文件夹未找到, 请检查 ComfyUI 是否安装完整```") return None, None, None env_data = create_comfyui_environment_dict(comfyui_root_path) update_comfyui_component_requires_list(env_data) update_comfyui_component_missing_requires_list(env_data) pkg_list = get_comfyui_component_requires_list(env_data) has_version_pkg = fitter_has_version_package(pkg_list) conflict_pkg = detect_conflict_package_from_list(has_version_pkg) update_comfyui_component_conflict_requires_list(env_data, conflict_pkg) req_list = statistical_need_install_require_component(env_data) conflict_info = statistical_has_conflict_component(env_data, conflict_pkg) return env_data, req_list, conflict_info def write_content_to_file( content: list[str], path: str | Path, ) -> None: ```"```"```"将内容列表写入到文件中 Args: content (list[str]): 内容列表 path (str | Path): 保存内容的路径 ```"```"```" if len(content) == 0: return dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path, exist_ok=True) try: logger.debug(```"写入文件到 %s```", path) with open(path, ```"w```", encoding=```"utf-8```") as f: for item in content: f.write(item + ```"\n```") except Exception as e: logger.error(```"写入文件到 %s 时出现了错误: %s```", path, e) def main() -> None: ```"```"```"主函数```"```"```" comfyui_root_path = COMMAND_ARGS.comfyui_path comfyui_conflict_notice = COMMAND_ARGS.conflict_depend_notice_path comfyui_requirement_path = COMMAND_ARGS.requirement_list_path debug_mode = COMMAND_ARGS.debug_mode if not os.path.exists(os.path.join(comfyui_root_path, ```"requirements.txt```")): logger.error(```"ComfyUI 依赖文件缺失, 请检查 ComfyUI 是否安装完整```") sys.exit(1) if not os.path.exists(os.path.join(comfyui_root_path, ```"custom_nodes```")): logger.error(```"ComfyUI 自定义节点文件夹未找到, 请检查 ComfyUI 是否安装完整```") sys.exit(1) if not comfyui_conflict_notice or not comfyui_requirement_path: logger.error( ```"未配置 --conflict-depend-notice-path / --requirement-list-path, 无法进行环境检测```" ) sys.exit(1) logger.debug(```"检测 ComfyUI 环境中```") env_data, req_list, conflict_info = process_comfyui_env_analysis(comfyui_root_path) write_content_to_file(conflict_info, comfyui_conflict_notice) write_content_to_file(req_list, comfyui_requirement_path) if debug_mode: display_comfyui_environment_dict(env_data) display_check_result(req_list, conflict_info) logger.debug(```"ComfyUI 环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 ComfyUI 运行环境组件依赖中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_comfyui_env.py`" -Value `$content Remove-Item -Path `"`$Env:CACHE_HOME/comfyui_requirement_list.txt`" -Force -Recurse -ErrorAction SilentlyContinue 2> `$null Remove-Item -Path `"`$Env:CACHE_HOME/comfyui_conflict_requirement_list.txt`" -Force -Recurse -ErrorAction SilentlyContinue 2> `$null python `"`$Env:CACHE_HOME/check_comfyui_env.py`" --comfyui-path `"`$PSScriptRoot/`$Env:CORE_PREFIX`" --conflict-depend-notice-path `"`$Env:CACHE_HOME/comfyui_conflict_requirement_list.txt`" --requirement-list-path `"`$Env:CACHE_HOME/comfyui_requirement_list.txt`" ` if (Test-Path `"`$Env:CACHE_HOME/comfyui_conflict_requirement_list.txt`") { Print-Msg `"检测到当前 ComfyUI 环境中安装的插件之间存在依赖冲突情况, 该问题并非致命, 但建议只保留一个插件, 否则部分功能可能无法正常使用`" Print-Msg `"您可以进入 ComfyUI 后使用 ComfyUI Manager 禁用或者卸载冲突的插件, 也可以进入 `$PSScriptRoot/`$Env:CORE_PREFIX/custom_nodes 路径, 将冲突插件的文件夹名称进行修改, 加上 .disabled 后缀后即可禁用插件, 或者直接删除插件的文件夹以卸载插件`" Print-Msg `"您可以选择按顺序安装依赖, 由于这将向环境中安装不符合版本要求的组件, 您将无法完全解决此问题, 但可避免组件由于依赖缺失而无法启动的情况`" Print-Msg `"您通常情况下可以选择忽略该警告并继续运行`" Write-Host `"-------------------------------------------------------------------------------`" Write-Host `"发生冲突的组件:`" `$content = Get-Content `"`$Env:CACHE_HOME/comfyui_conflict_requirement_list.txt`" for (`$i = 0; `$i -lt `$content.Length; `$i++) { Write-Host `$content[`$i] } Write-Host `"-------------------------------------------------------------------------------`" Print-Msg `"是否按顺序安装冲突依赖 (yes/no) ?`" Print-Msg `"提示:`" Print-Msg `"如果不选择按顺序安装冲突依赖, 则跳过安装冲突依赖直接运行 ComfyUI`" Print-Msg `"输入 yes 或 no 后回车`" `$option = (Read-Host `"========================================>`").Trim() if (`$option -eq `"yes`" -or `$option -eq `"y`" -or `$option -eq `"YES`" -or `$option -eq `"Y`") { Print-Msg `"按顺序安装冲突组件依赖中`" } else { Print-Msg `"跳过按顺序安装组件依赖`" return } } # 安装组件依赖 if (!(Test-Path `"`$Env:CACHE_HOME/comfyui_requirement_list.txt`")) { Print-Msg `"ComfyUI 运行环境无组件依赖缺失`" return } `$requirement_list = Get-Content `"`$Env:CACHE_HOME/comfyui_requirement_list.txt`" `$sum = if (`$requirement_list.GetType().Name -eq `"String`") { 1 } else { `$requirement_list.Length } for (`$i = 0; `$i -lt `$sum; `$i++) { `$path = if (`$requirement_list.GetType().Name -eq `"String`") { `$requirement_list } else { `$requirement_list[`$i] } `$name = Split-Path `$(Split-Path `$path -Parent) -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 安装 `$name 组件依赖中`" if (`$USE_UV) { uv pip install -r `"`$path`" if (!(`$?)) { Print-Msg `"[`$(`$i + 1)/`$sum] 检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$path`" } } else { python -m pip install -r `"`$path`" } if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name 组件依赖安装成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name 组件依赖安装失败, 可能会导致该组件缺失依赖出现运行异常`" } `$install_script = `"`$(Split-Path `$path -Parent)/install.py`" if (Test-Path `"`$install_script`") { Print-Msg `"[`$(`$i + 1)/`$sum] 执行 `$name 的依赖安装脚本中`" python `"`$install_script`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name 组件依赖安装脚本执行成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name 组件依赖安装脚本执行失败, 可能会导致该组件缺失依赖出现运行异常`" } } } } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 Numpy 版本 function Check-Numpy-Version { `$content = `" import importlib.metadata from importlib.metadata import version try: ver = int(version('numpy').split('.')[0]) except: ver = -1 if ver > 1: print(True) else: print(False) `".Trim() Print-Msg `"检查 Numpy 版本中`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"检测到 Numpy 版本大于 1, 这可能导致部分组件出现异常, 尝试重装中`" if (`$USE_UV) { uv pip install `"numpy==1.26.4`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `"numpy==1.26.4`" } } else { python -m pip install `"numpy==1.26.4`" } if (`$?) { Print-Msg `"Numpy 重新安装成功`" } else { Print-Msg `"Numpy 重新安装失败, 这可能导致部分功能异常`" } } else { Print-Msg `"Numpy 无版本问题`" } } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 ComfyUI 运行环境 function Check-ComfyUI-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 ComfyUI 运行环境检测, 这可能会导致 ComfyUI 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 ComfyUI 运行环境中`" } Check-ComfyUI-Requirements Check-ComfyUI-Env-Requirements Fix-PyTorch Check-Onnxruntime-GPU Check-Numpy-Version Check-MS-VCPP-Redistributable Print-Msg `"ComfyUI 运行环境检查完成`" } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过 ComfyUI Installer 更新检查`" } else { Check-ComfyUI-Installer-Update } Set-Github-Mirror Set-HuggingFace-Mirror Set-uv PyPI-Mirror-Status if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 ComfyUI 是否已正确安装, 或者尝试运行 ComfyUI Installer 进行修复`" Read-Host | Out-Null return } `$launch_args = Get-ComfyUI-Launch-Args # 记录上次的路径 `$current_path = `$(Get-Location).ToString() Set-Location `"`$PSScriptRoot/`$Env:CORE_PREFIX`" Create-ComfyUI-Shortcut Check-ComfyUI-Env Set-PyTorch-CUDA-Memory-Alloc Print-Msg `"启动 ComfyUI 中`" if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过启动 ComfyUI`" } else { python main.py `$launch_args `$req = `$? if (`$req) { Print-Msg `"ComfyUI 正常退出`" } else { Print-Msg `"ComfyUI 出现异常, 已退出`" } Read-Host | Out-Null } Set-Location `"`$current_path`" } ################### Main ".Trim() if (Test-Path "$InstallPath/launch.ps1") { Print-Msg "更新 launch.ps1 中" } else { Print-Msg "生成 launch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 ComfyUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 ComfyUI Installer 更新检查 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 ComfyUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # ComfyUI Installer 更新检测 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 ComfyUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -le `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 ComfyUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 ComfyUI Installer 更新`" return } } else { Print-Msg `"检测到 ComfyUI Installer 有新版本可用`" } Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过 ComfyUI Installer 更新检查`" } else { Check-ComfyUI-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 ComfyUI 是否已正确安装, 或者尝试运行 ComfyUI Installer 进行修复`" Read-Host | Out-Null return } Print-Msg `"拉取 ComfyUI 更新内容中`" Fix-Git-Point-Off-Set `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$core_origin_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" fetch --recurse-submodules --all if (`$?) { Print-Msg `"应用 ComfyUI 更新中`" `$commit_hash = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" reset --hard `"`$remote_branch`" --recurse-submodules `$core_latest_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$core_origin_ver -eq `$core_latest_ver) { Print-Msg `"ComfyUI 已为最新版, 当前版本:`$core_origin_ver`" } else { Print-Msg `"ComfyUI 更新成功, 版本:`$core_origin_ver -> `$core_latest_ver`" } } else { Print-Msg `"拉取 ComfyUI 更新内容失败`" Print-Msg `"更新 ComfyUI 失败, 请检查控制台日志。可尝试重新运行 ComfyUI Installer 更新脚本进行重试`" } Print-Msg `"退出 ComfyUI 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 更新脚本 function Write-Update-Node-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 ComfyUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 ComfyUI Installer 更新检查 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 ComfyUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # ComfyUI Installer 更新检测 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 ComfyUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -le `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 ComfyUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 ComfyUI Installer 更新`" return } } else { Print-Msg `"检测到 ComfyUI Installer 有新版本可用`" } Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 列出更新结果 function List-Update-Status (`$update_status) { `$success = 0 `$failed = 0 `$sum = 0 Print-Msg `"当前 ComfyUI 自定义节点更新结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"自定义节点名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"更新结果`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$update_status.Count; `$i++) { `$content = `$update_status[`$i] `$name = `$content[0] `$ver = `$content[1] `$status = `$content[2] `$sum += 1 if (`$status) { `$success += 1 } else { `$failed += 1 } Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`${name}: `" -ForegroundColor White -NoNewline if (`$status) { Write-Host `"`$ver `" -ForegroundColor Cyan } else { Write-Host `"`$ver `" -ForegroundColor Red } } Write-Host Write-Host `"[●: `$sum | ✓: `$success | ×: `$failed]`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过 ComfyUI Installer 更新检查`" } else { Check-ComfyUI-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 ComfyUI 是否已正确安装, 或者尝试运行 ComfyUI Installer 进行修复`" Read-Host | Out-Null return } `$node_list = Get-ChildItem -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/custom_nodes`" | Select-Object -ExpandProperty FullName `$sum = 0 `$count = 0 ForEach (`$node in `$node_list) { if (Test-Path `"`$node/.git`") { `$sum += 1 } } Print-Msg `"更新 ComfyUI 自定义节点中`" `$update_status = New-Object System.Collections.ArrayList ForEach (`$node in `$node_list) { if (!(Test-Path `"`$node/.git`")) { continue } `$count += 1 `$node_name = `$(`$(Get-Item `$node).Name) Print-Msg `"[`$count/`$sum] 更新 `$node_name 自定义节点中`" Fix-Git-Point-Off-Set `"`$node`" `$origin_ver = `$(git -C `"`$node`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$node`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$node`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$node`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$node`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$node`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$node`" fetch --recurse-submodules --all if (`$?) { `$commit_hash = `$(git -C `"`$node`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$node`" reset --hard `"`$remote_branch`" --recurse-submodules `$latest_ver = `$(git -C `"`$node`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$origin_ver -eq `$latest_ver) { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点已为最新版`" `$update_status.Add(@(`$node_name, `"已为最新版`", `$true)) | Out-Null } else { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点更新成功, 版本:`$origin_ver -> `$latest_ver`" `$update_status.Add(@(`$node_name, `"更新成功, 版本:`$origin_ver -> `$latest_ver`", `$true)) | Out-Null } } else { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点更新失败`" `$update_status.Add(@(`$node_name, `"更新失败`", `$false)) | Out-Null } } List-Update-Status `$update_status Print-Msg `"退出 ComfyUI 自定义节点更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update_node.ps1") { Print-Msg "更新 update_node.ps1 中" } else { Print-Msg "生成 update_node.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update_node.ps1" -Value $content } # 获取安装脚本 function Write-Launch-ComfyUI-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 ComfyUI Installer function Download-ComfyUI-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 ComfyUI Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/comfyui_installer.ps1`" if (`$?) { Print-Msg `"下载 ComfyUI Installer 脚本成功`" break } else { Print-Msg `"下载 ComfyUI Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 ComfyUI Installer 脚本`" } else { Print-Msg `"下载 ComfyUI Installer 脚本失败, 可尝试重新运行 ComfyUI Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { `$arg.Add(`"-DisableGithubMirror`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } `$arg.Add(`"-UseCustomGithubMirror`", `$github_mirror) } } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Set-Proxy `$status = Download-ComfyUI-Installer if (`$status) { Print-Msg `"运行 ComfyUI Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/comfyui_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 ComfyUI Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_comfyui_installer.ps1") { Print-Msg "更新 launch_comfyui_installer.ps1 中" } else { Print-Msg "生成 launch_comfyui_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_comfyui_installer.ps1" -Value $content } # 重装 PyTorch 脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWithTorch, [switch]`$BuildWithTorchReinstall, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableUV, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-DisablePyPIMirror] [-DisableUpdate] [-DisableUV] [-DisableProxy] [-UseCustomProxy] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 ComfyUI Installer 构建模式 -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 ComfyUI Installer 构建模式, 并且添加 -BuildWithTorch) 在 ComfyUI Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 ComfyUI Installer 更新检查 -DisableUV 禁用 ComfyUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableAutoApplyUpdate 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # ComfyUI Installer 更新检测 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 ComfyUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -le `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 ComfyUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 ComfyUI Installer 更新`" return } } else { Print-Msg `"检测到 ComfyUI Installer 有新版本可用`" } Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 xFormers 版本 function Get-xFormers-Version { `$content = `" from importlib.metadata import version try: ver = version('xformers') except: ver = None print(ver) `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 获取驱动支持的最高 CUDA 版本 function Get-Drive-Support-CUDA-Version { Print-Msg `"获取显卡驱动支持的最高 CUDA 版本`" if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) { `$cuda_ver = `$(nvidia-smi -q | Select-String -Pattern 'CUDA Version\s*:\s*([\d.]+)').Matches.Groups[1].Value } else { `$cuda_ver = `"未知`" } return `$cuda_ver } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } return `$torch_ver, `$xformers_ver } # 获取 HashTable 的值 function Get-HashValue { param( [hashtable]`$Hashtable, [string]`$Key, [object]`$Default = `$null ) if (`$Hashtable.ContainsKey(`$Key)) { return `$Hashtable[`$Key] } else { return `$Default } } # 获取可用的 PyTorch 类型 function Get-Avaliable-PyTorch-Type { `$content = `" import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 CUDA_TYPE = [ 'cu113', 'cu117', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu129', 'cu130', ] def get_avaliable_device() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() device_list = ['cpu'] if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): device_list.append('xpu') if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): device_list.append('directml') if compare_versions(cuda_comp_cap, '10.0') > 0: for ver in CUDA_TYPE: if compare_versions(ver, str(int(12.8 * 10))) >= 0: device_list.append(ver) else: for ver in CUDA_TYPE: if compare_versions(ver, str(int(cuda_support_ver * 10))) <= 0: device_list.append(ver) return ','.join(list(set(device_list))) if __name__ == '__main__': print(get_avaliable_device()) `".Trim() Print-Msg `"获取可用的 PyTorch 类型`" `$res = `$(python -c `"`$content`") return `$res -split ',' | ForEach-Object { `$_.Trim() } } # 获取 PyTorch 列表 function Get-PyTorch-List { `$pytorch_list = New-Object System.Collections.ArrayList `$supported_type = Get-Avaliable-PyTorch-Type # >>>>>>>>>> Start `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==1.12.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CUDA 11.3) + xFormers 0.0.14`" `"type`" = `"cu113`" `"supported`" = `"cu113`" -in `$supported_type `"torch`" = `"torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==1.12.1+cu113`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.13.1+cpu torchvision==0.14.1+cpu torchaudio==0.13.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 torch-directml==0.1.13.1.dev230413`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CUDA 11.7) + xFormers 0.0.16`" `"type`" = `"cu117`" `"supported`" = `"cu117`" -in `$supported_type `"torch`" = `"torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==1.13.1+cu117`" `"xformers`" = `"xformers==0.0.18`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.0 torch-directml==0.2.0.dev230426`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.0.0a0+gite9ebda2 torchvision==0.15.2a0+fa99a53 intel_extension_for_pytorch==2.0.110+gitc6ea20b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CUDA 11.8) + xFormers 0.0.18`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.0+cu118`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.1+cpu torchvision==0.15.2+cpu torchaudio==2.0.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CUDA 11.8) + xFormers 0.0.22`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.1+cu118`" `"xformers`" = `"xformers==0.0.22`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.0+cpu torchvision==0.16.0+cpu torchaudio==2.1.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi torchaudio==2.1.0a0+cxx11.abi intel_extension_for_pytorch==2.1.10+xpu`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Core Ultra)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+git7bcf7da torchvision==0.16.0+fbb4cc5 torchaudio==2.1.0+6ea1133 intel_extension_for_pytorch==2.1.20+git4849f3b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.1+cpu torchvision==0.16.1+cpu torchaudio==2.1.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 11.8) + xFormers 0.0.23`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu118 torchvision==0.16.1+cu118 torchaudio==2.1.1+cu118`" `"xformers`" = `"xformers==0.0.23+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 12.1) + xFormers 0.0.23`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu121 torchvision==0.16.1+cu121 torchaudio==2.1.1+cu121`" `"xformers`" = `"xformers===0.0.23`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.2+cpu torchvision==0.16.2+cpu torchaudio==2.1.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 11.8) + xFormers 0.0.23.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118`" `"xformers`" = `"xformers==0.0.23.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 12.1) + xFormers 0.0.23.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu121 torchvision==0.16.2+cu121 torchaudio==2.1.2+cu121`" `"xformers`" = `"xformers===0.0.23.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 11.8) + xFormers 0.0.24`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu118 torchvision==0.17.0+cu118 torchaudio==2.2.0+cu118`" `"xformers`" = `"xformers==0.0.24+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 12.1) + xFormers 0.0.24`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu121 torchvision==0.17.0+cu121 torchaudio==2.2.0+cu121`" `"xformers`" = `"xformers===0.0.24`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.1+cpu torchvision==0.17.1+cpu torchaudio==2.2.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 11.8) + xFormers 0.0.25`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu118 torchvision==0.17.1+cu118 torchaudio==2.2.1+cu118`" `"xformers`" = `"xformers==0.0.25+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 torch-directml==0.2.1.dev240521`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 12.1) + xFormers 0.0.25`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121`" `"xformers`" = `"xformers===0.0.25`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.2+cpu torchvision==0.17.2+cpu torchaudio==2.2.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 11.8) + xFormers 0.0.25.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu118 torchvision==0.17.2+cu118 torchaudio==2.2.2+cu118`" `"xformers`" = `"xformers==0.0.25.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 12.1) + xFormers 0.0.25.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu121 torchvision==0.17.2+cu121 torchaudio==2.2.2+cu121`" `"xformers`" = `"xformers===0.0.25.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.0+cpu torchvision==0.18.0+cpu torchaudio==2.3.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 11.8) + xFormers 0.0.26.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" `"xformers`" = `"xformers==0.0.26.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 12.1) + xFormers 0.0.26.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121`" `"xformers`" = `"xformers===0.0.26.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.1+cpu torchvision==0.18.1+cpu torchaudio==2.3.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 torch-directml==0.2.3.dev240715`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 11.8) + xFormers 0.0.27`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118`" `"xformers`" = `"xformers==0.0.27+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 12.1) + xFormers 0.0.27`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121`" `"xformers`" = `"xformers===0.0.27`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.0+cpu torchvision==0.19.0+cpu torchaudio==2.4.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 11.8) + xFormers 0.0.27.post2`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu118 torchvision==0.19.0+cu118 torchaudio==2.4.0+cu118`" `"xformers`" = `"xformers==0.0.27.post2+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 12.1) + xFormers 0.0.27.post2`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu121 torchvision==0.19.0+cu121 torchaudio==2.4.0+cu121`" `"xformers`" = `"xformers==0.0.27.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.1+cpu torchvision==0.19.1+cpu torchaudio==2.4.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CUDA 12.4) + xFormers 0.0.28.post1`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.4.1+cu124 torchvision==0.19.1+cu124 torchaudio==2.4.1+cu124`" `"xformers`" = `"xformers==0.0.28.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.0+cpu torchvision==0.20.0+cpu torchaudio==2.5.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CUDA 12.4) + xFormers 0.0.28.post2`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.0+cu124 torchvision==0.20.0+cu124 torchaudio==2.5.0+cu124`" `"xformers`" = `"xformers==0.0.28.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.1+cpu torchvision==0.20.1+cpu torchaudio==2.5.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CUDA 12.4) + xFormers 0.0.28.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124`" `"xformers`" = `"xformers==0.0.28.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+cpu torchvision==0.21.0+cpu torchaudio==2.6.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+xpu torchvision==0.21.0+xpu torchaudio==2.6.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.4) + xFormers 0.0.29.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.6) + xFormers 0.0.29.post3`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu126 torchvision==0.21.0+cu126 torchaudio==2.6.0+cu126`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+cpu torchvision==0.22.0+cpu torchaudio==2.7.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+xpu torchvision==0.22.0+xpu torchaudio==2.7.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu118 torchvision==0.22.0+cu118 torchaudio==2.7.0+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.6) + xFormers 0.0.30`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu126 torchvision==0.22.0+cu126 torchaudio==2.7.0+cu126`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.8) + xFormers 0.0.30`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu128 torchvision==0.22.0+cu128 torchaudio==2.7.0+cu128`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+cpu torchvision==0.22.1+cpu torchaudio==2.7.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+xpu torchvision==0.22.1+xpu torchaudio==2.7.1+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu118 torchvision==0.22.1+cu118 torchaudio==2.7.1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.6) + xFormers 0.0.31.post1`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu126 torchvision==0.22.1+cu126 torchaudio==2.7.1+cu126`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.8) + xFormers 0.0.31.post1`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu128 torchvision==0.22.1+cu128 torchaudio==2.7.1+cu128`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+cpu torchvision==0.23.0+cpu torchaudio==2.8.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+xpu torchvision==0.23.0+xpu torchaudio==2.8.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu128 torchvision==0.23.0+cu128 torchaudio==2.8.0+cu128`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.9)`" `"type`" = `"cu129`" `"supported`" = `"cu129`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129`" # `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 13.0)`" `"type`" = `"cu130`" `"supported`" = `"cu130`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU130 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null # <<<<<<<<<< End return `$pytorch_list } # 列出 PyTorch 列表 function List-PyTorch (`$pytorch_list) { Print-Msg `"PyTorch 版本列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"版本序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"PyTorch 版本`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"支持当前设备情况`" -ForegroundColor Blue for (`$i = 0; `$i -lt `$pytorch_list.Count; `$i++) { `$pytorch_hashtables = `$pytorch_list[`$i] `$count += 1 `$name = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"name`" `$supported = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"supported`" Write-Host `"- `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline if (`$supported) { Write-Host `"(支持✓)`" -ForegroundColor Green } else { Write-Host `"(不支持×)`" -ForegroundColor Red } } Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过 ComfyUI Installer 更新检查`" } else { Check-ComfyUI-Installer-Update } Set-uv PyPI-Mirror-Status `$pytorch_list = Get-PyTorch-List `$go_to = 0 `$to_exit = 0 `$torch_ver = `"`" `$xformers_ver = `"`" `$cuda_support_ver = Get-Drive-Support-CUDA-Version `$current_torch_ver, `$current_xformers_ver = Get-PyTorch-And-xFormers-Version `$after_list_model_option = `"`" while (`$True) { switch (`$after_list_model_option) { display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" List-PyTorch `$pytorch_list Print-Msg `"当前 PyTorch 版本: `$current_torch_ver`" Print-Msg `"当前 xFormers 版本: `$current_xformers_ver`" Print-Msg `"当前显卡驱动支持的最高 CUDA 版本: `$cuda_support_ver`" Print-Msg `"请选择 PyTorch 版本`" Print-Msg `"提示:`" Print-Msg `"1. PyTorch 版本通常来说选择最新版的即可`" Print-Msg `"2. 驱动支持的最高 CUDA 版本需要大于或等于要安装的 PyTorch 中所带的 CUDA 版本, 若驱动支持的最高 CUDA 版本低于要安装的 PyTorch 中所带的 CUDA 版本, 可尝试更新显卡驱动, 或者选择 CUDA 版本更低的 PyTorch`" Print-Msg `"3. 输入数字后回车, 或者输入 exit 退出 PyTorch 重装脚本`" if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建已启用, 指定安装的 PyTorch 序号: `$BuildWithTorch`" `$arg = `$BuildWithTorch `$go_to = 1 } else { `$arg = (Read-Host `"========================================>`").Trim() } switch (`$arg) { exit { Print-Msg `"退出 PyTorch 重装脚本`" `$to_exit = 1 `$go_to = 1 } Default { try { # 检测输入是否符合列表 `$i = [int]`$arg if (!((`$i -ge 1) -and (`$i -le `$pytorch_list.Count))) { `$after_list_model_option = `"display_input_error`" break } `$pytorch_info = `$pytorch_list[(`$i - 1)] `$combination_name = Get-HashValue -Hashtable `$pytorch_info -Key `"name`" `$torch_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"torch`" `$xformers_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"xformers`" `$index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"index_mirror`" `$extra_index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"extra_index_mirror`" `$find_links = Get-HashValue -Hashtable `$pytorch_info -Key `"find_links`" if (`$null -ne `$index_mirror) { `$Env:PIP_INDEX_URL = `$index_mirror `$Env:UV_DEFAULT_INDEX = `$index_mirror } if (`$null -ne `$extra_index_mirror) { `$Env:PIP_EXTRA_INDEX_URL = `$extra_index_mirror `$Env:UV_INDEX = `$extra_index_mirror } if (`$null -ne `$find_links) { `$Env:PIP_FIND_LINKS = `$find_links `$Env:UV_FIND_LINKS = `$find_links } } catch { `$after_list_model_option = `"display_input_error`" break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否选择仅强制重装 ? (通常情况下不需要)`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { if (`$BuildWithTorchReinstall) { `$use_force_reinstall = `"yes`" } else { `$use_force_reinstall = `"no`" } } else { `$use_force_reinstall = (Read-Host `"========================================>`").Trim() } if (`$use_force_reinstall -eq `"yes`" -or `$use_force_reinstall -eq `"y`" -or `$use_force_reinstall -eq `"YES`" -or `$use_force_reinstall -eq `"Y`") { `$force_reinstall_arg = `"--force-reinstall`" `$force_reinstall_status = `"启用`" } else { `$force_reinstall_arg = New-Object System.Collections.ArrayList `$force_reinstall_status = `"禁用`" } Print-Msg `"当前的选择: `$combination_name`" Print-Msg `"PyTorch: `$torch_ver`" Print-Msg `"xFormers: `$xformers_ver`" Print-Msg `"仅强制重装: `$force_reinstall_status`" Print-Msg `"是否确认安装?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$install_torch = `"yes`" } else { `$install_torch = (Read-Host `"========================================>`").Trim() } if (`$install_torch -eq `"yes`" -or `$install_torch -eq `"y`" -or `$install_torch -eq `"YES`" -or `$install_torch -eq `"Y`") { Print-Msg `"重装 PyTorch 中`" if (`$USE_UV) { uv pip install `$torch_ver.ToString().Split() `$force_reinstall_arg if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } } else { python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } if (`$?) { Print-Msg `"安装 PyTorch 成功`" } else { Print-Msg `"安装 PyTorch 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } if (`$null -ne `$xformers_ver) { Print-Msg `"重装 xFormers 中`" if (`$USE_UV) { `$current_xf_ver = Get-xFormers-Version if (`$xformers_ver.Split(`"=`")[-1] -ne `$current_xf_ver) { Print-Msg `"卸载原有 xFormers 中`" python -m pip uninstall xformers -y } uv pip install `$xformers_ver `$force_reinstall_arg --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } } else { python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } if (`$?) { Print-Msg `"安装 xFormers 成功`" } else { Print-Msg `"安装 xFormers 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 ComfyUI Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 ComfyUI Installer 更新检查 -DisableAutoApplyUpdate 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # ComfyUI Installer 更新检测 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 ComfyUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -le `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 ComfyUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 ComfyUI Installer 更新`" return } } else { Print-Msg `"检测到 ComfyUI Installer 有新版本可用`" } Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`" -Force } elseif ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/nai1-artist_all_in_one_merge.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/Counterfeit-V3.0_fp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cetusMix_Whalefall2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ex2K_sse2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/kohakuV5_rev2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinamix_meinaV11.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/oukaStar_10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/rabbit_v6.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/sweetSugarSyndrome_rev15.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/AnythingV5Ink_ink.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinapastel_v6Pastel.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/qteamixQ_omegaFp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-lora/resolve/master/sdxl/sd_xl_offset_example-lora_1.0.safetensors`", `"SDXL`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl_edit.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/AnythingXL_xl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/abyssorangeXLElse_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animaPencilXL_v200.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/bluePencilXL_v401.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/nekorayxl_v06W3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/CounterfeitXL-V1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null # SD 3 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips_t5xxlfp8.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_fp8_scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_turbo.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/emi3.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null # SD 3 Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_g.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_l.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp16.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn_scaled.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null # HunyuanDiT `$model_list.Add(@(`"https://modelscope.cn/models/licyks/comfyui-extension-models/resolve/master/hunyuan_dit_comfyui/hunyuan_dit_1.2.safetensors`", `"HunyuanDiT`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/comfyui-extension-models/resolve/master/hunyuan_dit_comfyui/comfy_freeway_animation_hunyuan_dit_180w.safetensors`", `"HunyuanDiT`", `"checkpoints`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux_dev_fp8_scaled_diffusion_model.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4-v2.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q2_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q3_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q6_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q8_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-F16.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q2_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q3_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q6_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q8_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-F16.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev_fp8_scaled.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-kontext_fp8_scaled.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-kontext-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/chroma-unlocked-v50.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null # FLUX Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_L.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q6_K.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q8_0.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f16.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f32.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"vae`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null # VAE approx `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/model.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sdxl.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sd3.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null # Upscale `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/Codeformer/codeformer-v0.1.0.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/16xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x-ITF-SkinDiffDetail-Lite-v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-BrightenRedux_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-YandereInpaint_375000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKDDetoon_97500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Poisson-Detailed_108000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Uniform-Detailed_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x-UltraSharp.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_CountryRoads_377000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Fatality_Comix_260000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Siax_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-Artisoftject_210000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere-Lite_280k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere_300k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-YandereNeoXL_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKDSuperscale_Artisoft_120000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NickelbackFS_72000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Nickelback_70000G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_RealisticRescaler_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Valar_v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_fatal_Anime_500000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_foolhardy_Remacri.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Superscale_150000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Typescale_175k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/A_ESRGAN_Single.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGAN.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGANx2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRNet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/ESRGAN_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/LADDIER1_282500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Neutral_115000_swaG.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharp_101000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharper_103000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Detailed_155000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Soft_190000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/WaifuGAN_v3_30000.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/lollypop.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/sudo_rife4_269.662_testV1_scale1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/detection_Resnet50_Final.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_bisenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_parsenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x2_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X2_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X4_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_CompressedSR_X4_48.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/SwinIR_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null # Embedding `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/EasyNegativeV2.safetensors`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist-anime.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-hands-5.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-image-v2-39000.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad_prompt_version2.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/ng_deepnegative_v1_75t.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/verybadimagenegative_v1.3.pt`", `"Embedding`", `"embeddings`")) | Out-Null # SD 1.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_ip2p_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_shuffle_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1e_sd15_tile_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1p_sd15_depth_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_canny_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_inpaint_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_lineart_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_mlsd_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_normalbae_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_openpose_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_scribble_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_seg_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_softedge_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15s2_lineart_anime_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_brightness.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_illumination.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_qrcode_monster.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null # SDXL ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/monster-labs-control_v1p_sdxl_qrcode_monster.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/mistoLine_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/destitech-controlnet-inpaint-dreamer-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/control-lora/resolve/master/control-lora-recolor-rank128-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/xinsir-controlnet-union-sdxl-1.0-promax.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/kohakuXLControlnet_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/animagineXL40_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLCanny_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineart_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLDepth_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLSoftedge_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineartRrealistic_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLShuffle_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLOpenPose_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLTile_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv0.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_canny_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_depth_midas_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_tile_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsCanny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartAnime.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsNormalMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsSoftedgeHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsMangaLine.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartRealistic.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidasV11.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribbleHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribblePidinet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_openposeModel.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsTile.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/NoobAI_Inpainting_ControlNet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null # SD 3.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_blur.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_canny.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_depth.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null # FLUX ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-redux-dev.safetensors`", `"FLUX ControlNet`", `"style_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q3_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_1.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_1.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q6_K.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q8_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank128.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank256.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank32.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank4.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank64.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank8.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-canny-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-depth-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-hed-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Depth.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Surface-Normals.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Upscaler.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-instantx-controlnet-union.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-mistoline.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-shakker-labs-controlnet-union-pro.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null # CLIP Vision `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_g.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_h.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_vitl.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/sigclip_vision_patch14_384.safetensors`", `"CLIP Vision`", `"clip_vision`")) | Out-Null # IP Adapter `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_light.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_plus.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_vit-G.safetensors`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter-plus_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/noobIPAMARK1_mark1.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-ip-adapter.safetensors`", `"FLUX IP Adapter`", `"controlnet`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"========================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"ComfyUI Installer 构建模式已启用, 跳过 ComfyUI Installer 更新检查`" } else { Check-ComfyUI-Installer-Update } Check-Aria2-Version if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 ComfyUI 是否已正确安装, 或者尝试运行 ComfyUI Installer 进行修复`" Read-Host | Out-Null return } `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/models/`$(`$content[2])`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list } Print-Msg `"退出模型下载脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # ComfyUI Installer 设置脚本 function Write-ComfyUI-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [switch]`$UseCustomProxy ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # 获取 ComfyUI Installer 自动检测更新设置 function Get-ComfyUI-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 ComfyUI Installer 自动应用更新设置 function Get-ComfyUI-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取启动参数设置 function Get-Launch-Args-Setting { if (Test-Path `"`$PSScriptRoot/launch_args.txt`") { return Get-Content `"`$PSScriptRoot/launch_args.txt`" } else { return `"无`" } } # 获取自动创建快捷启动方式 function Get-Auto-Set-Launch-Shortcut-Setting { if (Test-Path `"`$PSScriptRoot/enable_shortcut.txt`") { return `"启用`" } else { return `"禁用`" } } # 获取 PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 ComfyUI 运行环境检测配置 function Get-ComfyUI-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动选择`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"========================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 ComfyUI 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # ComfyUI Installer 自动检查更新设置 function Update-ComfyUI-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 ComfyUI Installer 自动检测更新设置: `$(Get-ComfyUI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 ComfyUI Installer 自动更新检查`" Print-Msg `"2. 禁用 ComfyUI Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 ComfyUI Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 ComfyUI Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 ComfyUI Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # ComfyUI Installer 自动应用更新设置 function Update-ComfyUI-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 ComfyUI Installer 自动应用更新设置: `$(Get-ComfyUI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 ComfyUI Installer 自动应用更新`" Print-Msg `"2. 禁用 ComfyUI Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 ComfyUI Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 ComfyUI Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # ComfyUI 启动参数设置 function Update-ComfyUI-Launch-Args-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 ComfyUI 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 设置 ComfyUI 启动参数`" Print-Msg `"2. 删除 ComfyUI 启动参数`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入 ComfyUI 启动参数`" Print-Msg `"提示: 保存启动参数后原本的启动参数配置将被覆盖`" Print-Msg `"输入启动参数后回车保存`" `$comfyui_launch_args = Get-User-Input Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/launch_args.txt`" -Value `$comfyui_launch_args Print-Msg `"设置 ComfyUI 启动参数成功, 使用的 ComfyUI 启动参数为: `$comfyui_launch_args`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/launch_args.txt`" -Force -Recurse 2> `$null Print-Msg `"删除 ComfyUI 启动参数成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 自动创建 ComfyUI 快捷启动方式设置 function Auto-Set-Launch-Shortcut-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动创建 ComfyUI 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动创建 ComfyUI 快捷启动方式`" Print-Msg `"2. 禁用自动创建 ComfyUI 快捷启动方式`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { New-Item -ItemType File -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force > `$null Print-Msg `"启用自动创建 ComfyUI 快捷启动方式成功`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用自动创建 ComfyUI 快捷启动方式成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # ComfyUI 运行环境检测设置 function ComfyUI-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 ComfyUI 运行环境检测设置: `$(Get-ComfyUI-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 ComfyUI 运行环境检测`" Print-Msg `"2. 禁用 ComfyUI 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 ComfyUI 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 ComfyUI 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 ComfyUI Installer 更新 function Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -gt `$COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 有新版本可用`" Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 ComfyUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"ComfyUI Installer 已是最新版本`" } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if ((Test-Path `"`$PSScriptRoot/python/python.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`")) { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/git.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`")) { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/main.py`") { `$comfyui_status = `"已安装`" } else { `$comfyui_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"ComfyUI: `$comfyui_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 ComfyUI Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 ComfyUI Installer 文档 function Get-ComfyUI-Installer-Help-Docs { Print-Msg `"调用浏览器打开 ComfyUI Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md`" } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"ComfyUI Installer 自动检查更新: `$(Get-ComfyUI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"ComfyUI Installer 自动应用更新: `$(Get-ComfyUI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"ComfyUI 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"自动创建 ComfyUI 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"ComfyUI 运行环境检测设置: `$(Get-ComfyUI-Env-Check-Setting)`" Print-Msg `"ComfyUI 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 Github 镜像源设置`" Print-Msg `"5. 进入 ComfyUI Installer 自动检查更新设置`" Print-Msg `"6. 进入 ComfyUI Installer 自动应用更新设置`" Print-Msg `"7. 进入 ComfyUI 启动参数设置`" Print-Msg `"8. 进入自动创建 ComfyUI 快捷启动方式设置`" Print-Msg `"9. 进入 PyPI 镜像源设置`" Print-Msg `"10. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"11. 进入 ComfyUI 运行环境检测设置`" Print-Msg `"12. 进入 ComfyUI 内核路径前缀设置`" Print-Msg `"13. 更新 ComfyUI Installer 管理脚本`" Print-Msg `"14. 检查环境完整性`" Print-Msg `"15. 查看 ComfyUI Installer 文档`" Print-Msg `"16. 退出 ComfyUI Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-Github-Mirror-Setting break } 5 { Update-ComfyUI-Installer-Auto-Check-Update-Setting break } 6 { Update-ComfyUI-Installer-Auto-Apply-Update-Setting break } 7 { Update-ComfyUI-Launch-Args-Setting break } 8 { Auto-Set-Launch-Shortcut-Setting break } 9 { PyPI-Mirror-Setting break } 10 { PyTorch-CUDA-Memory-Alloc-Setting break } 11 { ComfyUI-Env-Check-Setting break } 12 { Update-Core-Prefix-Setting break } 13 { Check-ComfyUI-Installer-Update break } 14 { Check-Env break } 15 { Get-ComfyUI-Installer-Help-Docs break } 16 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 ComfyUI Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableGithubMirror, [switch]`$UseCustomGithubMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror ) & { `$prefix_list = @(`"core`", `"ComfyUI`", `"comfyui`", `"ComfyUI-aki-v1.0`", `"ComfyUI-aki-v1.1`", `"ComfyUI-aki-v1.2`", `"ComfyUI-aki-v1.3`", `"ComfyUI-aki-v1.4`", `"ComfyUI-aki-v1.5`", `"ComfyUI-aki-v1.6`", `"ComfyUI-aki-v1.7`", `"ComfyUI-aki-v2`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # ComfyUI Installer 版本和检查更新间隔 `$Env:COMFYUI_INSTALLER_VERSION = $COMFYUI_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CU130 = `"$PIP_EXTRA_INDEX_MIRROR_CU130`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:COMFYUI_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:COMFYUI_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableGithubMirror 禁用 ComfyUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示符信息 function global:prompt { `"`$(Write-Host `"[ComfyUI Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:COMFYUI_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # ComfyUI Installer 更新检测 function global:Check-ComfyUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/comfyui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/comfyui_installer/comfyui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/comfyui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:COMFYUI_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 ComfyUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/comfyui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/comfyui_installer.ps1`" | Select-String -Pattern `"COMFYUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 ComfyUI Installer 更新中`" } else { Print-Msg `"检查 ComfyUI Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:COMFYUI_INSTALLER_VERSION) { Print-Msg `"ComfyUI Installer 有新版本可用`" Print-Msg `"调用 ComfyUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/comfyui_installer.ps1`" -InstallPath `"`$Env:COMFYUI_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 ComfyUI Installer 管理脚本以应用更新, 回车退出 ComfyUI Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"ComfyUI Installer 已是最新版本`" } } # 启用 Github 镜像源 function global:Test-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$Env:COMFYUI_INSTALLER_ROOT/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/.gitconfig`") { Remove-Item -Path `"`$Env:COMFYUI_INSTALLER_ROOT/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } if ((Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { # 使用自定义 Github 镜像源 if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$Env:COMFYUI_INSTALLER_ROOT/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `$i/licyk/empty `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 安装 ComfyUI 自定义节点 function global:Install-ComfyUI-Node (`$url) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$node_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" `$cache_path = `"`$Env:CACHE_HOME/`${node_name}_tmp`" `$path = `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/custom_nodes/`$node_name`" if (!(Test-Path `"`$path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"安装 `$node_name 自定义节点中`" # 清理缓存路径 if (Test-Path `"`$cache_path`") { Remove-Item -Path `"`$cache_path`" -Force -Recurse } git clone --recurse-submodules `$url `"`$cache_path`" if (`$?) { # 清理空文件夹 if (Test-Path `"`$path`") { `$random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path `"`$path`" -Destination `"`$Env:CACHE_HOME/`$random_string`" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path `"`$([System.IO.Path]::GetDirectoryName(`$path))`" -Force > `$null Move-Item -Path `"`$cache_path`" -Destination `"`$path`" -Force Print-Msg `"`$node_name 自定义节点安装成功`" } else { Print-Msg `"`$node_name 自定义节点安装失败`" } } else { Print-Msg `"`$node_name 自定义节点已安装`" } } # Git 下载命令 function global:Git-Clone (`$url, `$path) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$repo_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" if (`$path.Length -ne 0) { `$repo_path = `$path } else { `$repo_path = `"`$(`$(Get-Location).ToString())/`$repo_name`" } if (!(Test-Path `"`$repo_path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$repo_path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"下载 `$repo_name 中`" git clone --recurse-submodules `$url `"`$path`" if (`$?) { Print-Msg `"`$repo_name 下载成功`" } else { Print-Msg `"`$repo_name 下载失败`" } } else { Print-Msg `"`$repo_name 已存在`" } } # 列出已安装的 ComfyUI 自定义节点 function global:List-Node { `$node_list = Get-ChildItem -Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/custom_nodes`" | Select-Object -ExpandProperty FullName Print-Msg `"当前 ComfyUI 已安装的自定义节点`" `$count = 0 ForEach (`$i in `$node_list) { if (Test-Path `"`$i`" -PathType Container) { `$count += 1 `$name = [System.IO.Path]::GetFileNameWithoutExtension(`"`$i`") Print-Msg `"- `$name`" } } Print-Msg `"ComfyUI 自定义节点路径: `$([System.IO.Path]::GetFullPath(`"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/custom_nodes`"))`" Print-Msg `"ComfyUI 自定义节点数量: `$count`" } # 安装绘世启动器 function global:Install-Hanamizuki { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe`", `"https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`", `"https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`" ) `$i = 0 if (!(Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX 未找到, 无法安装绘世启动器, 请检查 ComfyUI 是否已正确安装, 或者尝试运行 ComfyUI Installer 进行修复`" return } New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if (Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`") { Print-Msg `"绘世启动器已安装, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" } else { ForEach (`$url in `$urls) { Print-Msg `"下载绘世启动器中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" Move-Item -Path `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`" -Force Print-Msg `"绘世启动器安装成功, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载绘世启动器中`" } else { Print-Msg `"下载绘世启动器失败`" return } } } } `$content = `" @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=ComfyUI if exist ```"%~dp0%DefaultCorePrefix%```" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if ```"%%i```"==```"-CorePrefix```" ( set NextIsValue=1 ) ) ) if exist ```"%CorePrefixFile%```" ( for /f ```"delims=```" %%i in ('powershell -command ```"Get-Content -Path '%CorePrefixFile%'```"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f ```"delims=```" %%i in ('powershell -command ```"```$current_path = '%CurrentPath%'.Trim('/').Trim('\'); ```$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(```$origin_core_prefix)) { ```$to_path = ```$origin_core_prefix; ```$from_uri = New-Object System.Uri(```$current_path.Replace('\', '/') + '/'); ```$to_uri = New-Object System.Uri(```$to_path.Replace('\', '/')); ```$origin_core_prefix = ```$from_uri.MakeRelativeUri(```$to_uri).ToString().Trim('/') }; Write-Host ```$origin_core_prefix```"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist ```"%RootPath%```" ( cd /d ```"%RootPath%```" ) else ( echo %CorePrefix% not found echo Please check if ComfyUI is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d ```"%CurrentPath%```" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d ```"%CurrentPath%```" pause exit 1 ) `".Trim() Set-Content -Encoding Default -Path `"`$Env:COMFYUI_INSTALLER_ROOT/hanamizuki.bat`" -Value `$content Print-Msg `"检查绘世启动器运行环境`" if (!(Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`")) { if (Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/python`") { Print-Msg `"尝试将 Python 移动至 `$Env:COMFYUI_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:COMFYUI_INSTALLER_ROOT/python`" `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Python 路径移动成功`" } else { Print-Msg `"Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境`" Print-Msg `"请关闭所有占用 Python 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 ComfyUI Installer 修复环境`" } } if (!(Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/git/bin/git.exe`")) { if (Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/git`") { Print-Msg `"尝试将 Git 移动至 `$Env:COMFYUI_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:COMFYUI_INSTALLER_ROOT/git`" `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Git 路径移动成功`" } else { Print-Msg `"Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境`" Print-Msg `"请关闭所有占用 Git 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 ComfyUI Installer 修复环境`" } } Print-Msg `"检查绘世启动器运行环境结束`" } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:COMFYUI_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 ComfyUI Installer 内置命令 function global:List-CMD { Write-Host `" ================================== ComfyUI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 ComfyUI Installer 内置命令: Update-uv Update-Aria2 Check-ComfyUI-Installer-Update Test-Github-Mirror Install-ComfyUI-Node Git-Clone Install-Hanamizuki List-Node Get-Core-Prefix List-CMD 更多帮助信息可在 ComfyUI Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md `" } # 显示 ComfyUI Installer 版本 function Get-ComfyUI-Installer-Version { `$ver = `$([string]`$Env:COMFYUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"ComfyUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror, 命令行参数 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror Set-Github-Mirror PyPI-Mirror-Status if (Test-Path `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$Env:COMFYUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`" } Print-Msg `"激活 ComfyUI Env`" Print-Msg `"更多帮助信息可在 ComfyUI Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activate.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[ComfyUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 ComfyUI Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== ComfyUI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 ComfyUI 的简单使用文档。 使用 ComfyUI Installer 进行安装并安装成功后,将在当前目录生成 ComfyUI 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - launch.ps1:启动 ComfyUI。 - update.ps1:更新 ComfyUI。 - update_node.ps1:更新 ComfyUI 自定义节点。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 ComfyUI 的模型文件夹中。 - reinstall_pytorch.ps1:重新安装 PyTorch 的脚本,在 PyTorch 出问题或者需要切换 PyTorch 版本时可使用。 - settings.ps1:管理 ComfyUI Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、Git 的命令 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - launch_comfyui_installer.ps1:获取最新的 ComfyUI Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - ComfyUI / core:ComfyUI 内核。 详细的 ComfyUI Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md ComfyUI 的使用教程: https://sdnote.netlify.app/guide/comfyui https://sdnote.netlify.app/help/comfyui https://docs.comfy.org/zh-CN/get_started/first_generation https://www.aigodlike.com https://space.bilibili.com/35723238/channel/collectiondetail?sid=1320931 https://comfyanonymous.github.io/ComfyUI_examples https://blenderneko.github.io/ComfyUI-docs https://comfyui-wiki.com/zh ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one ComfyUI 项目地址:https://github.com/comfyanonymous/ComfyUI ==================================================================== ########## 用户协议 ########## 使用该软件代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Launch-Script Write-Update-Script Write-Update-Node-Script Write-Launch-ComfyUI-Install-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-ComfyUI-Installer-Settings-Script Write-Env-Activate-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script Write-Hanamizuki-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-ComfyUI-Installer-Config { Print-Msg "为 ComfyUI Installer 管理脚本复制 ComfyUI Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($DisableGithubMirror)) -and (Test-Path "$PSScriptRoot/disable_gh_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_gh_mirror.txt -> $InstallPath/disable_gh_mirror.txt" } elseif ((!($DisableGithubMirror)) -and (!($UseCustomGithubMirror)) -and (Test-Path "$PSScriptRoot/gh_mirror.txt") -and (!(Test-Path "$PSScriptRoot/disable_gh_mirror.txt"))) { Copy-Item -Path "$PSScriptRoot/gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/gh_mirror.txt -> $InstallPath/gh_mirror.txt" } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 写入启动绘世启动器脚本 function Write-Hanamizuki-Script { param ( [switch]$Force ) $content = " @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=ComfyUI if exist `"%~dp0%DefaultCorePrefix%`" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if `"%%i`"==`"-CorePrefix`" ( set NextIsValue=1 ) ) ) if exist `"%CorePrefixFile%`" ( for /f `"delims=`" %%i in ('powershell -command `"Get-Content -Path '%CorePrefixFile%'`"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f `"delims=`" %%i in ('powershell -command `"`$current_path = '%CurrentPath%'.Trim('/').Trim('\'); `$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix; `$from_uri = New-Object System.Uri(`$current_path.Replace('\', '/') + '/'); `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')); `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') }; Write-Host `$origin_core_prefix`"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist `"%RootPath%`" ( cd /d `"%RootPath%`" ) else ( echo %CorePrefix% not found echo Please check if ComfyUI is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d `"%CurrentPath%`" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d `"%CurrentPath%`" pause exit 1 ) ".Trim() if ((!($Force)) -and (!(Test-Path "$InstallPath/hanamizuki.bat"))) { return } if (Test-Path "$InstallPath/hanamizuki.bat") { Print-Msg "更新 hanamizuki.bat 中" } else { Print-Msg "生成 hanamizuki.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/hanamizuki.bat" -Value $content } # 安装绘世启动器 function Install-Hanamizuki { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe", "https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe", "https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe" ) $i = 0 if (!($InstallHanamizuki)) { return } New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null if (Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe") { Print-Msg "绘世启动器已安装, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" } else { ForEach ($url in $urls) { Print-Msg "下载绘世启动器中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/hanamizuki_tmp.exe" Move-Item -Path "$Env:CACHE_HOME/hanamizuki_tmp.exe" "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe" -Force Print-Msg "绘世启动器安装成功, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载绘世启动器中" } else { Print-Msg "下载绘世启动器失败" return } } } } } # 配置绘世启动器运行环境 function Configure-Hanamizuki-Env { if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe")) { return } Write-Hanamizuki-Script -Force Print-Msg "检查绘世启动器运行环境" if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { if (Test-Path "$InstallPath/python") { Print-Msg "尝试将 Python 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/python" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Python 路径移动成功" } else { Print-Msg "Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境" Print-Msg "请关闭所有占用 Python 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 ComfyUI Installer 修复环境" } } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { if (Test-Path "$InstallPath/git") { Print-Msg "尝试将 Git 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/git" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Git 路径移动成功" } else { Print-Msg "Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境" Print-Msg "请关闭所有占用 Git 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 ComfyUI Installer 修复环境" } } Print-Msg "检查绘世启动器运行环境结束" } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 ComfyUI 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 ComfyUI Installer, 更多的说明请阅读 ComfyUI Installer 使用文档" Print-Msg "ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-ComfyUI-Installer-Config if ($BuildMode) { Use-Build-Mode Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "ComfyUI 环境构建完成, 路径: $InstallPath" } else { Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "ComfyUI 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 ComfyUI 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 ComfyUI Installer 使用文档" Print-Msg "ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md" Print-Msg "退出 ComfyUI Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWithTorch", $BuildWithTorch) if ($BuildWithTorchReinstall) { $launch_args.Add("-BuildWithTorchReinstall", $true) } if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 ComfyUI 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithUpdateNode) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 ComfyUI 自定义节点更新脚本中" . "$InstallPath/update_node.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($LaunchArg) { $launch_args.Add("-LaunchArg", $LaunchArg) } if ($EnableShortcut) { $launch_args.Add("-EnableShortcut", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 ComfyUI 启动脚本中" . "$InstallPath/launch.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-ComfyUI-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 ComfyUI 的绝对路径>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-BuildMode] [-BuildWithUpdate] [-BuildWithUpdateNode] [-BuildWithLaunch] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-NoPreDownloadNode] [-NoPreDownloadModel] [-PyTorchPackage <PyTorch 软件包>] [-InstallHanamizuki] [-NoCleanCache] [-xFormersPackage <xFormers 软件包>] [-DisableUpdate] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-LaunchArg <ComfyUI 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 ComfyUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -InstallPath <安装 ComfyUI 的绝对路径> 指定 ComfyUI Installer 安装 ComfyUI 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 ComfyUI Installer 安装 ComfyUI 到 D:\Donwload 这个路径 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -UseUpdateMode 指定 ComfyUI Installer 使用更新模式, 只对 ComfyUI Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 ComfyUI Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 ComfyUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 ComfyUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableGithubMirror 禁用 ComfyUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -BuildMode 启用 ComfyUI Installer 构建模式, 在基础安装流程结束后将调用 ComfyUI Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 ComfyUI Installer 的执行, 而是直接退出 当指定调用多个 ComfyUI Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorch, -BuildWithTorchReinstall 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - update_node.ps1 (对应 -BuildWithUpdateNode 参数) - launch.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 update.ps1 脚本, 更新 ComfyUI 内核 -BuildWithUpdateNode (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 update_node.ps1 脚本, 更新 ComfyUI 自定义节点 -BuildWithLaunch (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 launch.ps1 脚本, 执行启动 ComfyUI 前的环境检查流程, 但跳过启动 ComfyUI -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 ComfyUI Installer 构建模式, 并且添加 -BuildWithTorch) 在 ComfyUI Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 ComfyUI Installer 构建模式) ComfyUI Installer 执行完基础安装流程后调用 ComfyUI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -NoPreDownloadNode 安装 ComfyUI 时跳过安装 ComfyUI 扩展 -NoPreDownloadModel 安装 ComfyUI 时跳过预下载模型 -PyTorchPackage <PyTorch 软件包> (需要同时搭配 -xFormersPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 PyTorch 版本, 如 -PyTorchPackage `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" -xFormersPackage <xFormers 软件包> (需要同时搭配 -PyTorchPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 xFormers 版本, 如 -xFormersPackage `"xformers===0.0.26.post1+cu118`" -InstallHanamizuki 安装绘世启动器, 并生成 hanamizuki.bat 用于启动绘世启动器 -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 禁用 ComfyUI Installer 更新检查 -DisableHuggingFaceMirror (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -LaunchArg <ComfyUI 启动参数> (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 设置 ComfyUI 自定义启动参数, 如启用 --fast 和 --auto-launch, 则使用 -LaunchArg `"--fast --auto-launch`" 进行启用 -EnableShortcut (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 创建 ComfyUI 启动快捷方式 -DisableCUDAMalloc (仅在 ComfyUI Installer 构建模式下生效, 并且只作用于 ComfyUI Installer 管理脚本) 禁用 ComfyUI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 ComfyUI Installer 构建模式下生效, 且只作用于 ComfyUI Installer 管理脚本) 禁用 ComfyUI Installer 检查 ComfyUI 运行环境中存在的问题, 禁用后可能会导致 ComfyUI 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate (仅在 ComfyUI Installer 构建模式下生效, 且只作用于 ComfyUI Installer 管理脚本) 禁用 ComfyUI Installer 自动应用新版本更新 更多的帮助信息请阅读 ComfyUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/comfyui_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-ComfyUI-Installer-Version Get-ComfyUI-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "ComfyUI Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/comfyui_installer.ps1
PowerShell
agpl-3.0
606,440
@echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 "%SYSTEMROOT%\system32\icacls.exe" "%SYSTEMROOT%\system32\config\system" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" echo :: Executing vbs script echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs" "%temp%\getadmin.vbs" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" ) pushd "%CD%" CD /D "%~dp0" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: "Set-ExecutionPolicy Unrestricted -Scope CurrentUser" powershell "Set-ExecutionPolicy Unrestricted -Scope CurrentUser" echo :: Enable long paths supported echo :: Executing command: "New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force" powershell "New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force" echo :: Configure completed echo :: Exit environment configuration script pause
2301_81996401/sd-webui-all-in-one
installer/configure_env.bat
Batchfile
agpl-3.0
1,624
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "Fooocus"), [string]$PyTorchMirrorType, [string]$InstallBranch, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithLaunch, [int]$BuildWithTorch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [int]$BuildWitchBranch, [switch]$NoPreDownloadModel, [string]$PyTorchPackage, [string]$xFormersPackage, [switch]$InstallHanamizuki, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [string]$UseCustomHuggingFaceMirror, [string]$LaunchArg, [switch]$EnableShortcut, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("core", "Fooocus", "fooocus", "fooocus_portable") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "core" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # Fooocus Installer 版本和检查更新间隔 $FOOOCUS_INSTALLER_VERSION = 207 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_ADDR } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_FIND_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121/torch_stable.html" $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # Github 镜像源列表 $GITHUB_MIRROR_LIST = @( "https://ghfast.top/https://github.com", "https://mirror.ghproxy.com/https://github.com", "https://ghproxy.net/https://github.com", "https://gh.api.99988866.xyz/https://github.com", "https://gh-proxy.com/https://github.com", "https://ghps.cc/https://github.com", "https://gh.idayer.com/https://github.com", "https://ghproxy.1888866.xyz/github.com", "https://slink.ltd/https://github.com", "https://github.boki.moe/github.com", "https://github.moeyy.xyz/https://github.com", "https://gh-proxy.net/https://github.com", "https://gh-proxy.ygxz.in/https://github.com", "https://wget.la/https://github.com", "https://kkgithub.com", "https://gitclone.com/github.com" ) # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # Fooocus 仓库地址 $FOOOCUS_REPO = if ((Test-Path "$PSScriptRoot/install_fooocus.txt") -or ($InstallBranch -eq "fooocus")) { "https://github.com/lllyasviel/Fooocus" } elseif ((Test-Path "$PSScriptRoot/install_fooocus_mre.txt") -or ($InstallBranch -eq "fooocus_mre")) { "https://github.com/MoonRide303/Fooocus-MRE" } elseif ((Test-Path "$PSScriptRoot/install_ruined_fooocus.txt") -or ($InstallBranch -eq "ruined_fooocus")) { "https://github.com/runew0lf/RuinedFooocus" } else { "https://github.com/lllyasviel/Fooocus" } # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $PYTHON_SCRIPTS_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $GIT_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/git/bin" $Env:PATH = "$PYTHON_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_EXTRA_PATH$([System.IO.Path]::PathSeparator)$GIT_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[Fooocus Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { $ver = $([string]$FOOOCUS_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "Fooocus Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / -DisableUV, 命令行参数 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # Github 镜像测试 function Set-Github-Mirror { $Env:GIT_CONFIG_GLOBAL = "$InstallPath/.gitconfig" # 设置 Git 配置文件路径 if (Test-Path "$InstallPath/.gitconfig") { Remove-Item -Path "$InstallPath/.gitconfig" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory "*" git config --global core.longpaths true if ((Test-Path "$PSScriptRoot/disable_gh_mirror.txt") -or ($DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg "检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源" return } # 使用自定义 Github 镜像源 if ((Test-Path "$PSScriptRoot/gh_mirror.txt") -or ($UseCustomGithubMirror)) { if ($UseCustomGithubMirror) { $github_mirror = $UseCustomGithubMirror } else { $github_mirror = Get-Content "$PSScriptRoot/gh_mirror.txt" } git config --global url."$github_mirror".insteadOf "https://github.com" Print-Msg "检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源" return } # 自动检测可用镜像源并使用 $status = 0 ForEach($i in $GITHUB_MIRROR_LIST) { Print-Msg "测试 Github 镜像源: $i" if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } git clone "$i/licyk/empty" "$Env:CACHE_HOME/github-mirror-test" --quiet if ($?) { Print-Msg "该 Github 镜像源可用" $github_mirror = $i $status = 1 break } else { Print-Msg "镜像源不可用, 更换镜像源进行测试" } } if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } if ($status -eq 0) { Print-Msg "无可用 Github 镜像源, 取消使用 Github 镜像源" } else { Print-Msg "设置 Github 镜像源" git config --global url."$github_mirror".insteadOf "https://github.com" } } # Git 仓库下载 function Git-CLone { param ( [String]$url, [String]$path ) $name = [System.IO.Path]::GetFileNameWithoutExtension("$url") $folder_name = [System.IO.Path]::GetFileName("$path") Print-Msg "检测 $name 是否已安装" $status = 0 if (!(Test-Path "$path")) { $status = 1 } else { $items = Get-ChildItem "$path" if ($items.Count -eq 0) { $status = 1 } } if ($status -eq 1) { Print-Msg "正在下载 $name" $cache_path = "$Env:CACHE_HOME/${folder_name}_tmp" # 清理缓存路径 if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } git clone --recurse-submodules $url "$cache_path" if ($?) { # 检测是否下载成功 # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Print-Msg "$name 安装成功" } else { Print-Msg "$name 安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "$name 已安装" } } # 设置 PyTorch 镜像源 function Get-PyTorch-Mirror ($pytorch_package) { # 获取 PyTorch 的版本 $torch_part = @($pytorch_package -split ' ' | Where-Object { $_ -like "torch==*" })[0] if ($PyTorchMirrorType) { Print-Msg "使用指定的 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } elseif ($torch_part) { # 获取 PyTorch 镜像源类型 if ($torch_part.split("+") -eq $torch_part) { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' if __name__ == '__main__': print(get_pytorch_mirror_type('$torch_part', use_xpu=True)) ".Trim() $mirror_type = $(python -c "$content") } else { $mirror_type = $torch_part.Split("+")[-1] } Print-Msg "PyTorch 镜像源类型: $mirror_type" } else { Print-Msg "未获取到 PyTorch 版本, 无法确定镜像源类型, 可能导致 PyTorch 安装失败" $mirror_type = "null" } # 设置对应的镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 为 PyTorch 获取合适的 CUDA 版本类型 function Get-Appropriate-CUDA-Version-Type { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def select_avaliable_type() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() if compare_versions(cuda_support_ver, '13.0') >= 0: return 'cu130' elif compare_versions(cuda_support_ver, '12.9') >= 0: return 'cu129' elif compare_versions(cuda_support_ver, '12.8') >= 0: return 'cu128' elif compare_versions(cuda_support_ver, '12.6') >= 0: return 'cu126' elif compare_versions(cuda_support_ver, '12.4') >= 0: return 'cu124' elif compare_versions(cuda_support_ver, '12.1') >= 0: return 'cu121' elif compare_versions(cuda_support_ver, '11.8') >= 0: return 'cu118' elif compare_versions(cuda_comp_cap, '10.0') > 0: return 'cu128' # RTX 50xx elif compare_versions(cuda_comp_cap, '0.0') > 0: return 'cu118' # 其他 Nvidia 显卡 else: gpus = get_gpu_list() if any([ x for x in gpus if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): return 'xpu' if any([ x for x in gpus if 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): return 'cu118' return 'cpu' if __name__ == '__main__': print(select_avaliable_type()) ".Trim() return $(python -c "$content") } # 获取合适的 PyTorch / xFormers 版本 function Get-PyTorch-And-xFormers-Package { Print-Msg "设置 PyTorch 和 xFormers 版本" if ($PyTorchPackage) { # 使用自定义的 PyTorch / xFormers 版本 if ($xFormersPackage){ return $PyTorchPackage, $xFormersPackage } else { return $PyTorchPackage, $null } } if ($PyTorchMirrorType) { Print-Msg "根据 $PyTorchMirrorType 类型的 PyTorch 镜像源配置 PyTorch 组合" $appropriate_cuda_version = $PyTorchMirrorType } else { $appropriate_cuda_version = Get-Appropriate-CUDA-Version-Type } switch ($appropriate_cuda_version) { cu130 { $pytorch_package = "torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130" $xformers_package = "xformers==0.0.33" break } cu129 { $pytorch_package = "torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129" $xformers_package = "xformers==0.0.32.post2" break } cu128 { $pytorch_package = "torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128" $xformers_package = "xformers==0.0.33" break } cu126 { $pytorch_package = "torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126" $xformers_package = "xformers==0.0.33" break } cu124 { $pytorch_package = "torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124" $xformers_package = "xformers==0.0.29.post3" break } cu121 { $pytorch_package = "torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121" $xformers_package = "xformers===0.0.27" break } cu118 { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } xpu { $pytorch_package = "torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu" $xformers_package = $null break } cpu { $pytorch_package = "torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu" $xformers_package = $null break } Default { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } } return $pytorch_package, $xformers_package } # 安装 PyTorch function Install-PyTorch { $pytorch_package, $xformers_package = Get-PyTorch-And-xFormers-Package $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror $pytorch_package # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch: $pytorch_package" Print-Msg "将要安装的 xFormers: $xformers_package" Print-Msg "检测是否需要安装 PyTorch" python -m pip show torch --quiet 2> $null if (!($?)) { Print-Msg "安装 PyTorch 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() } } else { python -m pip install $pytorch_package.ToString().Split() } if ($?) { Print-Msg "PyTorch 安装成功" } else { Print-Msg "PyTorch 安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch 已安装, 无需再次安装" } Print-Msg "检测是否需要安装 xFormers" python -m pip show xformers --quiet 2> $null if (!($?)) { if ($xformers_package) { Print-Msg "安装 xFormers 中" if ($USE_UV) { uv pip install $xformers_package.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $xformers_package.ToString().Split() --no-deps } } else { python -m pip install $xformers_package.ToString().Split() --no-deps } if ($?) { Print-Msg "xFormers 安装成功" } else { Print-Msg "xFormers 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg "xFormers 已安装, 无需再次安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 Fooocus 依赖 function Install-Fooocus-Dependence { # 记录脚本所在路径 $current_path = $(Get-Location).ToString() Set-Location "$InstallPath/$Env:CORE_PREFIX" $dep_path = "$InstallPath/$Env:CORE_PREFIX/requirements_versions.txt" Print-Msg "安装 Fooocus 依赖中" if ($USE_UV) { uv pip install -r "$dep_path" if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install -r "$dep_path" } } else { python -m pip install -r "$dep_path" } if ($?) { Print-Msg "Fooocus 依赖安装成功" } else { Print-Msg "Fooocus 依赖安装失败, 终止 Fooocus 安装进程, 可尝试重新运行 Fooocus Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } Set-Location "$current_path" } # 模型下载器 function Model-Downloader ($download_list) { $sum = $download_list.Count for ($i = 0; $i -lt $download_list.Count; $i++) { $content = $download_list[$i] $url = $content[0] $path = $content[1] $file = $content[2] $model_full_path = Join-Path -Path $path -ChildPath $file if (Test-Path $model_full_path) { Print-Msg "[$($i + 1)/$sum] $file 模型已存在于 $path 中" } else { Print-Msg "[$($i + 1)/$sum] 下载 $file 模型到 $path 中" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M $url -d "$path" -o "$file" if ($?) { Print-Msg "[$($i + 1)/$sum] $file 下载成功" } else { Print-Msg "[$($i + 1)/$sum] $file 下载失败" } } } } # 更新 Fooocus 预设文件 function Update-Fooocus-Preset { $fooocus_preset_json_content = @{ "default_model" = "Illustrious-XL-v1.0.safetensors" "default_refiner" = "None" "default_refiner_switch" = 0.8 "default_loras" = @( @("None", 1.0), @("None", 1.0), @("None", 1.0), @("None", 1.0), @("None", 1.0) ) "default_cfg_scale" = 5.0 "default_sample_sharpness" = 2.0 "default_sampler" = "euler_ancestral" "default_scheduler" = "sgm_uniform" "default_performance" = "Speed" "default_prompt" = "`nmasterpiece,best quality,newest," "default_prompt_negative" = "low quality,worst quality,normal quality,text,signature,jpeg artifacts,bad anatomy,old,early,copyright name,watermark,artist name,signature," "default_styles" = @() "default_image_number" = 1 "default_aspect_ratio" = "1344*1008" "checkpoint_downloads" = @{ "Illustrious-XL-v1.0.safetensors" = "https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors" } "embeddings_downloads" = @{} "lora_downloads" = @{} "available_aspect_ratios" = @( "704*1408", "704*1344", "768*1344", "768*1280", "832*1216", "1216*832", "832*1152", "896*1152", "896*1088", "960*1088", "960*1024", "1024*1024", "1024*960", "1088*960", "1088*896", "1152*896", "1152*832", "1216*832", "1280*768", "1344*768", "1344*704", "1408*704", "1472*704", "1536*640", "1600*640", "1664*576", "1728*576", "1920*1080", "1080*1920", "576*1024", "768*1024", "1024*576", "1024*768", "1024*1024", "2048*2048", "1536*864", "864*1536", "1472*828", "828*1472", "1344*756", "756*1344", "1344*1008", "1008*1344", "1536*1152", "1152*1536", "1472*1104", "1104*1472", "1920*640", "1920*824", "824*1920", "1920*768", "1536*768", "1488*640", "1680*720" ) "default_save_metadata_to_images" = $true "default_metadata_scheme" = "a1111" "default_clip_skip" = 2 "default_black_out_nsfw" = $false "metadata_created_by" = "Fooocus" "default_developer_debug_mode_checkbox" = $true "default_describe_apply_prompts_checkbox" = $false "default_describe_content_type" = @( "Art/Anime" ) } $fooocus_language_zh_json_content = @{ "Preview" = "预览" "Gallery" = "相册" "Generate" = "生成" "Skip" = "跳过" "Stop" = "停止" "Input Image" = "图生图" "Advanced" = "高级设置" "Upscale or Variation" = "放大或重绘" "Image Prompt" = "参考图" "Inpaint or Outpaint (beta)" = "内部重绘或外部扩展(测试版)" "Drag above image to here" = "将图像拖到这里" "Upscale or Variation:" = "放大或重绘:" "Disabled" = "禁用" "Vary (Subtle)" = "变化(微妙)" "Vary (Strong)" = "变化(强烈)" "Upscale (1.5x)" = "放大(1.5 倍)" "Upscale (2x)" = "放大(2 倍)" "Upscale (Fast 2x)" = "快速放大(2 倍)" "📔 Document" = "📔 说明文档" "Image" = "图像" "Stop At" = "停止于" "Weight" = "权重" "Type" = "类型" "PyraCanny" = "边缘检测" "CPDS" = "深度结构检测" "* `"Image Prompt`" is powered by Fooocus Image Mixture Engine (v1.0.1)." = "* `“图生图`”由 Fooocus 图像混合引擎提供支持(v1.0.1)。" "The scaler multiplied to positive ADM (use 1.0 to disable)." = "正向 ADM 的缩放倍数(使用 1.0 禁用)。" "The scaler multiplied to negative ADM (use 1.0 to disable)." = "反向 ADM 的缩放倍数(使用 1.0 禁用)。" "When to end the guidance from positive/negative ADM." = "何时结束来自正向 / 反向 ADM 的指导。" "Similar to the Control Mode in A1111 (use 0.0 to disable)." = "类似于 SD WebUI 中的控制模式(使用 0.0 禁用)。" "Outpaint Expansion (" = "外部扩展 (" "Outpaint" = "外部重绘" "Left" = "向左扩展" "Right" = "向右扩展" "Top" = "向上扩展" "Bottom" = "向下扩展" "* `"Inpaint or Outpaint`" is powered by the sampler `"DPMPP Fooocus Seamless 2M SDE Karras Inpaint Sampler`" (beta)" = "* `“内部填充或外部填充`”由`“DPMPP Fooocus Seamless 2M SDE Karras Inpaint Sampler`”(测试版)采样器提供支持" "Setting" = "设置" "Style" = "样式" "Performance" = "性能" "Speed" = "均衡" "Quality" = "质量" "Extreme Speed" = "LCM 加速" "Lightning" = "SDXL Lightning 加速" "Hyper-SD" = "Hyper SD 加速" "Aspect Ratios" = "宽高比" "896×1152" = "896×1152" "width × height" = "宽 × 高" "704×1408" = "704×1408" "704×1344" = "704×1344" "768×1344" = "768×1344" "768×1280" = "768×1280" "832×1216" = "832×1216" "832×1152" = "832×1152" "896×1088" = "896×1088" "960×1088" = "960×1088" "960×1024" = "960×1024" "1024×1024" = "1024×1024" "1024×960" = "1024×960" "1088×960" = "1088×960" "1088×896" = "1088×896" "1152×832" = "1152×832" "1216×832" = "1216×832" "1280×768" = "1280×768" "1344×768" = "1344×768" "1344×704" = "1344×704" "1408×704" = "1408×704" "1472×704" = "1472×704" "1536×640" = "1536×640" "1600×640" = "1600×640" "1664×576" = "1664×576" "1728×576" = "1728×576" "Image Number" = "出图数量" "Negative Prompt" = "反向提示词" "Describing what you do not want to see." = "描述你不想看到的内容。" "Random" = "随机种子" "Seed" = "种子" "📚 History Log" = "📚 历史记录" "Image Style" = "图像风格" "Fooocus V2" = "Fooocus V2 风格" "Default (Slightly Cinematic)" = "默认(轻微的电影感)" "Fooocus Masterpiece" = "Fooocus - 杰作" "Random Style" = "随机风格" "Fooocus Photograph" = "Fooocus - 照片" "Fooocus Negative" = "Fooocus - 反向提示词" "SAI 3D Model" = "SAI - 3D模型" "SAI Analog Film" = "SAI - 模拟电影" "SAI Anime" = "SAI - 动漫" "SAI Cinematic" = "SAI - 电影片段" "SAI Comic Book" = "SAI - 漫画" "SAI Craft Clay" = "SAI - 工艺粘土" "SAI Digital Art" = "SAI - 数字艺术" "SAI Enhance" = "SAI - 增强" "SAI Fantasy Art" = "SAI - 奇幻艺术" "SAI Isometric" = "SAI - 等距风格" "SAI Line Art" = "SAI - 线条艺术" "SAI Lowpoly" = "SAI - 低多边形" "SAI Neonpunk" = "SAI - 霓虹朋克" "SAI Origami" = "SAI - 折纸" "SAI Photographic" = "SAI - 摄影" "SAI Pixel Art" = "SAI - 像素艺术" "SAI Texture" = "SAI - 纹理" "MRE Cinematic Dynamic" = "MRE - 史诗电影" "MRE Spontaneous Picture" = "MRE - 自发图片" "MRE Artistic Vision" = "MRE - 艺术视觉" "MRE Dark Dream" = "MRE - 黑暗梦境" "MRE Gloomy Art" = "MRE - 阴郁艺术" "MRE Bad Dream" = "MRE - 噩梦" "MRE Underground" = "MRE - 阴森地下" "MRE Surreal Painting" = "MRE - 超现实主义绘画" "MRE Dynamic Illustration" = "MRE - 动态插画" "MRE Undead Art" = "MRE - 遗忘艺术家作品" "MRE Elemental Art" = "MRE - 元素艺术" "MRE Space Art" = "MRE - 空间艺术" "MRE Ancient Illustration" = "MRE - 古代插图" "MRE Brave Art" = "MRE - 勇敢艺术" "MRE Heroic Fantasy" = "MRE - 英雄幻想" "MRE Dark Cyberpunk" = "MRE - 黑暗赛博朋克" "MRE Lyrical Geometry" = "MRE - 抒情几何抽象画" "MRE Sumi E Symbolic" = "MRE - 墨绘长笔画" "MRE Sumi E Detailed" = "MRE - 精细墨绘画" "MRE Manga" = "MRE - 日本漫画" "MRE Anime" = "MRE - 日本动画片" "MRE Comic" = "MRE - 成人漫画书插画" "Ads Advertising" = "广告 - 广告" "Ads Automotive" = "广告 - 汽车" "Ads Corporate" = "广告 - 企业品牌" "Ads Fashion Editorial" = "广告 - 时尚编辑" "Ads Food Photography" = "广告 - 美食摄影" "Ads Gourmet Food Photography" = "广告 - 美食摄影" "Ads Luxury" = "广告 - 奢侈品" "Ads Real Estate" = "广告 - 房地产" "Ads Retail" = "广告 - 零售" "Artstyle Abstract" = "艺术风格 - 抽象" "Artstyle Abstract Expressionism" = "艺术风格 - 抽象表现主义" "Artstyle Art Deco" = "艺术风格 - 装饰艺术" "Artstyle Art Nouveau" = "艺术风格 - 新艺术" "Artstyle Constructivist" = "艺术风格 - 构造主义" "Artstyle Cubist" = "艺术风格 - 立体主义" "Artstyle Expressionist" = "艺术风格 - 表现主义" "Artstyle Graffiti" = "艺术风格 - 涂鸦" "Artstyle Hyperrealism" = "艺术风格 - 超写实主义" "Artstyle Impressionist" = "艺术风格 - 印象派" "Artstyle Pointillism" = "艺术风格 - 点彩派" "Artstyle Pop Art" = "艺术风格 - 波普艺术" "Artstyle Psychedelic" = "艺术风格 - 迷幻" "Artstyle Renaissance" = "艺术风格 - 文艺复兴" "Artstyle Steampunk" = "艺术风格 - 蒸汽朋克" "Artstyle Surrealist" = "艺术风格 - 超现实主义" "Artstyle Typography" = "艺术风格 - 字体设计" "Artstyle Watercolor" = "艺术风格 - 水彩" "Futuristic Biomechanical" = "未来主义 - 生物机械" "Futuristic Biomechanical Cyberpunk" = "未来主义 - 生物机械 - 赛博朋克" "Futuristic Cybernetic" = "未来主义 - 人机融合" "Futuristic Cybernetic Robot" = "未来主义 - 人机融合 - 机器人" "Futuristic Cyberpunk Cityscape" = "未来主义 - 赛博朋克城市" "Futuristic Futuristic" = "未来主义 - 未来主义" "Futuristic Retro Cyberpunk" = "未来主义 - 复古赛博朋克" "Futuristic Retro Futurism" = "未来主义 - 复古未来主义" "Futuristic Sci Fi" = "未来主义 - 科幻" "Futuristic Vaporwave" = "未来主义 - 蒸汽波" "Game Bubble Bobble" = "游戏 - 泡泡龙" "Game Cyberpunk Game" = "游戏 - 赛博朋克游戏" "Game Fighting Game" = "游戏 - 格斗游戏" "Game Gta" = "游戏 - 侠盗猎车手" "Game Mario" = "游戏 - 马里奥" "Game Minecraft" = "游戏 - 我的世界" "Game Pokemon" = "游戏 - 宝可梦" "Game Retro Arcade" = "游戏 - 复古街机" "Game Retro Game" = "游戏 - 复古游戏" "Game Rpg Fantasy Game" = "游戏 - 角色扮演幻想游戏" "Game Strategy Game" = "游戏 - 策略游戏" "Game Streetfighter" = "游戏 - 街头霸王" "Game Zelda" = "游戏 - 塞尔达传说" "Misc Architectural" = "其他 - 建筑" "Misc Disco" = "其他 - 迪斯科" "Misc Dreamscape" = "其他 - 梦境" "Misc Dystopian" = "其他 - 反乌托邦" "Misc Fairy Tale" = "其他 - 童话故事" "Misc Gothic" = "其他 - 哥特风" "Misc Grunge" = "其他 - 垮掉的" "Misc Horror" = "其他 - 恐怖" "Misc Kawaii" = "其他 - 可爱" "Misc Lovecraftian" = "其他 - 洛夫克拉夫特" "Misc Macabre" = "其他 - 恐怖" "Misc Manga" = "其他 - 漫画" "Misc Metropolis" = "其他 - 大都市" "Misc Minimalist" = "其他 - 极简主义" "Misc Monochrome" = "其他 - 单色" "Misc Nautical" = "其他 - 航海" "Misc Space" = "其他 - 太空" "Misc Stained Glass" = "其他 - 彩色玻璃" "Misc Techwear Fashion" = "其他 - 科技时尚" "Misc Tribal" = "其他 - 部落" "Misc Zentangle" = "其他 - 禅绕画" "Papercraft Collage" = "手工艺 - 拼贴" "Papercraft Flat Papercut" = "手工艺 - 平面剪纸" "Papercraft Kirigami" = "手工艺 - 切纸" "Papercraft Paper Mache" = "手工艺 - 纸浆塑造" "Papercraft Paper Quilling" = "手工艺 - 纸艺卷轴" "Papercraft Papercut Collage" = "手工艺 - 剪纸拼贴" "Papercraft Papercut Shadow Box" = "手工艺 - 剪纸影箱" "Papercraft Stacked Papercut" = "手工艺 - 层叠剪纸" "Papercraft Thick Layered Papercut" = "手工艺 - 厚层剪纸" "Photo Alien" = "摄影 - 外星人" "Photo Film Noir" = "摄影 - 黑色电影" "Photo Glamour" = "摄影 - 魅力" "Photo Hdr" = "摄影 - 高动态范围" "Photo Iphone Photographic" = "摄影 - 苹果手机摄影" "Photo Long Exposure" = "摄影 - 长曝光" "Photo Neon Noir" = "摄影 - 霓虹黑色" "Photo Silhouette" = "摄影 - 轮廓" "Photo Tilt Shift" = "摄影 - 移轴" "Cinematic Diva" = "电影女主角" "Abstract Expressionism" = "抽象表现主义" "Academia" = "学术" "Action Figure" = "动作人偶" "Adorable 3D Character" = "可爱的3D角色" "Adorable Kawaii" = "可爱的卡哇伊" "Art Deco" = "装饰艺术" "Art Nouveau" = "新艺术,美丽艺术" "Astral Aura" = "星体光环" "Avant Garde" = "前卫" "Baroque" = "巴洛克" "Bauhaus Style Poster" = "包豪斯风格海报" "Blueprint Schematic Drawing" = "蓝图示意图" "Caricature" = "漫画" "Cel Shaded Art" = "卡通渲染" "Character Design Sheet" = "角色设计表" "Classicism Art" = "古典主义艺术" "Color Field Painting" = "色彩领域绘画" "Colored Pencil Art" = "彩色铅笔艺术" "Conceptual Art" = "概念艺术" "Constructivism" = "建构主义" "Cubism" = "立体主义" "Dadaism" = "达达主义" "Dark Fantasy" = "黑暗奇幻" "Dark Moody Atmosphere" = "黑暗忧郁气氛" "Dmt Art Style" = "迷幻艺术风格" "Doodle Art" = "涂鸦艺术" "Double Exposure" = "双重曝光" "Dripping Paint Splatter Art" = "滴漆飞溅艺术" "Expressionism" = "表现主义" "Faded Polaroid Photo" = "褪色的宝丽来照片" "Fauvism" = "野兽派" "Flat 2d Art" = "平面 2D 艺术" "Fortnite Art Style" = "堡垒之夜艺术风格" "Futurism" = "未来派" "Glitchcore" = "故障核心" "Glo Fi" = "光明高保真" "Googie Art Style" = "古吉艺术风格" "Graffiti Art" = "涂鸦艺术" "Harlem Renaissance Art" = "哈莱姆文艺复兴艺术" "High Fashion" = "高级时装" "Idyllic" = "田园诗般" "Impressionism" = "印象派" "Infographic Drawing" = "信息图表绘图" "Ink Dripping Drawing" = "滴墨绘画" "Japanese Ink Drawing" = "日式水墨画" "Knolling Photography" = "规律摆放摄影" "Light Cheery Atmosphere" = "轻松愉快的气氛" "Logo Design" = "标志设计" "Luxurious Elegance" = "奢华优雅" "Macro Photography" = "微距摄影" "Mandola Art" = "曼陀罗艺术" "Marker Drawing" = "马克笔绘图" "Medievalism" = "中世纪主义" "Minimalism" = "极简主义" "Neo Baroque" = "新巴洛克" "Neo Byzantine" = "新拜占庭" "Neo Futurism" = "新未来派" "Neo Impressionism" = "新印象派" "Neo Rococo" = "新洛可可" "Neoclassicism" = "新古典主义" "Op Art" = "欧普艺术" "Ornate And Intricate" = "华丽而复杂" "Pencil Sketch Drawing" = "铅笔素描" "Pop Art 2" = "流行艺术2" "Rococo" = "洛可可" "Silhouette Art" = "剪影艺术" "Simple Vector Art" = "简单矢量艺术" "Sketchup" = "草图" "Steampunk 2" = "赛博朋克2" "Surrealism" = "超现实主义" "Suprematism" = "至上主义" "Terragen" = "地表风景" "Tranquil Relaxing Atmosphere" = "宁静轻松的氛围" "Sticker Designs" = "贴纸设计" "Vibrant Rim Light" = "生动的边缘光" "Volumetric Lighting" = "体积照明" "Watercolor 2" = "水彩2" "Whimsical And Playful" = "异想天开、俏皮" "Fooocus Cinematic" = "Fooocus - 电影" "Fooocus Enhance" = "Fooocus - 增强" "Fooocus Sharp" = "Fooocus - 锐化" "Mk Chromolithography" = "MK - 彩色平版印刷" "Mk Cross Processing Print" = "MK - 交叉处理" "Mk Dufaycolor Photograph" = "MK - 杜菲色" "Mk Herbarium" = "MK - 标本" "Mk Punk Collage" = "MK - 拼贴朋克" "Mk Mosaic" = "MK - 马赛克" "Mk Van Gogh" = "MK - 梵高" "Mk Coloring Book" = "MK - 简笔画" "Mk Singer Sargent" = "MK - 辛格·萨金特" "Mk Pollock" = "MK - 波洛克" "Mk Basquiat" = "MK - 巴斯奇亚" "Mk Andy Warhol" = "MK - 安迪·沃霍尔" "Mk Halftone Print" = "MK - 半色调" "Mk Gond Painting" = "MK - 贡德艺术" "Mk Albumen Print" = "MK - 蛋白银印相" "Mk Inuit Carving" = "MK - 因纽特雕塑艺术" "Mk Bromoil Print" = "MK - 溴油印" "Mk Calotype Print" = "MK - 卡洛型" "Mk Color Sketchnote" = "MK - 涂鸦" "Mk Cibulak Porcelain" = "MK - 蓝洋葱" "Mk Alcohol Ink Art" = "MK - 墨画" "Mk One Line Art" = "MK - 单线艺术" "Mk Blacklight Paint" = "MK - 黑白艺术" "Mk Carnival Glass" = "MK - 彩虹色玻璃" "Mk Cyanotype Print" = "MK - 蓝晒" "Mk Cross Stitching" = "MK - 十字绣" "Mk Encaustic Paint" = "MK - 热蜡画" "Mk Embroidery" = "MK - 刺绣" "Mk Gyotaku" = "MK - 鱼拓" "Mk Luminogram" = "MK - 发光图" "Mk Lite Brite Art" = "MK - 灯光创意" "Mk Mokume Gane" = "MK - 木目金" "Pebble Art" = "鹅卵石艺术" "Mk Palekh" = "MK - 缩影" "Mk Suminagashi" = "MK - 漂浮墨水" "Mk Scrimshaw" = "MK - 斯克林肖" "Mk Shibori" = "MK - 手工扎染" "Mk Vitreous Enamel" = "MK - 搪瓷" "Mk Ukiyo E" = "MK - 浮世绘" "Mk Vintage Airline Poster" = "MK - 复古艺术" "Mk Vintage Travel Poster" = "MK - 复古艺术旅行" "Mk Bauhaus Style" = "MK - 包豪斯设计风格" "Mk Afrofuturism" = "MK - 未来主义" "Mk Atompunk" = "MK - 原子朋克" "Mk Constructivism" = "MK - 建构" "Mk Chicano Art" = "MK - 奇卡诺艺术" "Mk De Stijl" = "MK - 荷兰风格" "Mk Dayak Art" = "MK - 达雅克艺术" "Mk Fayum Portrait" = "MK - 法尤姆风格" "Mk Illuminated Manuscript" = "MK - 泥金装饰手抄" "Mk Kalighat Painting" = "MK - 卡利加特绘画" "Mk Madhubani Painting" = "MK - 马杜巴尼艺术" "Mk Pictorialism" = "MK - 绘画摄影" "Mk Pichwai Painting" = "MK - 皮切瓦伊" "Mk Patachitra Painting" = "MK - 粘土艺术" "Mk Samoan Art Inspired" = "MK - 萨摩亚艺术" "Mk Tlingit Art" = "MK - 特林吉特艺术" "Mk Adnate Style" = "MK - 具象艺术" "Mk Ron English Style" = "MK - 罗恩·英格利斯" "Mk Shepard Fairey Style" = "MK - 街头艺术" "Fooocus Semi Realistic" = "Fooocus - 半现实风格" "Mk Anthotype Print" = "MK - 花汁印相" "Mk Aquatint Print" = "MK - 飞尘腐蚀版画" "Model" = "模型" "Base Model (SDXL only)" = "基础模型(只支持 SDXL)" "Refiner (SDXL or SD 1.5)" = "精修模型 (支持 SDXL 或 SD 1.5)" "None" = "无" "LoRAs" = "LoRAs 模型" "SDXL LoRA 1" = "SDXL LoRA 模型 1" "SDXL LoRA 2" = "SDXL LoRA 模型 2" "SDXL LoRA 3" = "SDXL LoRA 模型 3" "SDXL LoRA 4" = "SDXL LoRA 模型 4" "SDXL LoRA 5" = "SDXL LoRA 模型 5" "LoRA 1" = "LoRA 模型 1" "LoRA 2" = "LoRA 模型 2" "LoRA 3" = "LoRA 模型 3" "LoRA 4" = "LoRA 模型 4" "LoRA 5" = "LoRA 模型 5" "Refresh" = "Refresh" "🔄 Refresh All Files" = "🔄 刷新全部文件" "Sampling Sharpness" = "采样清晰度" "Higher value means image and texture are sharper." = "值越大,图像和纹理越清晰。" "Guidance Scale" = "提示词引导系数" "Higher value means style is cleaner, vivider, and more artistic." = "提示词作用的强度,值越大,风格越干净、生动、更具艺术感。" "Developer Debug Mode" = "开发者调试模式" "Developer Debug Tools" = "开发者调试工具" "Positive ADM Guidance Scaler" = "正向 ADM 引导系数" "The scaler multiplied to positive ADM (use 1.0 to disable). " = "正向 ADM 引导的倍率 (使用 1.0 以禁用)。 " "Negative ADM Guidance Scaler" = "负向 ADM 引导系数" "The scaler multiplied to negative ADM (use 1.0 to disable). " = "负向 ADM 引导的倍率(使用 1.0 以禁用)。 " "ADM Guidance End At Step" = "ADM 引导结束步长" "When to end the guidance from positive/negative ADM. " = "正向 / 负向 ADM 结束引导的时间。 " "Refiner swap method" = "Refiner 精炼模型交换方式" "joint" = "joint 联合" "separate" = "separate 分离" "CFG Mimicking from TSNR" = "从 TSNR 模拟 CFG" "Enabling Fooocus's implementation of CFG mimicking for TSNR (effective when real CFG > mimicked CFG)." = "启用 Fooocus 的 TSNR 模拟 CFG 的功能(当真实的 CFG 大于模拟的 CFG 时生效)。" "Sampler" = "采样器" "dpmpp_2m_sde_gpu" = "dpmpp_2m_sde_gpu" "Only effective in non-inpaint mode." = "仅在非重绘模式下有效。" "euler" = "euler" "euler_ancestral" = "euler_ancestral" "heun" = "heun" "dpm_2" = "dpm_2" "dpm_2_ancestral" = "dpm_2_ancestral" "lms" = "lms" "dpm_fast" = "dpm_fast" "dpm_adaptive" = "dpm_adaptive" "dpmpp_2s_ancestral" = "dpmpp_2s_ancestral" "dpmpp_sde" = "dpmpp_sde" "dpmpp_sde_gpu" = "dpmpp_sde_gpu" "dpmpp_2m" = "dpmpp_2m" "dpmpp_2m_sde" = "dpmpp_2m_sde" "dpmpp_3m_sde" = "dpmpp_3m_sde" "dpmpp_3m_sde_gpu" = "dpmpp_3m_sde_gpu" "ddpm" = "ddpm" "ddim" = "ddim" "uni_pc" = "uni_pc" "uni_pc_bh2" = "uni_pc_bh2" "Scheduler" = "调度器" "karras" = "karras" "Scheduler of Sampler." = "采样器的调度器。" "normal" = "normal" "exponential" = "exponential" "sgm_uniform" = "sgm_uniform" "simple" = "simple" "ddim_uniform" = "ddim_uniform" "Forced Overwrite of Sampling Step" = "强制覆盖采样步长" "Set as -1 to disable. For developer debugging." = "设为 -1 以禁用。用于开发者调试。" "Forced Overwrite of Refiner Switch Step" = "强制重写精炼器开关步数" "Forced Overwrite of Generating Width" = "强制覆盖生成宽度" "Set as -1 to disable. For developer debugging. Results will be worse for non-standard numbers that SDXL is not trained on." = "设为 -1 以禁用。用于开发者调试。对于 SDXL 没有训练过的非标准数字,结果会差。" "Forced Overwrite of Generating Height" = "强制覆盖生成高度" "Forced Overwrite of Denoising Strength of `"Vary`"" = "强制覆盖`“变化`”的去噪强度" "Set as negative number to disable. For developer debugging." = "设为负数以禁用。用于开发者调试。" "Forced Overwrite of Denoising Strength of `"Upscale`"" = "强制覆盖`“放大`”去噪强度" "Inpaint Engine" = "重绘引擎" "v1" = "v1" "Version of Fooocus inpaint model" = "重绘模型的版本选择" "v2.5" = "v2.5" "Control Debug" = "控制调试" "Debug Preprocessors" = "启用预处理器结果展示" "Mixing Image Prompt and Vary/Upscale" = "混合图生图和变化 / 放大" "Mixing Image Prompt and Inpaint" = "混合图生图和重绘" "Softness of ControlNet" = "ControlNet 控制权重" "Similar to the Control Mode in A1111 (use 0.0 to disable). " = "类似于 SD WebUI 中的控制模式(使用 0.0 来禁用)。 " "Canny" = "Canny 边缘检测算法" "Canny Low Threshold" = "Canny 最低阈值" "Canny High Threshold" = "Canny 最高阈值" "FreeU" = "FreeU 提示词精准性优化" "Enabled" = "启用" "B1" = "B1" "B2" = "B2" "S1" = "S1" "S2" = "S2" "Type prompt here." = "在这里输入反向提示词(请用英文逗号分隔)" "wheel" = "滚轮" "Zoom canvas" = "画布缩放" "Adjust brush size" = "调整笔刷尺寸" "Reset zoom" = "画布复位" "Fullscreen mode" = "全屏模式" "Move canvas" = "移动画布" "Overlap" = "图层重叠" "Preset" = "预设配置" "Output Format" = "图片保存格式" "Type prompt here or paste parameters." = "在这里输入提示词(请用英文逗号分隔)" "🔎 Type here to search styles ..." = "🔎 搜索风格预设 ..." "Image Sharpness" = "图像锐化" "Debug Tools" = "调试工具" "Control" = "ControlNet 设置" "See the results from preprocessors." = "显示预处理处理结果选项" "Do not preprocess images. (Inputs are already canny/depth/cropped-face/etc.)" = "不对图像进行预处理 (导入的图像要求是 边缘控制图 / 深度图 / 面部特征图 / 其他)" "Skip Preprocessors" = "禁用图片预处理" "Inpaint" = "重绘设置" "Debug Inpaint Preprocessing" = "启用重绘预处理功能调试" "Disable initial latent in inpaint" = "禁用在重绘中初始化潜空间" "Inpaint Denoising Strength" = "重绘幅度" "Same as the denoising strength in A1111 inpaint. Only used in inpaint, not used in outpaint. (Outpaint always use 1.0)" = "该选项和 A1111 SD WebUI 中重绘功能的重绘幅度相同。该选项仅应用于图生图重绘功能中,在文生图中该设置无效(在文生图中该值为 1.0)" "Inpaint Respective Field" = "重绘蒙版区域范围" "The area to inpaint. Value 0 is same as `"Only Masked`" in A1111. Value 1 is same as `"Whole Image`" in A1111. Only used in inpaint, not used in outpaint. (Outpaint always use 1.0)" = "调整重绘区域的范围。该值为 0 时和 A1111 SD WebUI 中`“重绘区域`”选项的`“仅蒙版区域`”的效果相同,为 1 时和`“整张图片`”效果相同。该选项仅应用于图生图重绘功能中,在文生图中该设置无效(在文生图中该值为 1.0)" "Mask Erode or Dilate" = "蒙版范围调整" "Positive value will make white area in the mask larger, negative value will make white area smaller.(default is 0, always process before any mask invert)" = "正值将使蒙版中的白色区域变大,负值将使白色区域变小。(默认值为 0,始终在任何蒙版反转之前进行处理)" "Enable Mask Upload" = "启用蒙版上传功能" "Invert Mask" = "反转蒙版(重绘非蒙版内容)" "ImagePrompt" = "图像作为提示次输入" "FaceSwap" = "面部更改" "Drag inpaint or outpaint image to here" = "导入需要重绘的图片" "Inpaint or Outpaint" = "图片重绘" "Method" = "功能" "Inpaint or Outpaint (default)" = "图片重绘(默认)" "Improve Detail (face, hand, eyes, etc.)" = "提升细节(面部,手,眼睛等)" "Modify Content (add objects, change background, etc.)" = "修改内容(添加对象、更改背景等)" "Outpaint Direction" = "图片扩充方向" "Additional Prompt Quick List" = "附加提示词快速添加列表" "Inpaint Additional Prompt" = "重绘附加提示词" "Describe what you want to inpaint." = "描述你想要重绘的" "* Powered by Fooocus Inpaint Engine" = "* 由 Fooocus 重绘引擎驱动" "Describe" = "图像提示词反推" "Drag any image to here" = "导入任意图片" "Content Type" = "图片内容种类" "Photograph" = "照片" "Art/Anime" = "画作 / 动漫图片" "Describe this Image into Prompt" = "反推图片的提示词" "Metadata" = "图片信息查看" "Drag any image generated by Fooocus here" = "导入由 Fooocus 生成的图片" "Apply Metadata" = "应用图片信息" "(Experimental) This may cause performance problems on some computers and certain internet conditions." = "(实验性)这可能会在某些计算机和某些互联网条件下导致性能问题。" "Generate Image Grid for Each Batch" = "为每个批次生成图像网格" "Disable preview during generation." = "在图片生成时禁用过程预览" "Disable Preview" = "禁用预览" "Disable intermediate results during generation, only show final gallery." = "在生成过程中禁用生成的中间结果,仅显示最终图库。" "Disable Intermediate Results" = "禁用中间生成结果" "Disable automatic seed increment when image number is > 1." = "当图片生成批次大于 1 时禁用种子增量" "Disable seed increment" = "禁用种子增量" "Read wildcards in order" = "按顺序读取通配符" "Adds parameters to generated images allowing manual regeneration." = "在生成的图片中添加元数据(提示词信息等)便于复现原图" "Save Metadata to Images" = "保存元数据到图像中" "Metadata Scheme" = "元数据格式" "Image Prompt parameters are not included. Use png and a1111 for compatibility with Civitai." = "使用默认设置时图片提示词参数不包括在内。使用 png 图片保存格式和 A1111 SD WebUI 的图片信息保存风格的图片更适合在 Civitai 进行分享。" "fooocus (json)" = "Fooocus 风格(json)" "a1111 (plain text)" = "A1111 SD WebUI 风格(纯文本)" "Refiner Switch At" = "Refind 切换时机" "Use 0.4 for SD1.5 realistic models; or 0.667 for SD1.5 anime models; or 0.8 for XL-refiners; or any value for switching two SDXL models." = "SD 1.5 真实模型使用 0.4,SD1.5 动漫模型为 0.667,XLRefind 机为 0.8,或用于切换两个 SDXL 模型的任何值。" "Waiting for task to start ..." = "等待任务开始 ..." "Connection errored out." = "连接超时" "Error" = "错误" "Loading..." = "加载中 ..." "Moving model to GPU ..." = "将模型移至 GPU ..." "Loading models ..." = "加载模型 ..." "VAE encoding ..." = "VAE 编码 ..." "Image processing ..." = "处理图像 ..." "Processing prompts ..." = "处理提示词 ..." "Download" = "下载" "Downloading control models ..." = "下载 ControlNet 模型 ..." "Loading control models ..." = "加载 ControlNet 模型 ..." "processing" = "处理中" "Downloading upscale models ..." = "下载放大模型 ..." "Downloading inpainter ..." = "下载重绘模型 ..." "Use via API" = "通过 API 调用" "Lost connection due to leaving page. Rejoining queue..." = "由于离开页面而失去连接。正在重新加入队列 ..." "Warning" = "警告" "Finished Images" = "已完成的图像" "On mobile, the connection can break if this tab is unfocused or the device sleeps, losing your position in queue." = "在移动端上,如果此选项卡无焦点或设备休眠,连接可能中断,从而失去队列中的位置。" "Initializing ..." = "初始化 ..." "Downloading LCM components ..." = "下载 LCM 组件 ..." "Downloading Lightning components ..." = "下载 Lightning 组件 ..." "Start drawing" = "开始涂鸦" "VAE Inpaint encoding ..." = "VAE 重绘编码 ..." "JSON.parse: unexpected character at line 2 column 1 of the JSON data" = "JSON 分析:JSON 数据中第 2 行第 1 列出现不期望字符" "API documentation" = "API 文档" "fn_index:" = "主要方法: " "Use the" = "使用" "Python library or the" = "Python 库或者" "Javascript package to query the demo via API." = "Javascript 包来查询演示 API。" "Unnamed Endpoints" = "未命名接口" "Return Type(s)" = "返回类型" "47 API endpoints" = "47 个 API 接口" "copy" = "复制" "copied!" = "已复制!" "JSON.parse: unexpected character at line 1 column 1 of the JSON data" = "JAVA 解析:JSON 数据第 1 行第 1 列出现意外字符" "Generate forever" = "无限生成" "Downloading Hyper-SD components ..." = "下载 Hyper SD 组件中 ..." "Inpaint brush color" = "重绘画笔颜色" "CLIP Skip" = "CLIP 跳过层数" "Bypass CLIP layers to avoid overfitting (use 1 to not skip any layers, 2 is recommended)." = "CLIP 跳过层数可避免过拟合的情况(使用 1 为不跳过任何层,2 为推荐值)" "VAE" = "VAE 模型" "Default (model)" = "默认(模型)" "Use black image if NSFW is detected." = "当检测到图片存在 NSFW 内容时将屏蔽图片" "Black Out NSFW" = "屏蔽 NSFW" "For images created by Fooocus" = "导入由 Fooocus 生成的图片" "- Zoom canvas" = " - 缩放画布" "- Adjust brush size" = " - 调整画笔大小" "- Undo last action" = "- 撤回上一次的操作" "- Reset zoom" = " - 重置缩放" "- Fullscreen mode" = " - 全屏模式" "- Move canvas" = " - 移动画布" "Image Size and Recommended Size" = "图片分辨率和推荐的生图分辨率" "Enhance" = "增强" "Enable" = "启用" "Detection prompt" = "检测提示词" "Use singular whenever possible" = "尽量使用单词进行描述" "Describe what you want to detect." = "描述你想要检测的。" "Detection Prompt Quick List" = "检测提示词快速选择列表" "Enhancement positive prompt" = "增强正面提示词" "Uses original prompt instead if empty." = "如果提示词为空,则使用原有的提示词。" "Enhancement negative prompt" = "增强负面提示词" "Uses original negative prompt instead if empty." = "如果提示词为空,则使用原有的负面提示词。" "Detection" = "检测" "Mask generation model" = "蒙版生成模型" "SAM Options" = "SAM 模型选项" "SAM model" = "SAM 模型" "Box Threshold" = "箱体阈值" "Text Threshold" = "文本阈值" "Maximum number of detections" = "检测最大数量" "Set to 0 to detect all" = "设置为 0 时检测所有" "Version of Fooocus inpaint model. If set, use performance Quality or Speed (no performance LoRAs) for best results." = "Fooocus 重绘模型的版本。如果已设置,在性能选项选择质量或者均衡(无加速 LoRA)以达到最佳效果。" "Positive value will make white area in the mask larger, negative value will make white area smaller. (default is 0, always processed before any mask invert)" = "该值为正值时会使遮罩中的白色区域变大,为负值时会使白色区域变小。(默认值为 0,并且在任何蒙版反转之前处理)" "#1" = "单元 1" "#2" = "单元 2" "#3" = "单元 3" "📔 Documentation" = "📔 文档" "Use with Enhance, skips image generation" = "使用增强功能后,跳过图像生成" "Settings" = "设置" "Styles" = "风格" "Fooocus Pony" = "Fooocus - 小马" "Models" = "模型" "Show enhance masks in preview and final results" = "在预览中展示增强蒙版和最后结果" "Debug Enhance Masks" = "启用增强蒙版调试" "Use GroundingDINO boxes instead of more detailed SAM masks" = "使用 GroundingDINO 箱体代替更多的细节 SAM 蒙版" "Debug GroundingDINO" = "启用 GroundingDINO 调试" "GroundingDINO Box Erode or Dilate" = "GroundingDINO 箱体侵蚀和扩张" "Enable Advanced Masking Features" = "启用高级蒙版特性" "Mask Upload" = "上传蒙版" "Invert Mask When Generating" = "在生成时反转蒙版" "Generate mask from image" = "为图像生成蒙版" "Order of Processing" = "处理顺序" "Use before to enhance small details and after to enhance large areas." = "在使用前可增强小细节,在使用后可增大面积。" "Before First Enhancement" = "在第一次增强前" "After Last Enhancement" = "在最后一次增强后" "Save only final enhanced image" = "仅保存最后一次增强后的图像" "Positive value will make white area in the mask larger, negative value will make white area smaller. (default is 0, processed before SAM)" = "该值为正值时会使遮罩中的白色区域变大,为负值时会使白色区域变小。(默认值为 0,并且在使用 SAM 之前处理)" "Apply Styles" = "应用风格预设" } # 创建一个不带 BOM 的 UTF-8 编码器 $utf8_encoding = New-Object System.Text.UTF8Encoding($false) $fooocus_preset_json_content = $fooocus_preset_json_content | ConvertTo-Json -Depth 4 $fooocus_language_zh_json_content = $fooocus_language_zh_json_content | ConvertTo-Json -Depth 4 Print-Msg "更新 Fooocus 预设文件" $stream_writer = [System.IO.StreamWriter]::new("$InstallPath/$Env:CORE_PREFIX/presets/fooocus_installer.json", $false, $utf8_encoding) $stream_writer.Write($fooocus_preset_json_content) $stream_writer.Close() Print-Msg "更新 Fooocus 翻译文件" $stream_writer = [System.IO.StreamWriter]::new("$InstallPath/$Env:CORE_PREFIX/language/zh.json", $false, $utf8_encoding) $stream_writer.Write($fooocus_language_zh_json_content) $stream_writer.Close() } # 安装 function Check-Install { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null Print-Msg "检测是否安装 Python" if ((Test-Path "$InstallPath/python/python.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } # 切换 uv 指定的 Python if (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe") { $Env:UV_PYTHON = "$InstallPath/$Env:CORE_PREFIX/python/python.exe" } Print-Msg "检测是否安装 Git" if ((Test-Path "$InstallPath/git/bin/git.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if ((Test-Path "$InstallPath/git/bin/aria2c.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/aria2c.exe")) { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Set-Github-Mirror # Fooocus 核心 Git-CLone "$FOOOCUS_REPO" "$InstallPath/$Env:CORE_PREFIX" Install-PyTorch Install-Fooocus-Dependence if (!(Test-Path "$InstallPath/launch_args.txt")) { Print-Msg "设置默认 Fooocus 启动参数" $content = "--language zh --preset fooocus_installer --disable-offload-from-vram --disable-analytics --always-download-new-model" Set-Content -Encoding UTF8 -Path "$InstallPath/launch_args.txt" -Value $content } Update-Fooocus-Preset if ($NoPreDownloadModel) { Print-Msg "检测到 -NoPreDownloadModel 命令行参数, 跳过下载模型" } else { Print-Msg "预下载模型中" $model_list = New-Object System.Collections.ArrayList $model_list.Add(@("https://modelscope.cn/models/licyks/fooocus-model/resolve/master/vae_approx/vaeapp_sd15.pth", "$InstallPath/$Env:CORE_PREFIX/models/vae_approx", "vaeapp_sd15.pth")) | Out-Null $model_list.Add(@("https://modelscope.cn/models/licyks/fooocus-model/resolve/master/vae_approx/xlvaeapp.pth", "$InstallPath/$Env:CORE_PREFIX/models/vae_approx", "xlvaeapp.pth")) | Out-Null $model_list.Add(@("https://modelscope.cn/models/licyks/fooocus-model/resolve/master/vae_approx/xl-to-v1_interposer-v4.0.safetensors", "$InstallPath/$Env:CORE_PREFIX/models/vae_approx", "xl-to-v1_interposer-v4.0.safetensors")) | Out-Null $model_list.Add(@("https://modelscope.cn/models/licyks/fooocus-model/resolve/master/prompt_expansion/fooocus_expansion/pytorch_model.bin", "$InstallPath/$Env:CORE_PREFIX/models/prompt_expansion/fooocus_expansion", "pytorch_model.bin")) | Out-Null $checkpoint_path = "$InstallPath/$Env:CORE_PREFIX/models/checkpoints" $url = "https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors" $name = Split-Path -Path $url -Leaf if ((!(Get-ChildItem -Path $checkpoint_path -Include "*.safetensors", "*.pth", "*.ckpt" -Recurse)) -or (Test-Path "$checkpoint_path/${name}.aria2")){ $model_list.Add(@("$url", "$checkpoint_path", "$name")) | Out-Null } Model-Downloader $model_list } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 启动脚本 function Write-Launch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableUV, [string]`$LaunchArg, [switch]`$EnableShortcut, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableUV] [-LaunchArg <Fooocus 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 Fooocus Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 Fooocus Installer 更新检查 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableUV 禁用 Fooocus Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -LaunchArg <Fooocus 启动参数> 设置 Fooocus 自定义启动参数, 如启用 --disable-offload-from-vram 和 --disable-analytics, 则使用 -LaunchArg ```"--disable-offload-from-vram --disable-analytics```" 进行启用 -EnableShortcut 创建 Fooocus 启动快捷方式 -DisableCUDAMalloc 禁用 Fooocus Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 Fooocus Installer 检查 Fooocus 运行环境中存在的问题, 禁用后可能会导致 Fooocus 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # Fooocus Installer 更新检测 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 Fooocus Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -le `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 Fooocus Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 Fooocus Installer 更新`" return } } else { Print-Msg `"检测到 Fooocus Installer 有新版本可用`" } Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # Fooocus 启动参数 function Get-Fooocus-Launch-Args { `$arguments = New-Object System.Collections.ArrayList if ((Test-Path `"`$PSScriptRoot/launch_args.txt`") -or (`$LaunchArg)) { if (`$LaunchArg) { `$launch_args = `$LaunchArg } else { `$launch_args = Get-Content `"`$PSScriptRoot/launch_args.txt`" } if (`$launch_args.Trim().Split().Length -le 1) { `$arguments = `$launch_args.Trim().Split() } else { `$arguments = [regex]::Matches(`$launch_args, '(`"[^`"]*`"|''[^'']*''|\S+)') | ForEach-Object { `$_.Value -replace '^[`"'']|[`"'']`$', '' } } Print-Msg `"检测到本地存在 launch_args.txt 启动参数配置文件 / -LaunchArg 命令行参数, 已读取该启动参数配置文件并应用启动参数`" Print-Msg `"使用的启动参数: `$arguments`" } return `$arguments } # 设置 Fooocus 的快捷启动方式 function Create-Fooocus-Shortcut { # 设置快捷方式名称 if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"lllyasviel/Fooocus`") -or (`$branch -eq `"lllyasviel/Fooocus.git`")) { `$filename = `"Fooocus`" } elseif ((`$branch -eq `"MoonRide303/Fooocus-MRE`") -or (`$branch -eq `"MoonRide303/Fooocus-MRE.git`")) { `$filename = `"Fooocus-MRE`" } elseif ((`$branch -eq `"runew0lf/RuinedFooocus`") -or (`$branch -eq `"runew0lf/RuinedFooocus.git`")) { `$filename = `"RuinedFooocus`" } else { `$filename = `"Fooocus`" } } else { `$filename = `"Fooocus`" } `$url = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/gradio_icon.ico`" `$shortcut_icon = `"`$PSScriptRoot/gradio_icon.ico`" if ((!(Test-Path `"`$PSScriptRoot/enable_shortcut.txt`")) -and (!(`$EnableShortcut))) { return } Print-Msg `"检测到 enable_shortcut.txt 配置文件 / -EnableShortcut 命令行参数, 开始检查 Fooocus 快捷启动方式中`" if (!(Test-Path `"`$shortcut_icon`")) { Print-Msg `"获取 Fooocus 图标中`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/gradio_icon.ico`" if (!(`$?)) { Print-Msg `"获取 Fooocus 图标失败, 无法创建 Fooocus 快捷启动方式`" return } } Print-Msg `"更新 Fooocus 快捷启动方式`" `$shell = New-Object -ComObject WScript.Shell `$desktop = [System.Environment]::GetFolderPath(`"Desktop`") `$shortcut_path = `"`$desktop\`$filename.lnk`" `$shortcut = `$shell.CreateShortcut(`$shortcut_path) `$shortcut.TargetPath = `"`$PSHome\powershell.exe`" `$launch_script_path = `$(Get-Item `"`$PSScriptRoot/launch.ps1`").FullName `$shortcut.Arguments = `"-ExecutionPolicy Bypass -File ```"`$launch_script_path```"`" `$shortcut.IconLocation = `$shortcut_icon # 保存到桌面 `$shortcut.Save() `$start_menu_path = `"`$Env:APPDATA/Microsoft/Windows/Start Menu/Programs`" `$taskbar_path = `"`$Env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar`" # 保存到开始菜单 Copy-Item -Path `"`$shortcut_path`" -Destination `"`$start_menu_path`" -Force # 固定到任务栏 # Copy-Item -Path `"`$shortcut_path`" -Destination `"`$taskbar_path`" -Force # `$shell = New-Object -ComObject Shell.Application # `$shell.Namespace([System.IO.Path]::GetFullPath(`$taskbar_path)).ParseName((Get-Item `$shortcut_path).Name).InvokeVerb('taskbarpin') } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 检查 Fooocus 依赖完整性 function Check-Fooocus-Requirements { `$content = `" import inspect import platform import re import os import sys import copy import logging import argparse import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--requirement-path```", type=_normalized_filepath, default=None, help=```"依赖文件路径```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"Requirement Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True def validate_requirements(requirement_path: str | Path) -> bool: ```"```"```"检测环境依赖是否完整 Args: requirement_path (str | Path): 依赖文件路径 Returns: bool: 如果有缺失依赖则返回````False```` ```"```"```" origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) for package in requires: if not is_package_installed(package): return False return True def main() -> None: requirement_path = COMMAND_ARGS.requirement_path if not os.path.isfile(requirement_path): logger.error(```"依赖文件未找到, 无法检查运行环境```") sys.exit(1) logger.debug(```"检测运行环境中```") print(validate_requirements(requirement_path)) logger.debug(```"环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 Fooocus 内核依赖完整性中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_fooocus_requirement.py`" -Value `$content `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements_versions.txt`" if (!(Test-Path `"`$dep_path`")) { `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements.txt`" } if (!(Test-Path `"`$dep_path`")) { Print-Msg `"未检测到 Fooocus 依赖文件, 跳过依赖完整性检查`" return } `$status = `$(python `"`$Env:CACHE_HOME/check_fooocus_requirement.py`" --requirement-path `"`$dep_path`") if (`$status -eq `"False`") { Print-Msg `"检测到 Fooocus 内核有依赖缺失, 安装 Fooocus 依赖中`" if (`$USE_UV) { uv pip install -r `"`$dep_path`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$dep_path`" } } else { python -m pip install -r `"`$dep_path`" } if (`$?) { Print-Msg `"Fooocus 依赖安装成功`" } else { Print-Msg `"Fooocus 依赖安装失败, 这将会导致 Fooocus 缺失依赖无法正常运行`" } } else { Print-Msg `"Fooocus 无缺失依赖`" } } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 Numpy 版本 function Check-Numpy-Version { `$content = `" import importlib.metadata from importlib.metadata import version try: ver = int(version('numpy').split('.')[0]) except: ver = -1 if ver > 1: print(True) else: print(False) `".Trim() Print-Msg `"检查 Numpy 版本中`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"检测到 Numpy 版本大于 1, 这可能导致部分组件出现异常, 尝试重装中`" if (`$USE_UV) { uv pip install `"numpy==1.26.4`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `"numpy==1.26.4`" } } else { python -m pip install `"numpy==1.26.4`" } if (`$?) { Print-Msg `"Numpy 重新安装成功`" } else { Print-Msg `"Numpy 重新安装失败, 这可能导致部分功能异常`" } } else { Print-Msg `"Numpy 无版本问题`" } } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 Fooocus 运行环境 function Check-Fooocus-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 Fooocus 运行环境检测, 这可能会导致 Fooocus 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 Fooocus 运行环境中`" } Check-Fooocus-Requirements Fix-PyTorch Check-Onnxruntime-GPU Check-Numpy-Version Check-MS-VCPP-Redistributable Print-Msg `"Fooocus 运行环境检查完成`" } # 设置 Fooocus 的 HuggingFace 镜像 function Get-Fooocus-HuggingFace-Mirror-Arg { `$hf_mirror_arg = New-Object System.Collections.ArrayList if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if (!((`$branch -eq `"lllyasviel/Fooocus`") -or (`$branch -eq `"lllyasviel/Fooocus.git`"))) { return `$hf_mirror_arg } } if ((!(Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`")) -and (!(`$DisableHuggingFaceMirror))) { `$hf_mirror_arg.Add(`"--hf-mirror`") | Out-Null `$hf_mirror_arg.Add(`"`$Env:HF_ENDPOINT`") | Out-Null } return `$hf_mirror_arg } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过 Fooocus Installer 更新检查`" } else { Check-Fooocus-Installer-Update } Set-HuggingFace-Mirror Set-uv PyPI-Mirror-Status if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Fooocus 是否已正确安装, 或者尝试运行 Fooocus Installer 进行修复`" Read-Host | Out-Null return } `$launch_args = Get-Fooocus-Launch-Args `$hf_mirror_arg = Get-Fooocus-HuggingFace-Mirror-Arg # 记录上次的路径 `$current_path = `$(Get-Location).ToString() Set-Location `"`$PSScriptRoot/`$Env:CORE_PREFIX`" Create-Fooocus-Shortcut Check-Fooocus-Env Set-PyTorch-CUDA-Memory-Alloc Print-Msg `"启动 Fooocus 中`" if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过启动 Fooocus`" } else { python launch.py `$launch_args `$hf_mirror_arg `$req = `$? if (`$req) { Print-Msg `"Fooocus 正常退出`" } else { Print-Msg `"Fooocus 出现异常, 已退出`" } Read-Host | Out-Null } Set-Location `"`$current_path`" } ################### Main ".Trim() if (Test-Path "$InstallPath/launch.ps1") { Print-Msg "更新 launch.ps1 中" } else { Print-Msg "生成 launch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 Fooocus Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 Fooocus Installer 更新检查 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 Fooocus Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # Fooocus Installer 更新检测 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 Fooocus Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -le `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 Fooocus Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 Fooocus Installer 更新`" return } } else { Print-Msg `"检测到 Fooocus Installer 有新版本可用`" } Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过 Fooocus Installer 更新检查`" } else { Check-Fooocus-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Fooocus 是否已正确安装, 或者尝试运行 Fooocus Installer 进行修复`" Read-Host | Out-Null return } Print-Msg `"拉取 Fooocus 更新内容中`" Fix-Git-Point-Off-Set `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$core_origin_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" fetch --recurse-submodules --all if (`$?) { Print-Msg `"应用 Fooocus 更新中`" `$commit_hash = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" reset --hard `"`$remote_branch`" --recurse-submodules `$core_latest_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$core_origin_ver -eq `$core_latest_ver) { Print-Msg `"Fooocus 已为最新版, 当前版本:`$core_origin_ver`" } else { Print-Msg `"Fooocus 更新成功, 版本:`$core_origin_ver -> `$core_latest_ver`" } } else { Print-Msg `"拉取 Fooocus 更新内容失败`" Print-Msg `"更新 Fooocus 失败, 请检查控制台日志。可尝试重新运行 Fooocus Installer 更新脚本进行重试`" } Print-Msg `"退出 Fooocus 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 分支切换脚本 function Write-Switch-Branch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWitchBranch, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchBranch <Fooocus 分支编号>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 Fooocus Installer 构建模式 -BuildWitchBranch <Fooocus 分支编号> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 switch_branch.ps1 脚本, 根据 Fooocus 分支编号切换到对应的 Fooocus 分支 Fooocus 分支编号可运行 switch_branch.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 Fooocus Installer 更新检查 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 Fooocus Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # Fooocus Installer 更新检测 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 Fooocus Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -le `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 Fooocus Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 Fooocus Installer 更新`" return } } else { Print-Msg `"检测到 Fooocus Installer 有新版本可用`" } Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 获取 Fooocus 分支 function Get-Fooocus-Branch { `$remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null) if (`$ref -eq `$null) { `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h`") } return `"`$(`$remote.Split(`"/`")[-2])/`$(`$remote.Split(`"/`")[-1]) `$([System.IO.Path]::GetFileName(`$ref))`" } # 切换 Fooocus 分支 function Switch-Fooocus-Branch (`$remote, `$branch, `$use_submod) { `$fooocus_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$preview_url = `$(git -C `"`$fooocus_path`" remote get-url origin) Set-Github-Mirror # 设置 Github 镜像源 Print-Msg `"Fooocus 远程源替换: `$preview_url -> `$remote`" git -C `"`$fooocus_path`" remote set-url origin `"`$remote`" # 替换远程源 # 处理 Git 子模块 if (`$use_submod) { Print-Msg `"更新 Fooocus 的 Git 子模块信息`" git -C `"`$fooocus_path`" submodule update --init --recursive } else { Print-Msg `"禁用 Fooocus 的 Git 子模块`" git -C `"`$fooocus_path`" submodule deinit --all -f } Print-Msg `"拉取 Fooocus 远程源更新`" git -C `"`$fooocus_path`" fetch # 拉取远程源内容 if (`$?) { if (`$use_submod) { Print-Msg `"清理原有的 Git 子模块`" git -C `"`$fooocus_path`" submodule deinit --all -f } Print-Msg `"切换 Fooocus 分支至 `$branch`" # 本地分支不存在时创建一个分支 git -C `"`$fooocus_path`" show-ref --verify --quiet `"refs/heads/`${branch}`" if (!(`$?)) { git -C `"`$fooocus_path`" branch `"`${branch}`" } git -C `"`$fooocus_path`" checkout `"`${branch}`" --force # 切换分支 Print-Msg `"应用 Fooocus 远程源的更新`" if (`$use_submod) { Print-Msg `"更新 Fooocus 的 Git 子模块信息`" git -C `"`$fooocus_path`" reset --hard `"origin/`$branch`" git -C `"`$fooocus_path`" submodule deinit --all -f git -C `"`$fooocus_path`" submodule update --init --recursive } if (`$use_submod) { git -C `"`$fooocus_path`" reset --recurse-submodules --hard `"origin/`$branch`" # 切换到最新的提交内容上 } else { git -C `"`$fooocus_path`" reset --hard `"origin/`$branch`" # 切换到最新的提交内容上 } Print-Msg `"切换 Fooocus 分支完成`" `$global:status = `$true } else { Print-Msg `"拉取 Fooocus 远程源更新失败, 取消分支切换`" Print-Msg `"尝试回退 Fooocus 的更改`" git -C `"`$fooocus_path`" remote set-url origin `"`$preview_url`" if (`$use_submod) { git -C `"`$fooocus_path`" submodule deinit --all -f } else { git -C `"`$fooocus_path`" submodule update --init --recursive } Print-Msg `"回退 Fooocus 分支更改完成`" Print-Msg `"切换 Fooocus 分支更改失败`" `$global:status = `$false } } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过 Fooocus Installer 更新检查`" } else { Check-Fooocus-Installer-Update } if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Fooocus 是否已正确安装, 或者尝试运行 Fooocus Installer 进行修复`" Read-Host | Out-Null return } `$content = `" ----------------------------------------------------- - 1、lllyasviel - Fooocus 分支 - 2、runew0lf - RuinedFooocus 分支 - 3、MoonRide303 - Fooocus-MRE 分支 ----------------------------------------------------- `".Trim() `$to_exit = 0 while (`$True) { Print-Msg `"Fooocus 分支列表`" `$go_to = 0 Write-Host `$content Print-Msg `"当前 Fooocus 分支: `$(Get-Fooocus-Branch)`" Print-Msg `"请选择 Fooocus 分支`" Print-Msg `"提示: 输入数字后回车, 或者输入 exit 退出 Fooocus 分支切换脚本`" if (`$BuildMode) { `$go_to = 1 `$arg = `$BuildWitchBranch } else { `$arg = (Read-Host `"========================================>`").Trim() } switch (`$arg) { 1 { `$remote = `"https://github.com/lllyasviel/Fooocus`" `$branch = `"main`" `$branch_name = `"lllyasviel - Fooocus 分支`" `$use_submod = `$false `$go_to = 1 } 2 { `$remote = `"https://github.com/runew0lf/RuinedFooocus`" `$branch = `"main`" `$branch_name = `"runew0lf - RuinedFooocus 分支`" `$use_submod = `$false `$go_to = 1 } 3 { `$remote = `"https://github.com/MoonRide303/Fooocus-MRE`" `$branch = `"moonride-main`" `$branch_name = `"MoonRide303 - Fooocus-MRE 分支`" `$use_submod = `$false `$go_to = 1 } exit { Print-Msg `"退出 Fooocus 分支切换脚本`" `$to_exit = 1 `$go_to = 1 } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否切换 Fooocus 分支到 `$branch_name ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$operate = `"yes`" } else { `$operate = (Read-Host `"========================================>`").Trim() } if (`$operate -eq `"yes`" -or `$operate -eq `"y`" -or `$operate -eq `"YES`" -or `$operate -eq `"Y`") { Print-Msg `"开始切换 Fooocus 分支`" Switch-Fooocus-Branch `$remote `$branch `$use_submod if (`$status) { Print-Msg `"切换 Fooocus 分支成功`" } else { Print-Msg `"切换 Fooocus 分支失败, 可尝试重新运行 Fooocus 分支切换脚本`" } } else { Print-Msg `"取消切换 Fooocus 分支`" } Print-Msg `"退出 Fooocus 分支切换脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/switch_branch.ps1") { Print-Msg "更新 switch_branch.ps1 中" } else { Print-Msg "生成 switch_branch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/switch_branch.ps1" -Value $content } # 获取安装脚本 function Write-Launch-Fooocus-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [string]`$InstallBranch, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 Fooocus Installer function Download-Fooocus-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 Fooocus Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/fooocus_installer.ps1`" if (`$?) { Print-Msg `"下载 Fooocus Installer 脚本成功`" break } else { Print-Msg `"下载 Fooocus Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Fooocus Installer 脚本`" } else { Print-Msg `"下载 Fooocus Installer 脚本失败, 可尝试重新运行 Fooocus Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { `$arg.Add(`"-DisableGithubMirror`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } `$arg.Add(`"-UseCustomGithubMirror`", `$github_mirror) } } if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"lllyasviel/Fooocus`") -or (`$branch -eq `"lllyasviel/Fooocus.git`")) { `$arg.Add(`"-InstallBranch`", `"fooocus`") } elseif ((`$branch -eq `"MoonRide303/Fooocus-MRE`") -or (`$branch -eq `"MoonRide303/Fooocus-MRE.git`")) { `$arg.Add(`"-InstallBranch`", `"fooocus_mre`") } elseif ((`$branch -eq `"runew0lf/RuinedFooocus`") -or (`$branch -eq `"runew0lf/RuinedFooocus.git`")) { `$arg.Add(`"-InstallBranch`", `"ruined_fooocus`") } } elseif ((Test-Path `"`$PSScriptRoot/install_fooocus.txt`") -or (`$InstallBranch -eq `"fooocus`")) { `$arg.Add(`"-InstallBranch`", `"fooocus`") } elseif ((Test-Path `"`$PSScriptRoot/install_fooocus_mre.txt`") -or (`$InstallBranch -eq `"fooocus_mre`")) { `$arg.Add(`"-InstallBranch`", `"fooocus_mre`") } elseif ((Test-Path `"`$PSScriptRoot/install_ruined_fooocus.txt`") -or (`$InstallBranch -eq `"ruined_fooocus`")) { `$arg.Add(`"-InstallBranch`", `"ruined_fooocus`") } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Set-Proxy `$status = Download-Fooocus-Installer if (`$status) { Print-Msg `"运行 Fooocus Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/fooocus_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 Fooocus Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_fooocus_installer.ps1") { Print-Msg "更新 launch_fooocus_installer.ps1 中" } else { Print-Msg "生成 launch_fooocus_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_fooocus_installer.ps1" -Value $content } # 重装 PyTorch 脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWithTorch, [switch]`$BuildWithTorchReinstall, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableUV, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-DisablePyPIMirror] [-DisableUpdate] [-DisableUV] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 Fooocus Installer 构建模式 -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 Fooocus Installer 构建模式, 并且添加 -BuildWithTorch) 在 Fooocus Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 Fooocus Installer 更新检查 -DisableUV 禁用 Fooocus Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableAutoApplyUpdate 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # Fooocus Installer 更新检测 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 Fooocus Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -le `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 Fooocus Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 Fooocus Installer 更新`" return } } else { Print-Msg `"检测到 Fooocus Installer 有新版本可用`" } Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 xFormers 版本 function Get-xFormers-Version { `$content = `" from importlib.metadata import version try: ver = version('xformers') except: ver = None print(ver) `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 获取驱动支持的最高 CUDA 版本 function Get-Drive-Support-CUDA-Version { Print-Msg `"获取显卡驱动支持的最高 CUDA 版本`" if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) { `$cuda_ver = `$(nvidia-smi -q | Select-String -Pattern 'CUDA Version\s*:\s*([\d.]+)').Matches.Groups[1].Value } else { `$cuda_ver = `"未知`" } return `$cuda_ver } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } return `$torch_ver, `$xformers_ver } # 获取 HashTable 的值 function Get-HashValue { param( [hashtable]`$Hashtable, [string]`$Key, [object]`$Default = `$null ) if (`$Hashtable.ContainsKey(`$Key)) { return `$Hashtable[`$Key] } else { return `$Default } } # 获取可用的 PyTorch 类型 function Get-Avaliable-PyTorch-Type { `$content = `" import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 CUDA_TYPE = [ 'cu113', 'cu117', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu129', 'cu130', ] def get_avaliable_device() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() device_list = ['cpu'] if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): device_list.append('xpu') if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): device_list.append('directml') if compare_versions(cuda_comp_cap, '10.0') > 0: for ver in CUDA_TYPE: if compare_versions(ver, str(int(12.8 * 10))) >= 0: device_list.append(ver) else: for ver in CUDA_TYPE: if compare_versions(ver, str(int(cuda_support_ver * 10))) <= 0: device_list.append(ver) return ','.join(list(set(device_list))) if __name__ == '__main__': print(get_avaliable_device()) `".Trim() Print-Msg `"获取可用的 PyTorch 类型`" `$res = `$(python -c `"`$content`") return `$res -split ',' | ForEach-Object { `$_.Trim() } } # 获取 PyTorch 列表 function Get-PyTorch-List { `$pytorch_list = New-Object System.Collections.ArrayList `$supported_type = Get-Avaliable-PyTorch-Type # >>>>>>>>>> Start `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==1.12.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CUDA 11.3) + xFormers 0.0.14`" `"type`" = `"cu113`" `"supported`" = `"cu113`" -in `$supported_type `"torch`" = `"torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==1.12.1+cu113`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.13.1+cpu torchvision==0.14.1+cpu torchaudio==0.13.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 torch-directml==0.1.13.1.dev230413`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CUDA 11.7) + xFormers 0.0.16`" `"type`" = `"cu117`" `"supported`" = `"cu117`" -in `$supported_type `"torch`" = `"torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==1.13.1+cu117`" `"xformers`" = `"xformers==0.0.18`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.0 torch-directml==0.2.0.dev230426`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.0.0a0+gite9ebda2 torchvision==0.15.2a0+fa99a53 intel_extension_for_pytorch==2.0.110+gitc6ea20b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CUDA 11.8) + xFormers 0.0.18`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.0+cu118`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.1+cpu torchvision==0.15.2+cpu torchaudio==2.0.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CUDA 11.8) + xFormers 0.0.22`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.1+cu118`" `"xformers`" = `"xformers==0.0.22`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.0+cpu torchvision==0.16.0+cpu torchaudio==2.1.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi torchaudio==2.1.0a0+cxx11.abi intel_extension_for_pytorch==2.1.10+xpu`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Core Ultra)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+git7bcf7da torchvision==0.16.0+fbb4cc5 torchaudio==2.1.0+6ea1133 intel_extension_for_pytorch==2.1.20+git4849f3b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.1+cpu torchvision==0.16.1+cpu torchaudio==2.1.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 11.8) + xFormers 0.0.23`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu118 torchvision==0.16.1+cu118 torchaudio==2.1.1+cu118`" `"xformers`" = `"xformers==0.0.23+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 12.1) + xFormers 0.0.23`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu121 torchvision==0.16.1+cu121 torchaudio==2.1.1+cu121`" `"xformers`" = `"xformers===0.0.23`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.2+cpu torchvision==0.16.2+cpu torchaudio==2.1.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 11.8) + xFormers 0.0.23.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118`" `"xformers`" = `"xformers==0.0.23.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 12.1) + xFormers 0.0.23.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu121 torchvision==0.16.2+cu121 torchaudio==2.1.2+cu121`" `"xformers`" = `"xformers===0.0.23.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 11.8) + xFormers 0.0.24`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu118 torchvision==0.17.0+cu118 torchaudio==2.2.0+cu118`" `"xformers`" = `"xformers==0.0.24+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 12.1) + xFormers 0.0.24`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu121 torchvision==0.17.0+cu121 torchaudio==2.2.0+cu121`" `"xformers`" = `"xformers===0.0.24`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.1+cpu torchvision==0.17.1+cpu torchaudio==2.2.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 11.8) + xFormers 0.0.25`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu118 torchvision==0.17.1+cu118 torchaudio==2.2.1+cu118`" `"xformers`" = `"xformers==0.0.25+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 torch-directml==0.2.1.dev240521`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 12.1) + xFormers 0.0.25`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121`" `"xformers`" = `"xformers===0.0.25`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.2+cpu torchvision==0.17.2+cpu torchaudio==2.2.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 11.8) + xFormers 0.0.25.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu118 torchvision==0.17.2+cu118 torchaudio==2.2.2+cu118`" `"xformers`" = `"xformers==0.0.25.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 12.1) + xFormers 0.0.25.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu121 torchvision==0.17.2+cu121 torchaudio==2.2.2+cu121`" `"xformers`" = `"xformers===0.0.25.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.0+cpu torchvision==0.18.0+cpu torchaudio==2.3.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 11.8) + xFormers 0.0.26.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" `"xformers`" = `"xformers==0.0.26.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 12.1) + xFormers 0.0.26.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121`" `"xformers`" = `"xformers===0.0.26.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.1+cpu torchvision==0.18.1+cpu torchaudio==2.3.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 torch-directml==0.2.3.dev240715`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 11.8) + xFormers 0.0.27`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118`" `"xformers`" = `"xformers==0.0.27+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 12.1) + xFormers 0.0.27`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121`" `"xformers`" = `"xformers===0.0.27`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.0+cpu torchvision==0.19.0+cpu torchaudio==2.4.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 11.8) + xFormers 0.0.27.post2`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu118 torchvision==0.19.0+cu118 torchaudio==2.4.0+cu118`" `"xformers`" = `"xformers==0.0.27.post2+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 12.1) + xFormers 0.0.27.post2`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu121 torchvision==0.19.0+cu121 torchaudio==2.4.0+cu121`" `"xformers`" = `"xformers==0.0.27.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.1+cpu torchvision==0.19.1+cpu torchaudio==2.4.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CUDA 12.4) + xFormers 0.0.28.post1`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.4.1+cu124 torchvision==0.19.1+cu124 torchaudio==2.4.1+cu124`" `"xformers`" = `"xformers==0.0.28.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.0+cpu torchvision==0.20.0+cpu torchaudio==2.5.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CUDA 12.4) + xFormers 0.0.28.post2`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.0+cu124 torchvision==0.20.0+cu124 torchaudio==2.5.0+cu124`" `"xformers`" = `"xformers==0.0.28.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.1+cpu torchvision==0.20.1+cpu torchaudio==2.5.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CUDA 12.4) + xFormers 0.0.28.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124`" `"xformers`" = `"xformers==0.0.28.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+cpu torchvision==0.21.0+cpu torchaudio==2.6.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+xpu torchvision==0.21.0+xpu torchaudio==2.6.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.4) + xFormers 0.0.29.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.6) + xFormers 0.0.29.post3`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu126 torchvision==0.21.0+cu126 torchaudio==2.6.0+cu126`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+cpu torchvision==0.22.0+cpu torchaudio==2.7.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+xpu torchvision==0.22.0+xpu torchaudio==2.7.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu118 torchvision==0.22.0+cu118 torchaudio==2.7.0+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.6) + xFormers 0.0.30`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu126 torchvision==0.22.0+cu126 torchaudio==2.7.0+cu126`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.8) + xFormers 0.0.30`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu128 torchvision==0.22.0+cu128 torchaudio==2.7.0+cu128`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+cpu torchvision==0.22.1+cpu torchaudio==2.7.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+xpu torchvision==0.22.1+xpu torchaudio==2.7.1+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu118 torchvision==0.22.1+cu118 torchaudio==2.7.1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.6) + xFormers 0.0.31.post1`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu126 torchvision==0.22.1+cu126 torchaudio==2.7.1+cu126`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.8) + xFormers 0.0.31.post1`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu128 torchvision==0.22.1+cu128 torchaudio==2.7.1+cu128`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+cpu torchvision==0.23.0+cpu torchaudio==2.8.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+xpu torchvision==0.23.0+xpu torchaudio==2.8.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu128 torchvision==0.23.0+cu128 torchaudio==2.8.0+cu128`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.9)`" `"type`" = `"cu129`" `"supported`" = `"cu129`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129`" # `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 13.0)`" `"type`" = `"cu130`" `"supported`" = `"cu130`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU130 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null # <<<<<<<<<< End return `$pytorch_list } # 列出 PyTorch 列表 function List-PyTorch (`$pytorch_list) { Print-Msg `"PyTorch 版本列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"版本序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"PyTorch 版本`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"支持当前设备情况`" -ForegroundColor Blue for (`$i = 0; `$i -lt `$pytorch_list.Count; `$i++) { `$pytorch_hashtables = `$pytorch_list[`$i] `$count += 1 `$name = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"name`" `$supported = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"supported`" Write-Host `"- `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline if (`$supported) { Write-Host `"(支持✓)`" -ForegroundColor Green } else { Write-Host `"(不支持×)`" -ForegroundColor Red } } Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过 Fooocus Installer 更新检查`" } else { Check-Fooocus-Installer-Update } Set-uv PyPI-Mirror-Status `$pytorch_list = Get-PyTorch-List `$go_to = 0 `$to_exit = 0 `$torch_ver = `"`" `$xformers_ver = `"`" `$cuda_support_ver = Get-Drive-Support-CUDA-Version `$current_torch_ver, `$current_xformers_ver = Get-PyTorch-And-xFormers-Version `$after_list_model_option = `"`" while (`$True) { switch (`$after_list_model_option) { display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" List-PyTorch `$pytorch_list Print-Msg `"当前 PyTorch 版本: `$current_torch_ver`" Print-Msg `"当前 xFormers 版本: `$current_xformers_ver`" Print-Msg `"当前显卡驱动支持的最高 CUDA 版本: `$cuda_support_ver`" Print-Msg `"请选择 PyTorch 版本`" Print-Msg `"提示:`" Print-Msg `"1. PyTorch 版本通常来说选择最新版的即可`" Print-Msg `"2. 驱动支持的最高 CUDA 版本需要大于或等于要安装的 PyTorch 中所带的 CUDA 版本, 若驱动支持的最高 CUDA 版本低于要安装的 PyTorch 中所带的 CUDA 版本, 可尝试更新显卡驱动, 或者选择 CUDA 版本更低的 PyTorch`" Print-Msg `"3. 输入数字后回车, 或者输入 exit 退出 PyTorch 重装脚本`" if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建已启用, 指定安装的 PyTorch 序号: `$BuildWithTorch`" `$arg = `$BuildWithTorch `$go_to = 1 } else { `$arg = (Read-Host `"========================================>`").Trim() } switch (`$arg) { exit { Print-Msg `"退出 PyTorch 重装脚本`" `$to_exit = 1 `$go_to = 1 } Default { try { # 检测输入是否符合列表 `$i = [int]`$arg if (!((`$i -ge 1) -and (`$i -le `$pytorch_list.Count))) { `$after_list_model_option = `"display_input_error`" break } `$pytorch_info = `$pytorch_list[(`$i - 1)] `$combination_name = Get-HashValue -Hashtable `$pytorch_info -Key `"name`" `$torch_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"torch`" `$xformers_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"xformers`" `$index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"index_mirror`" `$extra_index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"extra_index_mirror`" `$find_links = Get-HashValue -Hashtable `$pytorch_info -Key `"find_links`" if (`$null -ne `$index_mirror) { `$Env:PIP_INDEX_URL = `$index_mirror `$Env:UV_DEFAULT_INDEX = `$index_mirror } if (`$null -ne `$extra_index_mirror) { `$Env:PIP_EXTRA_INDEX_URL = `$extra_index_mirror `$Env:UV_INDEX = `$extra_index_mirror } if (`$null -ne `$find_links) { `$Env:PIP_FIND_LINKS = `$find_links `$Env:UV_FIND_LINKS = `$find_links } } catch { `$after_list_model_option = `"display_input_error`" break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否选择仅强制重装 ? (通常情况下不需要)`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { if (`$BuildWithTorchReinstall) { `$use_force_reinstall = `"yes`" } else { `$use_force_reinstall = `"no`" } } else { `$use_force_reinstall = (Read-Host `"========================================>`").Trim() } if (`$use_force_reinstall -eq `"yes`" -or `$use_force_reinstall -eq `"y`" -or `$use_force_reinstall -eq `"YES`" -or `$use_force_reinstall -eq `"Y`") { `$force_reinstall_arg = `"--force-reinstall`" `$force_reinstall_status = `"启用`" } else { `$force_reinstall_arg = New-Object System.Collections.ArrayList `$force_reinstall_status = `"禁用`" } Print-Msg `"当前的选择: `$combination_name`" Print-Msg `"PyTorch: `$torch_ver`" Print-Msg `"xFormers: `$xformers_ver`" Print-Msg `"仅强制重装: `$force_reinstall_status`" Print-Msg `"是否确认安装?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$install_torch = `"yes`" } else { `$install_torch = (Read-Host `"========================================>`").Trim() } if (`$install_torch -eq `"yes`" -or `$install_torch -eq `"y`" -or `$install_torch -eq `"YES`" -or `$install_torch -eq `"Y`") { Print-Msg `"重装 PyTorch 中`" if (`$USE_UV) { uv pip install `$torch_ver.ToString().Split() `$force_reinstall_arg if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } } else { python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } if (`$?) { Print-Msg `"安装 PyTorch 成功`" } else { Print-Msg `"安装 PyTorch 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } if (`$null -ne `$xformers_ver) { Print-Msg `"重装 xFormers 中`" if (`$USE_UV) { `$current_xf_ver = Get-xFormers-Version if (`$xformers_ver.Split(`"=`")[-1] -ne `$current_xf_ver) { Print-Msg `"卸载原有 xFormers 中`" python -m pip uninstall xformers -y } uv pip install `$xformers_ver `$force_reinstall_arg --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } } else { python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } if (`$?) { Print-Msg `"安装 xFormers 成功`" } else { Print-Msg `"安装 xFormers 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 Fooocus Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 Fooocus Installer 更新检查 -DisableAutoApplyUpdate 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Fooocus Installer 更新检测 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 Fooocus Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -le `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 Fooocus Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 Fooocus Installer 更新`" return } } else { Print-Msg `"检测到 Fooocus Installer 有新版本可用`" } Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`" -Force } elseif ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/nai1-artist_all_in_one_merge.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/Counterfeit-V3.0_fp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cetusMix_Whalefall2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ex2K_sse2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/kohakuV5_rev2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinamix_meinaV11.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/oukaStar_10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/rabbit_v6.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/sweetSugarSyndrome_rev15.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/AnythingV5Ink_ink.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinapastel_v6Pastel.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/qteamixQ_omegaFp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-lora/resolve/master/sdxl/sd_xl_offset_example-lora_1.0.safetensors`", `"SDXL`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl_edit.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/AnythingXL_xl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/abyssorangeXLElse_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animaPencilXL_v200.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/bluePencilXL_v401.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/nekorayxl_v06W3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/CounterfeitXL-V1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null # SD 3 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips_t5xxlfp8.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_fp8_scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_turbo.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/emi3.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null # SD 3 Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_g.safetensors`", `"SD 3 Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_l.safetensors`", `"SD 3 Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp16.safetensors`", `"SD 3 Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"SD 3 Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn_scaled.safetensors`", `"SD 3 Text Encoder`", `"clip`")) | Out-Null # HunyuanDiT `$model_list.Add(@(`"https://modelscope.cn/models/licyks/comfyui-extension-models/resolve/master/hunyuan_dit_comfyui/hunyuan_dit_1.2.safetensors`", `"HunyuanDiT`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/comfyui-extension-models/resolve/master/hunyuan_dit_comfyui/comfy_freeway_animation_hunyuan_dit_180w.safetensors`", `"HunyuanDiT`", `"checkpoints`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux_dev_fp8_scaled_diffusion_model.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4-v2.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q2_K.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q3_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_1.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_1.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q6_K.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q8_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-F16.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q2_K.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q3_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_1.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_1.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_K_S.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q6_K.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q8_0.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-F16.gguf`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"unet`")) | Out-Null # FLUX Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_L.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_M.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_S.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_M.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_S.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_M.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_S.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q6_K.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q8_0.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f16.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f32.gguf`", `"FLUX Text Encoder`", `"clip`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"vae`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null # VAE approx `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/model.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sdxl.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sd3.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null # Upscale `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/Codeformer/codeformer-v0.1.0.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/16xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x-ITF-SkinDiffDetail-Lite-v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-BrightenRedux_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-YandereInpaint_375000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKDDetoon_97500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Poisson-Detailed_108000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Uniform-Detailed_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x-UltraSharp.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_CountryRoads_377000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Fatality_Comix_260000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Siax_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-Artisoftject_210000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere-Lite_280k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere_300k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-YandereNeoXL_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKDSuperscale_Artisoft_120000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NickelbackFS_72000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Nickelback_70000G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_RealisticRescaler_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Valar_v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_fatal_Anime_500000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_foolhardy_Remacri.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Superscale_150000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Typescale_175k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/A_ESRGAN_Single.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGAN.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGANx2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRNet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/ESRGAN_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/LADDIER1_282500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Neutral_115000_swaG.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharp_101000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharper_103000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Detailed_155000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Soft_190000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/WaifuGAN_v3_30000.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/lollypop.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/sudo_rife4_269.662_testV1_scale1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/detection_Resnet50_Final.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_bisenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_parsenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x2_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X2_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X4_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_CompressedSR_X4_48.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/SwinIR_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null # Embedding `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/EasyNegativeV2.safetensors`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist-anime.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-hands-5.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-image-v2-39000.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad_prompt_version2.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/ng_deepnegative_v1_75t.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/verybadimagenegative_v1.3.pt`", `"Embedding`", `"embeddings`")) | Out-Null # SD 1.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_ip2p_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_shuffle_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1e_sd15_tile_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1p_sd15_depth_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_canny_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_inpaint_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_lineart_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_mlsd_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_normalbae_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_openpose_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_scribble_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_seg_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_softedge_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15s2_lineart_anime_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_brightness.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_illumination.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_qrcode_monster.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null # SDXL ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/monster-labs-control_v1p_sdxl_qrcode_monster.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/mistoLine_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/destitech-controlnet-inpaint-dreamer-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/control-lora/resolve/master/control-lora-recolor-rank128-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/xinsir-controlnet-union-sdxl-1.0-promax.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/kohakuXLControlnet_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/animagineXL40_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLCanny_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineart_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLDepth_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLSoftedge_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineartRrealistic_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLShuffle_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLOpenPose_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLTile_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv0.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_canny_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_depth_midas_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_tile_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsCanny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartAnime.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsNormalMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsSoftedgeHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsMangaLine.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartRealistic.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidasV11.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribbleHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribblePidinet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_openposeModel.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsTile.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/NoobAI_Inpainting_ControlNet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null # SD 3.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_blur.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_canny.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_depth.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null # FLUX ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-redux-dev.safetensors`", `"FLUX ControlNet`", `"style_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev.safetensors`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q3_K_S.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_0.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_1.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_K_S.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_0.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_1.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_K_S.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q6_K.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q8_0.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank128.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank256.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank32.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank4.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank64.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank8.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev.safetensors`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev.safetensors`", `"FLUX ControlNet`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-canny-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-depth-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-hed-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Depth.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Surface-Normals.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Upscaler.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-instantx-controlnet-union.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-mistoline.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-shakker-labs-controlnet-union-pro.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null # CLIP Vision `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_g.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_h.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_vitl.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/sigclip_vision_patch14_384.safetensors`", `"CLIP Vision`", `"clip_vision`")) | Out-Null # IP Adapter `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_light.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_plus.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_vit-G.safetensors`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter-plus_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/noobIPAMARK1_mark1.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-ip-adapter.safetensors`", `"FLUX IP Adapter`", `"controlnet`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"========================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"Fooocus Installer 构建模式已启用, 跳过 Fooocus Installer 更新检查`" } else { Check-Fooocus-Installer-Update } Check-Aria2-Version if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Fooocus 是否已正确安装, 或者尝试运行 Fooocus Installer 进行修复`" Read-Host | Out-Null return } `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/models/`$(`$content[2])`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list } Print-Msg `"退出模型下载脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # Fooocus Installer 设置脚本 function Write-Fooocus-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # 获取 Fooocus Installer 自动检测更新设置 function Get-Fooocus-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 Fooocus Installer 自动应用更新设置 function Get-Fooocus-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取启动参数设置 function Get-Launch-Args-Setting { if (Test-Path `"`$PSScriptRoot/launch_args.txt`") { return Get-Content `"`$PSScriptRoot/launch_args.txt`" } else { return `"无`" } } # 获取自动创建快捷启动方式 function Get-Auto-Set-Launch-Shortcut-Setting { if (Test-Path `"`$PSScriptRoot/enable_shortcut.txt`") { return `"启用`" } else { return `"禁用`" } } # 获取 PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 Fooocus 运行环境检测配置 function Get-Fooocus-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"========================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 Fooocus 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://ghproxy.1888866.xyz/github.com`" Print-Msg `" https://slink.ltd/https://github.com`" Print-Msg `" https://github.boki.moe/github.com`" Print-Msg `" https://github.moeyy.xyz/https://github.com`" Print-Msg `" https://gh-proxy.net/https://github.com`" Print-Msg `" https://gh-proxy.ygxz.in/https://github.com`" Print-Msg `" https://wget.la/https://github.com`" Print-Msg `" https://kkgithub.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Fooocus Installer 自动检查更新设置 function Update-Fooocus-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Fooocus Installer 自动检测更新设置: `$(Get-Fooocus-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Fooocus Installer 自动更新检查`" Print-Msg `"2. 禁用 Fooocus Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 Fooocus Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Fooocus Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 Fooocus Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Fooocus Installer 自动应用更新设置 function Update-Fooocus-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Fooocus Installer 自动应用更新设置: `$(Get-Fooocus-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Fooocus Installer 自动应用更新`" Print-Msg `"2. 禁用 Fooocus Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Fooocus Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 Fooocus Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Fooocus 启动参数设置 function Update-Fooocus-Launch-Args-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Fooocus 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 设置 Fooocus 启动参数`" Print-Msg `"2. 删除 Fooocus 启动参数`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入 Fooocus 启动参数`" Print-Msg `"提示: 保存启动参数后原有的启动参数将被覆盖, Fooocus 可用的启动参数可阅读: https://github.com/lllyasviel/Fooocus?tab=readme-ov-file#all-cmd-flags`" Print-Msg `"输入启动参数后回车保存`" `$fooocus_launch_args = Get-User-Input Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/launch_args.txt`" -Value `$fooocus_launch_args Print-Msg `"设置 Fooocus 启动参数成功, 使用的 Fooocus 启动参数为: `$fooocus_launch_args`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/launch_args.txt`" -Force -Recurse 2> `$null Print-Msg `"删除 Fooocus 启动参数成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 自动创建 Fooocus 快捷启动方式设置 function Auto-Set-Launch-Shortcut-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动创建 Fooocus 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动创建 Fooocus 快捷启动方式`" Print-Msg `"2. 禁用自动创建 Fooocus 快捷启动方式`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { New-Item -ItemType File -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force > `$null Print-Msg `"启用自动创建 Fooocus 快捷启动方式成功`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用自动创建 Fooocus 快捷启动方式成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Fooocus 运行环境检测设置 function Fooocus-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Fooocus 运行环境检测设置: `$(Get-Fooocus-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Fooocus 运行环境检测`" Print-Msg `"2. 禁用 Fooocus 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Fooocus 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 Fooocus 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 Fooocus Installer 更新 function Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -gt `$FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 有新版本可用`" Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 Fooocus Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"Fooocus Installer 已是最新版本`" } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if ((Test-Path `"`$PSScriptRoot/python/python.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`")) { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/git.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`")) { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/launch.py`") { `$fooocus_status = `"已安装`" } else { `$fooocus_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"Fooocus: `$fooocus_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 Fooocus Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 Fooocus Installer 文档 function Get-Fooocus-Installer-Help-Docs { Print-Msg `"调用浏览器打开 Fooocus Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md`" } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"Fooocus Installer 自动检查更新: `$(Get-Fooocus-Installer-Auto-Check-Update-Setting)`" Print-Msg `"Fooocus Installer 自动应用更新: `$(Get-Fooocus-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"Fooocus 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"自动创建 Fooocus 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"Fooocus 运行环境检测设置: `$(Get-Fooocus-Env-Check-Setting)`" Print-Msg `"Fooocus 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 Github 镜像源设置`" Print-Msg `"5. 进入 Fooocus Installer 自动检查更新设置`" Print-Msg `"6. 进入 Fooocus Installer 自动应用更新设置`" Print-Msg `"7. 进入 Fooocus 启动参数设置`" Print-Msg `"8. 进入自动创建 Fooocus 快捷启动方式设置`" Print-Msg `"9. 进入 PyPI 镜像源设置`" Print-Msg `"10. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"11. 进入 Fooocus 运行环境检测设置`" Print-Msg `"12. 进入 Fooocus 内核路径前缀设置`" Print-Msg `"13. 更新 Fooocus Installer 管理脚本`" Print-Msg `"14. 检查环境完整性`" Print-Msg `"15. 查看 Fooocus Installer 文档`" Print-Msg `"16. 退出 Fooocus Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-Github-Mirror-Setting break } 5 { Update-Fooocus-Installer-Auto-Check-Update-Setting break } 6 { Update-Fooocus-Installer-Auto-Apply-Update-Setting break } 7 { Update-Fooocus-Launch-Args-Setting break } 8 { Auto-Set-Launch-Shortcut-Setting break } 9 { PyPI-Mirror-Setting break } 10 { PyTorch-CUDA-Memory-Alloc-Setting break } 11 { Fooocus-Env-Check-Setting break } 12 { Update-Core-Prefix-Setting break } 13 { Check-Fooocus-Installer-Update break } 14 { Check-Env break } 15 { Get-Fooocus-Installer-Help-Docs break } 16 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 Fooocus Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror ) & { `$prefix_list = @(`"core`", `"Fooocus`", `"fooocus`", `"fooocus_portable`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # Fooocus Installer 版本和检查更新间隔 `$Env:FOOOCUS_INSTALLER_VERSION = $FOOOCUS_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:FOOOCUS_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableGithubMirror 禁用 Fooocus Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示符信息 function global:prompt { `"`$(Write-Host `"[Fooocus Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:FOOOCUS_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # Fooocus Installer 更新检测 function global:Check-Fooocus-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/fooocus_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/fooocus_installer/fooocus_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/fooocus_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:FOOOCUS_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 Fooocus Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/fooocus_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/fooocus_installer.ps1`" | Select-String -Pattern `"FOOOCUS_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 Fooocus Installer 更新中`" } else { Print-Msg `"检查 Fooocus Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:FOOOCUS_INSTALLER_VERSION) { Print-Msg `"Fooocus Installer 有新版本可用`" Print-Msg `"调用 Fooocus Installer 进行更新中`" . `"`$Env:CACHE_HOME/fooocus_installer.ps1`" -InstallPath `"`$Env:FOOOCUS_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 Fooocus Installer 管理脚本以应用更新, 回车退出 Fooocus Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"Fooocus Installer 已是最新版本`" } } # 安装绘世启动器 function global:Install-Hanamizuki { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe`", `"https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`", `"https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`" ) `$i = 0 if (!(Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX 未找到, 无法安装绘世启动器, 请检查 Fooocus 是否已正确安装, 或者尝试运行 Fooocus Installer 进行修复`" return } New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if (Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`") { Print-Msg `"绘世启动器已安装, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" } else { ForEach (`$url in `$urls) { Print-Msg `"下载绘世启动器中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" Move-Item -Path `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`" -Force Print-Msg `"绘世启动器安装成功, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载绘世启动器中`" } else { Print-Msg `"下载绘世启动器失败`" return } } } } `$content = `" @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=Fooocus if exist ```"%~dp0%DefaultCorePrefix%```" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if ```"%%i```"==```"-CorePrefix```" ( set NextIsValue=1 ) ) ) if exist ```"%CorePrefixFile%```" ( for /f ```"delims=```" %%i in ('powershell -command ```"Get-Content -Path '%CorePrefixFile%'```"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f ```"delims=```" %%i in ('powershell -command ```"```$current_path = '%CurrentPath%'.Trim('/').Trim('\'); ```$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(```$origin_core_prefix)) { ```$to_path = ```$origin_core_prefix; ```$from_uri = New-Object System.Uri(```$current_path.Replace('\', '/') + '/'); ```$to_uri = New-Object System.Uri(```$to_path.Replace('\', '/')); ```$origin_core_prefix = ```$from_uri.MakeRelativeUri(```$to_uri).ToString().Trim('/') }; Write-Host ```$origin_core_prefix```"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist ```"%RootPath%```" ( cd /d ```"%RootPath%```" ) else ( echo %CorePrefix% not found echo Please check if Fooocus is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d ```"%CurrentPath%```" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d ```"%CurrentPath%```" pause exit 1 ) `".Trim() Set-Content -Encoding Default -Path `"`$Env:FOOOCUS_INSTALLER_ROOT/hanamizuki.bat`" -Value `$content Print-Msg `"检查绘世启动器运行环境`" if (!(Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`")) { if (Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/python`") { Print-Msg `"尝试将 Python 移动至 `$Env:FOOOCUS_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:FOOOCUS_INSTALLER_ROOT/python`" `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Python 路径移动成功`" } else { Print-Msg `"Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境`" Print-Msg `"请关闭所有占用 Python 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 Fooocus Installer 修复环境`" } } if (!(Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/git/bin/git.exe`")) { if (Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/git`") { Print-Msg `"尝试将 Git 移动至 `$Env:FOOOCUS_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:FOOOCUS_INSTALLER_ROOT/git`" `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Git 路径移动成功`" } else { Print-Msg `"Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境`" Print-Msg `"请关闭所有占用 Git 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 Fooocus Installer 修复环境`" } } Print-Msg `"检查绘世启动器运行环境结束`" } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:FOOOCUS_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 Fooocus Installer 内置命令 function global:List-CMD { Write-Host `" ================================== Fooocus Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 Fooocus Installer 内置命令: Update-uv Update-Aria2 Check-Fooocus-Installer-Update Install-Hanamizuki Get-Core-Prefix List-CMD 更多帮助信息可在 Fooocus Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md `" } # 显示 Fooocus Installer 版本 function Get-Fooocus-Installer-Version { `$ver = `$([string]`$Env:FOOOCUS_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"Fooocus Installer 版本: v`${major}.`${minor}.`${micro}`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror Set-Github-Mirror PyPI-Mirror-Status # 切换 uv 指定的 Python if (Test-Path `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$Env:FOOOCUS_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`" } Print-Msg `"激活 Fooocus Env`" Print-Msg `"更多帮助信息可在 Fooocus Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activate.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Fooocus Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 Fooocus Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== Fooocus Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 Fooocus 的简单使用文档。 使用 Fooocus Installer 进行安装并安装成功后,将在当前目录生成 Fooocus 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - launch.ps1:启动 Fooocus。 - update.ps1:更新 Fooocus。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 Fooocus 的模型文件夹中。 - reinstall_pytorch.ps1:重新安装 PyTorch 的脚本,在 PyTorch 出问题或者需要切换 PyTorch 版本时可使用。 - switch_branch.ps1:切换 Fooocus 分支。 - settings.ps1:管理 Fooocus Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - launch_fooocus_installer.ps1:获取最新的 Fooocus Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - Fooocus / core:Fooocus 内核。 详细的 Fooocus Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md Fooocus 一些使用方法: https://github.com/lllyasviel/Fooocus/discussions/117 https://github.com/lllyasviel/Fooocus/discussions/830 ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one Fooocus 项目地址:https://github.com/lllyasviel/Fooocus Fooocus-MRE 项目地址:https://github.com/MoonRide303/Fooocus-MRE RuinedFooocus 项目地址:https://github.com/runew0lf/RuinedFooocus ==================================================================== ########## 用户协议 ########## 使用该软件代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Launch-Script Write-Update-Script Write-Switch-Branch-Script Write-Launch-Fooocus-Install-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-Fooocus-Installer-Settings-Script Write-Env-Activate-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script Write-Hanamizuki-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-Fooocus-Installer-Config { Print-Msg "为 Fooocus Installer 管理脚本复制 Fooocus Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($DisableGithubMirror)) -and (Test-Path "$PSScriptRoot/disable_gh_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_gh_mirror.txt -> $InstallPath/disable_gh_mirror.txt" } elseif ((!($DisableGithubMirror)) -and (!($UseCustomGithubMirror)) -and (Test-Path "$PSScriptRoot/gh_mirror.txt") -and (!(Test-Path "$PSScriptRoot/disable_gh_mirror.txt"))) { Copy-Item -Path "$PSScriptRoot/gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/gh_mirror.txt -> $InstallPath/gh_mirror.txt" } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 写入启动绘世启动器脚本 function Write-Hanamizuki-Script { param ( [switch]$Force ) $content = " @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=Fooocus if exist `"%~dp0%DefaultCorePrefix%`" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if `"%%i`"==`"-CorePrefix`" ( set NextIsValue=1 ) ) ) if exist `"%CorePrefixFile%`" ( for /f `"delims=`" %%i in ('powershell -command `"Get-Content -Path '%CorePrefixFile%'`"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f `"delims=`" %%i in ('powershell -command `"`$current_path = '%CurrentPath%'.Trim('/').Trim('\'); `$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix; `$from_uri = New-Object System.Uri(`$current_path.Replace('\', '/') + '/'); `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')); `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') }; Write-Host `$origin_core_prefix`"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist `"%RootPath%`" ( cd /d `"%RootPath%`" ) else ( echo %CorePrefix% not found echo Please check if Fooocus is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d `"%CurrentPath%`" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d `"%CurrentPath%`" pause exit 1 ) ".Trim() if ((!($Force)) -and (!(Test-Path "$InstallPath/hanamizuki.bat"))) { return } if (Test-Path "$InstallPath/hanamizuki.bat") { Print-Msg "更新 hanamizuki.bat 中" } else { Print-Msg "生成 hanamizuki.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/hanamizuki.bat" -Value $content } # 安装绘世启动器 function Install-Hanamizuki { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe", "https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe", "https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe" ) $i = 0 if (!($InstallHanamizuki)) { return } New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null if (Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe") { Print-Msg "绘世启动器已安装, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" } else { ForEach ($url in $urls) { Print-Msg "下载绘世启动器中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/hanamizuki_tmp.exe" Move-Item -Path "$Env:CACHE_HOME/hanamizuki_tmp.exe" "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe" -Force Print-Msg "绘世启动器安装成功, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载绘世启动器中" } else { Print-Msg "下载绘世启动器失败" return } } } } } # 配置绘世启动器运行环境 function Configure-Hanamizuki-Env { if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe")) { return } Write-Hanamizuki-Script -Force Print-Msg "检查绘世启动器运行环境" if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { if (Test-Path "$InstallPath/python") { Print-Msg "尝试将 Python 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/python" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Python 路径移动成功" } else { Print-Msg "Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境" Print-Msg "请关闭所有占用 Python 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 Fooocus Installer 修复环境" } } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { if (Test-Path "$InstallPath/git") { Print-Msg "尝试将 Git 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/git" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Git 路径移动成功" } else { Print-Msg "Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境" Print-Msg "请关闭所有占用 Git 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 Fooocus Installer 修复环境" } } Print-Msg "检查绘世启动器运行环境结束" } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 Fooocus 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 Fooocus Installer, 更多的说明请阅读 Fooocus Installer 使用文档" Print-Msg "Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" if ((Test-Path "$PSScriptRoot/install_fooocus.txt") -or ($InstallBranch -eq "fooocus")) { Print-Msg "检测到 install_fooocus.txt 配置文件 / -InstallBranch fooocus 命令行参数, 选择安装 lllyasviel/Fooocus" } elseif ((Test-Path "$PSScriptRoot/install_fooocus_mre.txt") -or ($InstallBranch -eq "fooocus_mre")) { Print-Msg "检测到 install_fooocus_mre.txt 配置文件 / -InstallBranch fooocus_mre 命令行参数, 选择安装 MoonRide303/Fooocus-MRE" } elseif ((Test-Path "$PSScriptRoot/install_ruined_fooocus.txt") -or ($InstallBranch -eq "ruined_fooocus")) { Print-Msg "检测到 install_ruined_fooocus.txt 配置文件 / -InstallBranch ruined_fooocus 命令行参数, 选择安装 runew0lf/RuinedFooocus" } else { Print-Msg "未指定安装的 Fooocus 分支, 默认选择安装 lllyasviel/Fooocus" } Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-Fooocus-Installer-Config if ($BuildMode) { Use-Build-Mode Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "Fooocus 环境构建完成, 路径: $InstallPath" } else { Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "Fooocus 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 Fooocus 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 Fooocus Installer 使用文档" Print-Msg "Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md" Print-Msg "退出 Fooocus Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWithTorch", $BuildWithTorch) if ($BuildWithTorchReinstall) { $launch_args.Add("-BuildWithTorchReinstall", $true) } if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWitchBranch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchBranch", $BuildWitchBranch) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Fooocus 分支切换脚本中" . "$InstallPath/switch_branch.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Fooocus 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($LaunchArg) { $launch_args.Add("-LaunchArg", $LaunchArg) } if ($EnableShortcut) { $launch_args.Add("-EnableShortcut", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Fooocus 启动脚本中" . "$InstallPath/launch.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-Fooocus-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 Fooocus 的绝对路径>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-InstallBranch <安装的 Fooocus 分支>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-BuildMode] [-BuildWithUpdate] [-BuildWithLaunch] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-BuildWitchBranch <Fooocus 分支编号>] [-NoPreDownloadModel] [-PyTorchPackage <PyTorch 软件包>] [-InstallHanamizuki] [-NoCleanCache] [-xFormersPackage <xFormers 软件包>] [-DisableUpdate] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-LaunchArg <Fooocus 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 Fooocus Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -InstallPath <安装 Fooocus 的绝对路径> 指定 Fooocus Installer 安装 Fooocus 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 Fooocus Installer 安装 Fooocus 到 D:\Donwload 这个路径 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -InstallBranch <安装的 Fooocus 分支> 指定 Fooocus Installer 安装的 Fooocus 分支 (fooocus, fooocus_mre, ruined_fooocus) 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallBranch `"fooocus_mre`", 这将指定 Fooocus Installer 安装 MoonRide303/Fooocus-MRE 分支 未指定该参数时, 默认安装 lllyasviel/Fooocus 分支 支持指定安装的分支如下: fooocus: lllyasviel/Fooocus fooocus_mre: MoonRide303/Fooocus-MRE ruined_fooocus: runew0lf/RuinedFooocus -UseUpdateMode 指定 Fooocus Installer 使用更新模式, 只对 Fooocus Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 Fooocus Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 Fooocus Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 Fooocus Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableGithubMirror 禁用 Fooocus Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -BuildMode 启用 Fooocus Installer 构建模式, 在基础安装流程结束后将调用 Fooocus Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 Fooocus Installer 的执行, 而是直接退出 当指定调用多个 Fooocus Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorch, -BuildWithTorchReinstall 参数) - switch_branch.ps1 (对应 -BuildWitchBranch 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - launch.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 update.ps1 脚本, 更新 Fooocus 内核 -BuildWithLaunch (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 launch.ps1 脚本, 执行启动 Fooocus 前的环境检查流程, 但跳过启动 Fooocus -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 Fooocus Installer 构建模式, 并且添加 -BuildWithTorch) 在 Fooocus Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -BuildWitchBranch <Fooocus 分支编号> (需添加 -BuildMode 启用 Fooocus Installer 构建模式) Fooocus Installer 执行完基础安装流程后调用 Fooocus Installer 的 switch_branch.ps1 脚本, 根据 Fooocus 分支编号切换到对应的 Fooocus 分支 Fooocus 分支编号可运行 switch_branch.ps1 脚本进行查看 -NoPreDownloadModel 安装 Fooocus 时跳过预下载模型 -PyTorchPackage <PyTorch 软件包> (需要同时搭配 -xFormersPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 PyTorch 版本, 如 -PyTorchPackage `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" -xFormersPackage <xFormers 软件包> (需要同时搭配 -PyTorchPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 xFormers 版本, 如 -xFormersPackage `"xformers===0.0.26.post1+cu118`" -InstallHanamizuki 安装绘世启动器, 并生成 hanamizuki.bat 用于启动绘世启动器 -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 禁用 Fooocus Installer 更新检查 -DisableHuggingFaceMirror (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -LaunchArg <Fooocus 启动参数> (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 设置 Fooocus 自定义启动参数, 如启用 --in-browser 和 --async-cuda-allocation, 则使用 -LaunchArg `"--in-browser --async-cuda-allocation`" 进行启用 -EnableShortcut (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 创建 Fooocus 启动快捷方式 -DisableCUDAMalloc (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 禁用 Fooocus Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 禁用 Fooocus Installer 检查 Fooocus 运行环境中存在的问题, 禁用后可能会导致 Fooocus 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate (仅在 Fooocus Installer 构建模式下生效, 并且只作用于 Fooocus Installer 管理脚本) 禁用 Fooocus Installer 自动应用新版本更新 更多的帮助信息请阅读 Fooocus Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/fooocus_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-Fooocus-Installer-Version Get-Fooocus-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "Fooocus Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/fooocus_installer.ps1
PowerShell
agpl-3.0
540,639
# PyPI 镜像源 $PIP_INDEX_MIRROR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_EXTRA_INDEX_MIRROR = "https://mirrors.cernet.edu.cn/pypi/web/simple" $PIP_FIND_MIRROR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" # PATH $PYTHON_PATH = "$PSScriptRoot/python" $PYTHON_SCRIPTS_PATH = "$PSScriptRoot/python/Scripts" $Env:PATH = "$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:CACHE_HOME = "$PSScriptRoot/cache" $Env:HF_HOME = "$PSScriptRoot/python/cache/huggingface" $Env:MATPLOTLIBRC = "$PSScriptRoot/cache" $Env:MODELSCOPE_CACHE = "$PSScriptRoot/python/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$PSScriptRoot/python/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$PSScriptRoot/python/cache/libsycl_cache" $Env:TORCH_HOME = "$PSScriptRoot/python/cache/torch" $Env:U2NET_HOME = "$PSScriptRoot/python/cache/u2net" $Env:XDG_CACHE_HOME = "$PSScriptRoot/cache" $Env:PIP_CACHE_DIR = "$PSScriptRoot/python/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$PSScriptRoot/python/cache/pycache" $Env:UV_CACHE_DIR = "$PSScriptRoot/python/cache/uv" $Env:UV_PYTHON = "$PSScriptRoot/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[Embed Python Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 下载并解压 Python function Install-Python { $url = "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.10.11-embed-amd64.zip" # 下载 Python Print-Msg "正在下载 Python" Invoke-WebRequest -Uri $url -OutFile "$PSScriptRoot/python/cache/python-3.10.11-embed-amd64.zip" if ($?) { # 检测是否下载成功并解压 Print-Msg "正在解压 Python" Expand-Archive -Path "$PSScriptRoot/python/cache/python-3.10.11-embed-amd64.zip" -DestinationPath "$PSScriptRoot/python" -Force Remove-Item -Path "$PSScriptRoot/python/cache/python-3.10.11-embed-amd64.zip" Modify-PythonPath Print-Msg "Python 安装成功" } else { Print-Msg "Python 安装失败, 可重新运行安装脚本重试失败的安装" Read-Host | Out-Null exit 1 } } # 修改 python310._pth 文件的内容 function Modify-PythonPath { Print-Msg "修改 python310._pth 文件内容" $content = @("python310.zip", ".", "", "# Uncomment to run site.main() automatically", "import site") Set-Content -Path "$PSScriptRoot/python/python310._pth" -Value $content } # 配置 Python 的 Pip 模块 function Install-Pip { $url = "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/get-pip.py" # 下载 get-pip.py Print-Msg "正在下载 get-pip.py" Invoke-WebRequest -Uri $url -OutFile "$PSScriptRoot/python/cache/get-pip.py" if ($?) { # 检测是否下载成功 # 执行 get-pip.py Print-Msg "通过 get-pip.py 安装 Pip 中" python "$PSScriptRoot/python/cache/get-pip.py" if ($?) { # 检测是否安装成功 Remove-Item -Path "$PSScriptRoot/python/cache/get-pip.py" Print-Msg "Pip 安装成功" } else { Remove-Item -Path "$PSScriptRoot/python/cache/get-pip.py" Print-Msg "Pip 安装失败, 可重新运行安装脚本重试失败的安装" Read-Host | Out-Null exit 1 } } else { Print-Msg "下载 get-pip.py 失败" Print-Msg "Pip 安装失败, 可重新运行安装脚本重试失败的安装" Read-Host | Out-Null exit 1 } } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 可重新运行安装脚本重试失败的安装" Read-Host | Out-Null exit 1 } } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " # PyPI 镜像源 `$PIP_INDEX_MIRROR = `"$PIP_INDEX_MIRROR`" `$PIP_EXTRA_INDEX_MIRROR = `"$PIP_EXTRA_INDEX_MIRROR`" `$PIP_FIND_MIRROR = `"$PIP_FIND_MIRROR`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/Scripts`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = `"`$PIP_EXTRA_INDEX_MIRROR`" `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = `"`$PIP_EXTRA_INDEX_MIRROR`" `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf8`" `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python.exe`" # 提示信息 function global:prompt { `"`$(Write-Host `"[Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Embed Python Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" if (!(Test-Path `"`$PSScriptRoot/disable_proxy.txt`")) { # 检测是否禁用自动设置镜像源 `$INTERNET_SETTING = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if (Test-Path `"`$PSScriptRoot/proxy.txt`") { # 本地存在代理配置 `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件, 已读取代理配置文件并设置代理`" } elseif (`$INTERNET_SETTING.ProxyEnable -eq 1) { # 系统已设置代理 `$Env:HTTP_PROXY = `"http://`$(`$INTERNET_SETTING.ProxyServer)`" `$Env:HTTPS_PROXY = `"http://`$(`$INTERNET_SETTING.ProxyServer)`" Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } else { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件, 禁用自动设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if (!(Test-Path `"`$PSScriptRoot/disable_mirror.txt`")) { # 检测是否禁用了自动设置 HuggingFace 镜像源 if (Test-Path `"`$PSScriptRoot/mirror.txt`") { # 本地存在 HuggingFace 镜像源配置 `$hf_mirror_value = Get-Content `"`$PSScriptRoot/mirror.txt`" `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 mirror.txt 配置文件, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } else { Print-Msg `"检测到本地存在 disable_mirror.txt 镜像源配置文件, 禁用自动设置 HuggingFace 镜像源`" } } function Main { Print-Msg `"初始化中`" Set-Proxy Set-HuggingFace-Mirror Print-Msg `"激活 Env`" } ################### Main " Set-Content -Encoding UTF8 -Path "$PSScriptRoot/python/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[Embed Python Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" " Set-Content -Encoding UTF8 -Path "$PSScriptRoot/python/terminal.ps1" -Value $content } function Main { Print-Msg "初始化中" Print-Msg "即将安装 Embed Python 的路径: $PSScriptRoot\python" Print-Msg "提示: 提示: 若出现某个步骤执行失败, 可尝试再次运行 Embed Python 安装脚本" if (!(Test-Path "$PSScriptRoot/python")) { New-Item -ItemType Directory -Force -Path "$PSScriptRoot/python" > $null } if (!(Test-Path "$PSScriptRoot/python/cache")) { New-Item -ItemType Directory -Force -Path "$PSScriptRoot/python/cache" > $null } Print-Msg "检测是否安装 Python" if (Test-Path "$PSScriptRoot/python/python.exe") { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } Print-Msg "检查是否安装 Pip" python -c "import pip" 2> $null if ($?) { Print-Msg "Pip 已安装" } else { Print-Msg "Pip 未安装" Install-Pip } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Write-Env-Activate-Script Write-Launch-Terminal-Script Print-Msg "安装 Embed Python 结束, 安装路径为: $PSScriptRoot\python" Print-Msg "$PSScriptRoot\python 目录中内置 terminal.ps1 脚本, 运行后将自动打开 PowerShell 进入 Embed Python 的环境, 或者手动打开 PowerShell 运行 activate.ps1 激活环境" Print-Msg "退出 Embed Python 安装脚本" } ################# Main Read-Host | Out-Null
2301_81996401/sd-webui-all-in-one
installer/install_embed_python.ps1
PowerShell
agpl-3.0
11,234
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "InvokeAI"), [string]$InvokeAIPackage = "InvokeAI", [string]$PyTorchMirrorType, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithUpdateNode, [switch]$BuildWithLaunch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [string]$UseCustomHuggingFaceMirror, [switch]$EnableShortcut, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("invokeai", "InvokeAI", "core") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "invokeai" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # InvokeAI Installer 版本和检查更新间隔 $INVOKEAI_INSTALLER_VERSION = 288 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_ADDR } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $Env:PATH = "$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:INVOKEAI_ROOT = "$InstallPath/$Env:CORE_PREFIX" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[InvokeAI Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { $ver = $([string]$INVOKEAI_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "InvokeAI Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 安装 InvokeAI function Install-InvokeAI { Print-Msg "正在下载 InvokeAI" if ($InvokeAIPackage -ne "InvokeAI") { Print-Msg "使用自定义 InvokeAI 版本: $InvokeAIPackage" } if ($USE_UV) { uv pip install $InvokeAIPackage.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $InvokeAIPackage.ToString().Split() --no-deps --use-pep517 } } else { python -m pip install $InvokeAIPackage.ToString().Split() --no-deps --use-pep517 } if ($?) { # 检测是否下载成功 Print-Msg "InvokeAI 安装成功" } else { Print-Msg "InvokeAI 安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 获取 PyTorch 镜像源 function Get-PyTorch-Mirror { $content = " import re import json import subprocess from importlib.metadata import requires def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' def get_invokeai_require_torch_version() -> str: try: invokeai_requires = requires('invokeai') except: return '2.2.2' torch_version = 'torch==2.2.2' for require in invokeai_requires: if get_package_name(require) == 'torch' and has_version(require): torch_version = require break if torch_version.startswith('torch>') and not torch_version.startswith('torch>='): return version_increment(get_package_version(torch_version)) elif torch_version.startswith('torch<') and not torch_version.startswith('torch<='): return version_decrement(get_package_version(torch_version)) elif torch_version.startswith('torch!='): return version_increment(get_package_version(torch_version)) else: return get_package_version(torch_version) if __name__ == '__main__': print(get_pytorch_mirror_type(get_invokeai_require_torch_version())) ".Trim() # 获取镜像类型 if ($PyTorchMirrorType) { Print-Msg "使用自定义 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } else { $mirror_type = $(python -c "$content") } # 设置 PyTorch 镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 获取 PyTorch 版本 function Get-PyTorch-Package-Name { param ( [switch]$IgnorexFormers ) if ($IgnorexFormers) { $xformers_added = "True" } else { $xformers_added = "False" } $content = " from importlib.metadata import requires def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] pytorch_ver = [] invokeai_requires = requires('invokeai') torch_added = False torchvision_added = False torchaudio_added = False xformers_added = $xformers_added for require in invokeai_requires: require = require.split(';')[0].strip() package_name = get_package_name(require) if package_name == 'torch' and not torch_added: pytorch_ver.append(require) torch_added = True if package_name == 'torchvision' and not torchvision_added: pytorch_ver.append(require) torchvision_added = True if package_name == 'torchaudio' and not torchaudio_added: pytorch_ver.append(require) torchaudio_added = True if package_name == 'xformers' and not xformers_added: pytorch_ver.append(require) xformers_added = True ver_list = ' '.join([str(x).strip() for x in pytorch_ver]) print(ver_list) ".Trim() return $(python -c "$content") } # 安装 PyTorch function Install-PyTorch { $has_pytorch = $false $has_xformers = $false $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror switch ($pytorch_mirror_type) { xpu { $ignore_xformers = $true $has_xformers = $true } cpu { $ignore_xformers = $true $has_xformers = $true } Default { $ignore_xformers = $false } } if ($ignore_xformers) { $pytorch_package = Get-PyTorch-Package-Name -IgnorexFormers } else { $pytorch_package = Get-PyTorch-Package-Name } # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch / xFormers: $pytorch_package" Print-Msg "检测是否需要安装 PyTorch / xFormers" python -m pip show torch --quiet 2> $null if ($?) { $has_pytorch = $true } if (!($ignore_xformers)) { python -m pip show xformers --quiet 2> $null if ($?) { $has_xformers = $true } } if (!$has_pytorch -or !$has_xformers) { Print-Msg "安装 PyTorch / xFormers 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() --use-pep517 --no-warn-conflicts } } else { python -m pip install $pytorch_package.ToString().Split() --use-pep517 --no-warn-conflicts } if ($?) { Print-Msg "PyTorch / xFormers 安装成功" } else { Print-Msg "PyTorch / xFormers 安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch / xFormers 已安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 InvokeAI 依赖 function Install-InvokeAI-Requirements { $content = " from importlib.metadata import version try: print('invokeai==' + version('invokeai')) except: print('invokeai') ".Trim() $invokeai_package = $(python -c "$content") Print-Msg "安装 InvokeAI 依赖中" if ($USE_UV) { uv pip install $invokeai_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $invokeai_package.ToString().Split() --use-pep517 } } else { python -m pip install $invokeai_package.ToString().Split() --use-pep517 } if ($?) { Print-Msg "InvokeAI 依赖安装成功" } else { Print-Msg "InvokeAI 依赖安装失败, 终止 InvokeAI 安装进程, 可尝试重新运行 InvokeAI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 安装 LibPatchMatch function Install-LibPatchMatch { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/libpatchmatch_windows_amd64.dll", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/libpatchmatch_windows_amd64.dll" ) $i = 0 ForEach ($url in $urls) { Print-Msg "下载 libpatchmatch_windows_amd64.dll 中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/libpatchmatch_windows_amd64.dll" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 libpatchmatch_windows_amd64.dll 中" } else { Print-Msg "下载 libpatchmatch_windows_amd64.dll 失败, 可能导致 InvokeAI 启动异常" return } } } Move-Item -Path "$Env:CACHE_HOME/libpatchmatch_windows_amd64.dll" -Destination "$InstallPath/python/Lib/site-packages/patchmatch/libpatchmatch_windows_amd64.dll" -Force Print-Msg "下载 libpatchmatch_windows_amd64.dll 成功" } # 安装 OpenCV World function Install-OpenCVWorld { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/opencv_world460.dll", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/opencv_world460.dll" ) $i = 0 ForEach ($url in $urls) { Print-Msg "下载 opencv_world460.dll 中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/opencv_world460.dll" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 opencv_world460.dll 中" } else { Print-Msg "下载 opencv_world460.dll 失败, 可能导致 InvokeAI 启动异常" return } } } Move-Item -Path "$Env:CACHE_HOME/opencv_world460.dll" -Destination "$InstallPath/python/Lib/site-packages/patchmatch/opencv_world460.dll" -Force Print-Msg "下载 opencv_world460.dll 成功" } # 下载 PyPatchMatch function Install-PyPatchMatch { if (!(Test-Path "$InstallPath/python/Lib/site-packages/patchmatch/libpatchmatch_windows_amd64.dll")) { Install-LibPatchMatch } else { Print-Msg "无需下载 libpatchmatch_windows_amd64.dll" } if (!(Test-Path "$InstallPath/python/Lib/site-packages/patchmatch/opencv_world460.dll")) { Install-OpenCVWorld } else { Print-Msg "无需下载 opencv_world460.dll" } } # 安装 function Check-Install { if (!(Test-Path "$InstallPath")) { New-Item -ItemType Directory -Path "$InstallPath" > $null } if (!(Test-Path "$Env:CACHE_HOME")) { New-Item -ItemType Directory -Path "$Env:CACHE_HOME" > $null } Print-Msg "检测是否安装 Python" if (Test-Path "$InstallPath/python/python.exe") { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } Print-Msg "检测是否安装 Git" if (Test-Path "$InstallPath/git/bin/git.exe") { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if (Test-Path "$InstallPath/git/bin/aria2c.exe") { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Print-Msg "检查是否安装 InvokeAI" python -m pip show invokeai --quiet 2> $null if ($?) { Print-Msg "InvokeAI 已安装" } else { Print-Msg "InvokeAI 未安装" Install-InvokeAI } Install-PyTorch Install-InvokeAI-Requirements Print-Msg "检测是否需要安装 PyPatchMatch" Install-PyPatchMatch # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 启动脚本 function Write-Launch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableUV, [switch]`$EnableShortcut, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableUV] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -BuildMode 启用 InvokeAI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 InvokeAI Installer 更新检查 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableUV 禁用 InvokeAI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -EnableShortcut 创建 Fooocus 启动快捷方式 -DisableCUDAMalloc 禁用 InvokeAI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 InvokeAI Installer 检查 Fooocus 运行环境中存在的问题, 禁用后可能会导致 Fooocus 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # InvokeAI Installer 更新检测 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 InvokeAI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -le `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 InvokeAI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 InvokeAI Installer 更新`" return } } else { Print-Msg `"检测到 InvokeAI Installer 有新版本可用`" } Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 获取 InvokeAI 的网页端口 function Get-InvokeAI-Launch-Address { `$port = 9090 `$ip = `"127.0.0.1`" Print-Msg `"获取 InvokeAI 界面地址`" if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/invokeai.yaml`") { # 读取配置文件中的端口配置 Get-Content -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/invokeai.yaml`" | ForEach-Object { `$matches = [regex]::Matches(`$_, '^(\w+): (.+)') foreach (`$match in `$matches) { `$key = `$match.Groups[1].Value `$value = `$match.Groups[2].Value if ((`$key -eq `"port`") -and (!(`$match.Groups[0].Value -eq `"`"))) { `$port = [int]`$value break } } } Get-Content -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/invokeai.yaml`" | ForEach-Object { `$matches = [regex]::Matches(`$_, '^(\w+): (.+)') foreach (`$match in `$matches) { `$key = `$match.Groups[1].Value `$value = `$match.Groups[2].Value if ((`$key -eq `"host`") -and (!(`$match.Groups[0].Value -eq `"`"))) { `$ip = `$value break } } } } # 检查端口是否被占用 while (`$true) { if (Get-NetTCPConnection -LocalPort `$port -ErrorAction SilentlyContinue | Where-Object {(`$_.LocalAddress -eq `"127.0.0.1`") -or (`$_.LocalAddress -eq `$ip)}) { `$port += 1 } else { break } } return `"http://`${ip}:`${port}`" } # 写入 InvokeAI 启动脚本 function Write-Launch-InvokeAI-Script { `$content = `" import re import sys from invokeai.app.run_app import run_app if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(run_app()) `".Trim() if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/launch_invokeai.py`" -Value `$content } # 设置 InvokeAI 的快捷启动方式 function Create-InvokeAI-Shortcut { `$filename = `"InvokeAI`" `$url = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/invokeai_icon.ico`" `$shortcut_icon = `"`$PSScriptRoot/invokeai_icon.ico`" if ((!(Test-Path `"`$PSScriptRoot/enable_shortcut.txt`")) -and (!(`$EnableShortcut))) { return } Print-Msg `"检测到 enable_shortcut.txt 配置文件 / -EnableShortcut 命令行参数, 开始检查 InvokeAI 快捷启动方式中`" if (!(Test-Path `"`$shortcut_icon`")) { Print-Msg `"获取 InvokeAI 图标中`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/invokeai_icon.ico`" if (!(`$?)) { Print-Msg `"获取 InvokeAI 图标失败, 无法创建 InvokeAI 快捷启动方式`" return } } Print-Msg `"更新 InvokeAI 快捷启动方式`" `$shell = New-Object -ComObject WScript.Shell `$desktop = [System.Environment]::GetFolderPath(`"Desktop`") `$shortcut_path = `"`$desktop\`$filename.lnk`" `$shortcut = `$shell.CreateShortcut(`$shortcut_path) `$shortcut.TargetPath = `"`$PSHome\powershell.exe`" `$launch_script_path = `$(Get-Item `"`$PSScriptRoot/launch.ps1`").FullName `$shortcut.Arguments = `"-ExecutionPolicy Bypass -File ```"`$launch_script_path```"`" `$shortcut.IconLocation = `$shortcut_icon # 保存到桌面 `$shortcut.Save() `$start_menu_path = `"`$Env:APPDATA/Microsoft/Windows/Start Menu/Programs`" `$taskbar_path = `"`$Env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar`" # 保存到开始菜单 Copy-Item -Path `"`$shortcut_path`" -Destination `"`$start_menu_path`" -Force # 固定到任务栏 # Copy-Item -Path `"`$shortcut_path`" -Destination `"`$taskbar_path`" -Force # `$shell = New-Object -ComObject Shell.Application # `$shell.Namespace([System.IO.Path]::GetFullPath(`$taskbar_path)).ParseName((Get-Item `$shortcut_path).Name).InvokeVerb('taskbarpin') } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 controlnet_aux function Check-ControlNet-Aux { `$content = `" try: import controlnet_aux success = True except: success = False if not success: from importlib.metadata import requires try: invokeai_requires = requires('invokeai') except: invokeai_requires = [] controlnet_aux_ver = None for req in invokeai_requires: if req.startswith('controlnet-aux=='): controlnet_aux_ver = req.split(';')[0].strip() break if success: print(None) else: if controlnet_aux_ver is None: print('controlnet_aux') else: print(controlnet_aux_ver) `".Trim() Print-Msg `"检查 controlnet_aux 模块是否已安装, 这可能需要一定时间`" `$controlnet_aux_ver = `$(python -c `"`$content`") if (`$controlnet_aux_ver -eq `"None`") { Print-Msg `"controlnet_aux 已安装`" } else { Print-Msg `"检测到 controlnet_aux 缺失, 尝试安装中`" python -m pip uninstall controlnet_aux -y if (`$USE_UV) { uv pip install `$controlnet_aux_ver.ToString().Split() --no-cache-dir if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$controlnet_aux_ver.ToString().Split() --use-pep517 --no-cache-dir } } else { python -m pip install `$controlnet_aux_ver.ToString().Split() --use-pep517 --no-cache-dir } if (`$?) { Print-Msg `"controlnet_aux 安装成功`" } else { Print-Msg `"controlnet_aux 安装失败, 可能会导致 InvokeAI 启动异常`" } } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 InvokeAI 运行环境 function Check-InvokeAI-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 InvokeAI 运行环境检测, 这可能会导致 InvokeAI 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 InvokeAI 运行环境中`" } Fix-PyTorch Check-MS-VCPP-Redistributable # Check-ControlNet-Aux Check-Onnxruntime-GPU Print-Msg `"InvokeAI 运行环境检查完成`" } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过 InvokeAI Installer 更新检查`" } else { Check-InvokeAI-Installer-Update } Set-HuggingFace-Mirror PyPI-Mirror-Status Set-uv Create-InvokeAI-Shortcut Check-InvokeAI-Env Set-PyTorch-CUDA-Memory-Alloc python -m pip show invokeai --quiet 2> `$null if (!(`$?)) { Print-Msg `"检测到 InvokeAI 未正确安装, 请运行 InvokeAI Installer 进行修复`" return } if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过启动 InvokeAI`" } else { `$web_addr = Get-InvokeAI-Launch-Address Print-Msg `"将使用浏览器打开 `$web_addr 地址, 进入 InvokeAI 的界面`" Print-Msg `"提示: 打开浏览器后, 浏览器可能会显示连接失败, 这是因为 InvokeAI 未完成启动, 可以在弹出的 PowerShell 中查看 InvokeAI 的启动过程, 等待 InvokeAI 启动完成后刷新浏览器网页即可`" Print-Msg `"提示:如果 PowerShell 界面长时间不动, 并且 InvokeAI 未启动, 可以尝试按下几次回车键`" Print-Msg `"提示: 如果浏览器未自动打开 `$web_addr 地址, 请手动打开浏览器, 输入 `$web_addr 并打开`" Start-Job -ScriptBlock { param (`$web_addr) Start-Sleep -Seconds 10 Start-Process `$web_addr } -ArgumentList `$web_addr | Out-Null Print-Msg `"启动 InvokeAI 中`" Write-Launch-InvokeAI-Script python `"`$Env:CACHE_HOME/launch_invokeai.py`" if (`$?) { Print-Msg `"InvokeAI 正常退出`" } else { Print-Msg `"InvokeAI 出现异常, 已退出`" } Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch.ps1") { Print-Msg "更新 launch.ps1 中" } else { Print-Msg "生成 launch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUV, [string]`$InvokeAIPackage = `"InvokeAI`", [string]`$PyTorchMirrorType, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-InvokeAIPackage <安装 InvokeAI 的软件包名>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -BuildMode 启用 InvokeAI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 InvokeAI Installer 更新检查 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUV 禁用 InvokeAI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -InvokeAIPackage <安装 InvokeAI 的软件包名> 指定 InvokeAI Installer 安装的 InvokeAI 版本 例如: .\`$(`$script:MyInvocation.MyCommand.Name) -InvokeAIPackage InvokeAI==5.0.2, 这将指定 InvokeAI Installer 安装 InvokeAI 5.0.2 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -DisableAutoApplyUpdate 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # InvokeAI Installer 更新检测 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 InvokeAI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -le `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 InvokeAI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 InvokeAI Installer 更新`" return } } else { Print-Msg `"检测到 InvokeAI Installer 有新版本可用`" } Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 获取 PyTorch 镜像源 function Get-PyTorch-Mirror { `$content = `" import re import json import subprocess from importlib.metadata import requires def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' def get_invokeai_require_torch_version() -> str: try: invokeai_requires = requires('invokeai') except: return '2.2.2' torch_version = 'torch==2.2.2' for require in invokeai_requires: if get_package_name(require) == 'torch' and has_version(require): torch_version = require break if torch_version.startswith('torch>') and not torch_version.startswith('torch>='): return version_increment(get_package_version(torch_version)) elif torch_version.startswith('torch<') and not torch_version.startswith('torch<='): return version_decrement(get_package_version(torch_version)) elif torch_version.startswith('torch!='): return version_increment(get_package_version(torch_version)) else: return get_package_version(torch_version) if __name__ == '__main__': print(get_pytorch_mirror_type(get_invokeai_require_torch_version())) `".Trim() # 获取镜像类型 if (`$PyTorchMirrorType) { Print-Msg `"使用自定义 PyTorch 镜像源类型: `$PyTorchMirrorType`" `$mirror_type = `$PyTorchMirrorType } else { `$mirror_type = `$(python -c `"`$content`") } # 设置 PyTorch 镜像源 switch (`$mirror_type) { cpu { Print-Msg `"设置 PyTorch 镜像源类型为 cpu`" `$pytorch_mirror_type = `"cpu`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } xpu { Print-Msg `"设置 PyTorch 镜像源类型为 xpu`" `$pytorch_mirror_type = `"xpu`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu11x { Print-Msg `"设置 PyTorch 镜像源类型为 cu11x`" `$pytorch_mirror_type = `"cu11x`" `$mirror_index_url = `$Env:PIP_INDEX_URL `$mirror_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$mirror_find_links = `$Env:PIP_FIND_LINKS } cu118 { Print-Msg `"设置 PyTorch 镜像源类型为 cu118`" `$pytorch_mirror_type = `"cu118`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu121 { Print-Msg `"设置 PyTorch 镜像源类型为 cu121`" `$pytorch_mirror_type = `"cu121`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu124 { Print-Msg `"设置 PyTorch 镜像源类型为 cu124`" `$pytorch_mirror_type = `"cu124`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu126 { Print-Msg `"设置 PyTorch 镜像源类型为 cu126`" `$pytorch_mirror_type = `"cu126`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu128 { Print-Msg `"设置 PyTorch 镜像源类型为 cu128`" `$pytorch_mirror_type = `"cu128`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu129 { Print-Msg `"设置 PyTorch 镜像源类型为 cu129`" `$pytorch_mirror_type = `"cu129`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } Default { Print-Msg `"未知的 PyTorch 镜像源类型: `$mirror_type, 使用默认 PyTorch 镜像源`" `$pytorch_mirror_type = `"null`" `$mirror_index_url = `$Env:PIP_INDEX_URL `$mirror_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$mirror_find_links = `$Env:PIP_FIND_LINKS } } return `$mirror_index_url, `$mirror_extra_index_url, `$mirror_find_links, `$pytorch_mirror_type } # 获取 PyTorch 版本 function Get-PyTorch-Package-Name { param ( [switch]`$IgnorexFormers ) if (`$IgnorexFormers) { `$xformers_added = `"True`" } else { `$xformers_added = `"False`" } `$content = `" from importlib.metadata import requires def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] pytorch_ver = [] invokeai_requires = requires('invokeai') torch_added = False torchvision_added = False torchaudio_added = False xformers_added = `$xformers_added for require in invokeai_requires: require = require.split(';')[0].strip() package_name = get_package_name(require) if package_name == 'torch' and not torch_added: pytorch_ver.append(require) torch_added = True if package_name == 'torchvision' and not torchvision_added: pytorch_ver.append(require) torchvision_added = True if package_name == 'torchaudio' and not torchaudio_added: pytorch_ver.append(require) torchaudio_added = True if package_name == 'xformers' and not xformers_added: pytorch_ver.append(require) xformers_added = True ver_list = ' '.join([str(x).strip() for x in pytorch_ver]) print(ver_list) `".Trim() return `$(python -c `"`$content`") } # 获取 InvokeAI 版本号 function Get-InvokeAI-Version { `$content = `" from importlib.metadata import version try: print('invokeai==' + version('invokeai')) except: print('invokeai==5.0.2') `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 更新 InvokeAI 内核 function Update-InvokeAI { Print-Msg `"更新 InvokeAI 中`" if (`$InvokeAIPackage -ne `"InvokeAI`") { Print-Msg `"更新到 InvokeAI 指定版本: `$InvokeAIPackage`" } if (`$USE_UV) { uv pip install `$InvokeAIPackage.ToString().Split() --upgrade --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$InvokeAIPackage.ToString().Split() --upgrade --no-deps --use-pep517 } } else { python -m pip install `$InvokeAIPackage.ToString().Split() --upgrade --no-deps --use-pep517 } if (`$?) { Print-Msg `"更新 InvokeAI 内核成功`" `$Global:UPDATE_INVOKEAI_STATUS = `$true } else { Print-Msg `"更新 InvokeAI 内核失败`" `$Global:UPDATE_INVOKEAI_STATUS = `$false } } # 更新 PyTorch function Update-PyTorch { `$mirror_pip_index_url, `$mirror_pip_extra_index_url, `$mirror_pip_find_links, `$pytorch_mirror_type = Get-PyTorch-Mirror switch (`$pytorch_mirror_type) { xpu { `$ignore_xformers = `$true } cpu { `$ignore_xformers = `$true } Default { `$ignore_xformers = `$false } } if (`$ignore_xformers) { `$pytorch_package = Get-PyTorch-Package-Name -IgnorexFormers } else { `$pytorch_package = Get-PyTorch-Package-Name } # 备份镜像源配置 `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_uv_default_index = `$Env:UV_DEFAULT_INDEX `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index = `$Env:UV_INDEX `$tmp_pip_find_links = `$Env:PIP_FIND_LINKS `$tmp_uv_find_links = `$Env:UV_FIND_LINKS # 设置新的镜像源 `$Env:PIP_INDEX_URL = `$mirror_pip_index_url `$Env:UV_DEFAULT_INDEX = `$mirror_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$mirror_pip_extra_index_url `$Env:UV_INDEX = `$mirror_pip_extra_index_url `$Env:PIP_FIND_LINKS = `$mirror_pip_find_links `$Env:UV_FIND_LINKS = `$mirror_pip_find_links Print-Msg `"将要安装的 PyTorch / xFormers: `$pytorch_package`" Print-Msg `"更新 PyTorch / xFormers 中`" if (`$USE_UV) { uv pip install `$pytorch_package.ToString().Split() if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$pytorch_package.ToString().Split() --use-pep517 --no-warn-conflicts } } else { python -m pip install `$pytorch_package.ToString().Split() --use-pep517 --no-warn-conflicts } if (`$?) { Print-Msg `"PyTorch / xFormers 更新成功`" `$Global:UPDATE_PYTORCH_STATUS = `$true } else { Print-Msg `"PyTorch / xFormers 更新失败`" `$Global:UPDATE_PYTORCH_STATUS = `$false } # 还原镜像源配置 `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_default_index `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_INDEX = `$tmp_uv_index `$Env:PIP_FIND_LINKS = `$tmp_pip_find_links `$Env:UV_FIND_LINKS = `$tmp_uv_find_links } # 更新 InvokeAI 依赖 function Update-InvokeAI-Requirements { `$invokeai_core_ver = Get-InvokeAI-Version Print-Msg `"更新 InvokeAI 依赖中`" if (`$USE_UV) { uv pip install `$invokeai_core_ver.ToString().Split() if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$invokeai_core_ver.ToString().Split() --use-pep517 } } else { python -m pip install `$invokeai_core_ver.ToString().Split() --use-pep517 } if (`$?) { Print-Msg `"更新 InvokeAI 依赖成功`" `$Global:UPDATE_INVOKEAI_REQ_STATUS = `$true } else { Print-Msg `"更新 InvokeAI 依赖失败`" `$Global:UPDATE_INVOKEAI_REQ_STATUS = `$false } } # 处理 InvokeAI 更新流程 function Process-InvokeAI-Update { `$invokeai_current_ver = Get-InvokeAI-Version `$fallback_invokeai_ver = `$false `$Global:PROCESS_INVOKEAI_UPDATE_STATUS = `$false Print-Msg `"开始更新 InvokeAI`" while (`$true) { Update-InvokeAI if (`$UPDATE_INVOKEAI_STATUS) { `$Global:UPDATE_CORE_INFO = `"更新成功`" } else { `$Global:UPDATE_CORE_INFO = `"更新失败`" `$Global:UPDATE_PYTORCH_INFO = `"由于内核更新失败, 不进行 PyTorch 更新`" `$Global:UPDATE_REQ_INFO = `"由于内核更新失败, 不进行依赖更新`" break } Update-PyTorch if (`$UPDATE_PYTORCH_STATUS) { `$Global:UPDATE_PYTORCH_INFO = `"更新成功`" } else { `$Global:UPDATE_PYTORCH_INFO = `"更新失败`" `$Global:UPDATE_REQ_INFO = `"由于 PyTorch 更新失败, 不进行依赖更新`" `$fallback_invokeai_ver = `$true break } Update-InvokeAI-Requirements if (`$UPDATE_INVOKEAI_REQ_STATUS) { `$Global:UPDATE_REQ_INFO = `"更新成功`" } else { `$Global:UPDATE_REQ_INFO = `"更新成功`" `$fallback_invokeai_ver = `$true break } `$Global:PROCESS_INVOKEAI_UPDATE_STATUS = `$true break } if (`$fallback_invokeai_ver) { Print-Msg `"尝试回退 InvokeAI 内核版本`" if (`$USE_UV) { uv pip install `$invokeai_current_ver.ToString().Split() --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$invokeai_current_ver.ToString().Split() --use-pep517 --no-deps } } else { python -m pip install `$invokeai_current_ver.ToString().Split() --use-pep517 --no-deps } if (`$?) { Print-Msg `"回退 InvokeAI 内核版本成功`" `$Global:UPDATE_CORE_INFO = `"由于 InvokeAI 依赖 / PyTorch 更新失败, 已尝试回退内核版本`" } else { Print-Msg `"回退 InvokeAI 内核版本失败`" `$Global:UPDATE_CORE_INFO = `"由于 InvokeAI 依赖 / PyTorch 更新失败, 已尝试回退内核版本, 但出现回退失败`" } } } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过 InvokeAI Installer 更新检查`" } else { Check-InvokeAI-Installer-Update } Set-uv PyPI-Mirror-Status `$ver = `$(python -m pip freeze | Select-String -Pattern `"invokeai`" | Out-String).trim().split(`"==`")[2] Process-InvokeAI-Update `$ver_ = `$(python -m pip freeze | Select-String -Pattern `"invokeai`" | Out-String).Trim().Split(`"==`")[2] Print-Msg `"============================================================================`" Print-Msg `"InvokeAI 更新结果:`" Print-Msg `"InvokeAI 核心: `$UPDATE_CORE_INFO`" Print-Msg `"PyTorch: `$UPDATE_PYTORCH_INFO`" Print-Msg `"InvokeAI 依赖: `$UPDATE_REQ_INFO`" Print-Msg `"============================================================================`" if (`$PROCESS_INVOKEAI_UPDATE_STATUS) { if (`$ver -eq `$ver_) { Print-Msg `"InvokeAI 更新成功, 当前版本:`$ver_`" } else { Print-Msg `"InvokeAI 更新成功, 版本:`$ver -> `$ver_`" } Print-Msg `"该版本更新日志:https://github.com/invoke-ai/InvokeAI/releases/latest`" } else { Print-Msg `"InvokeAI 更新失败, 请检查控制台日志。可尝试重新运行 InvokeAI 更新脚本进行重试`" } Print-Msg `"退出 InvokeAI 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 更新脚本 function Write-Update-Node-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -BuildMode 启用 InvokeAI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 InvokeAI Installer 更新检查 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 InvokeAI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # InvokeAI Installer 更新检测 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 InvokeAI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -le `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 InvokeAI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 InvokeAI Installer 更新`" return } } else { Print-Msg `"检测到 InvokeAI Installer 有新版本可用`" } Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 列出更新结果 function List-Update-Status (`$update_status) { `$success = 0 `$failed = 0 `$sum = 0 Print-Msg `"当前 InvokeAI 自定义节点更新结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"自定义节点名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"更新结果`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$update_status.Count; `$i++) { `$content = `$update_status[`$i] `$name = `$content[0] `$ver = `$content[1] `$status = `$content[2] `$sum += 1 if (`$status) { `$success += 1 } else { `$failed += 1 } Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`${name}: `" -ForegroundColor White -NoNewline if (`$status) { Write-Host `"`$ver `" -ForegroundColor Cyan } else { Write-Host `"`$ver `" -ForegroundColor Red } } Write-Host Write-Host `"[●: `$sum | ✓: `$success | ×: `$failed]`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过 InvokeAI Installer 更新检查`" } else { Check-InvokeAI-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/nodes`")) { Print-Msg `"内核所对应扩展路径 `$PSScriptRoot\`$Env:CORE_PREFIX\nodes 未找到, 无法更新 InvokeAI 自定义节点`" Read-Host | Out-Null return } `$node_list = Get-ChildItem -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/nodes`" | Select-Object -ExpandProperty FullName `$sum = 0 `$count = 0 ForEach (`$node in `$node_list) { if (Test-Path `"`$node/.git`") { `$sum += 1 } } Print-Msg `"更新 InvokeAI 自定义节点中`" `$update_status = New-Object System.Collections.ArrayList ForEach (`$node in `$node_list) { if (!(Test-Path `"`$node/.git`")) { continue } `$count += 1 `$node_name = `$(`$(Get-Item `$node).Name) Print-Msg `"[`$count/`$sum] 更新 `$node_name 自定义节点中`" Fix-Git-Point-Off-Set `"`$node`" `$origin_ver = `$(git -C `"`$node`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$node`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$node`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$node`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$node`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$node`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$node`" fetch --recurse-submodules --all if (`$?) { `$commit_hash = `$(git -C `"`$node`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$node`" reset --hard `"`$remote_branch`" --recurse-submodules `$latest_ver = `$(git -C `"`$node`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$origin_ver -eq `$latest_ver) { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点已为最新版`" `$update_status.Add(@(`$node_name, `"已为最新版`", `$true)) | Out-Null } else { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点更新成功, 版本:`$origin_ver -> `$latest_ver`" `$update_status.Add(@(`$node_name, `"更新成功, 版本:`$origin_ver -> `$latest_ver`", `$true)) | Out-Null } } else { Print-Msg `"[`$count/`$sum] `$node_name 自定义节点更新失败`" `$update_status.Add(@(`$node_name, `"更新失败`", `$false)) | Out-Null } } List-Update-Status `$update_status Print-Msg `"退出 InvokeAI 自定义节点更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update_node.ps1") { Print-Msg "更新 update_node.ps1 中" } else { Print-Msg "生成 update_node.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update_node.ps1" -Value $content } # 获取安装脚本 function Write-Launch-InvokeAI-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 InvokeAI Installer function Download-InvokeAI-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 InvokeAI Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/invokeai_installer.ps1`" if (`$?) { Print-Msg `"下载 InvokeAI Installer 脚本成功`" break } else { Print-Msg `"下载 InvokeAI Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 InvokeAI Installer 脚本`" } else { Print-Msg `"下载 InvokeAI Installer 脚本失败, 可尝试重新运行 InvokeAI Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Set-Proxy `$status = Download-InvokeAI-Installer if (`$status) { Print-Msg `"运行 InvokeAI Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/invokeai_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 InvokeAI Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_invokeai_installer.ps1") { Print-Msg "更新 launch_invokeai_installer.ps1 中" } else { Print-Msg "生成 launch_invokeai_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_invokeai_installer.ps1" -Value $content } # PyTorch 重装脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableUV, [string]`$InvokeAIPackage = `"InvokeAI`", [string]`$PyTorchMirrorType, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableUV] [-InvokeAIPackage <安装 InvokeAI 的软件包名>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -BuildMode 启用 InvokeAI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 InvokeAI Installer 更新检查 -DisableUV 禁用 InvokeAI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -InvokeAIPackage <安装 InvokeAI 的软件包名> 指定 InvokeAI Installer 安装的 InvokeAI 版本 例如: .\`$(`$script:MyInvocation.MyCommand.Name) -InvokeAIPackage InvokeAI==5.0.2, 这将指定 InvokeAI Installer 安装 InvokeAI 5.0.2 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -DisableAutoApplyUpdate 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 PyTorch 镜像源 function Get-PyTorch-Mirror { `$content = `" import re import json import subprocess from importlib.metadata import requires def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' def get_invokeai_require_torch_version() -> str: try: invokeai_requires = requires('invokeai') except: return '2.2.2' torch_version = 'torch==2.2.2' for require in invokeai_requires: if get_package_name(require) == 'torch' and has_version(require): torch_version = require break if torch_version.startswith('torch>') and not torch_version.startswith('torch>='): return version_increment(get_package_version(torch_version)) elif torch_version.startswith('torch<') and not torch_version.startswith('torch<='): return version_decrement(get_package_version(torch_version)) elif torch_version.startswith('torch!='): return version_increment(get_package_version(torch_version)) else: return get_package_version(torch_version) if __name__ == '__main__': print(get_pytorch_mirror_type(get_invokeai_require_torch_version())) `".Trim() # 获取镜像类型 if (`$PyTorchMirrorType) { Print-Msg `"使用自定义 PyTorch 镜像源类型: `$PyTorchMirrorType`" `$mirror_type = `$PyTorchMirrorType } else { `$mirror_type = `$(python -c `"`$content`") } # 设置 PyTorch 镜像源 switch (`$mirror_type) { cpu { Print-Msg `"设置 PyTorch 镜像源类型为 cpu`" `$pytorch_mirror_type = `"cpu`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } xpu { Print-Msg `"设置 PyTorch 镜像源类型为 xpu`" `$pytorch_mirror_type = `"xpu`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu11x { Print-Msg `"设置 PyTorch 镜像源类型为 cu11x`" `$pytorch_mirror_type = `"cu11x`" `$mirror_index_url = `$Env:PIP_INDEX_URL `$mirror_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$mirror_find_links = `$Env:PIP_FIND_LINKS } cu118 { Print-Msg `"设置 PyTorch 镜像源类型为 cu118`" `$pytorch_mirror_type = `"cu118`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu121 { Print-Msg `"设置 PyTorch 镜像源类型为 cu121`" `$pytorch_mirror_type = `"cu121`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu124 { Print-Msg `"设置 PyTorch 镜像源类型为 cu124`" `$pytorch_mirror_type = `"cu124`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu126 { Print-Msg `"设置 PyTorch 镜像源类型为 cu126`" `$pytorch_mirror_type = `"cu126`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu128 { Print-Msg `"设置 PyTorch 镜像源类型为 cu128`" `$pytorch_mirror_type = `"cu128`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } cu129 { Print-Msg `"设置 PyTorch 镜像源类型为 cu129`" `$pytorch_mirror_type = `"cu129`" `$mirror_index_url = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `$mirror_extra_index_url = `"`" `$mirror_find_links = `"`" } Default { Print-Msg `"未知的 PyTorch 镜像源类型: `$mirror_type, 使用默认 PyTorch 镜像源`" `$pytorch_mirror_type = `"null`" `$mirror_index_url = `$Env:PIP_INDEX_URL `$mirror_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$mirror_find_links = `$Env:PIP_FIND_LINKS } } return `$mirror_index_url, `$mirror_extra_index_url, `$mirror_find_links, `$pytorch_mirror_type } # 获取 PyTorch 版本 function Get-PyTorch-Package-Name { param ( [switch]`$IgnorexFormers ) if (`$IgnorexFormers) { `$xformers_added = `"True`" } else { `$xformers_added = `"False`" } `$content = `" from importlib.metadata import requires def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] pytorch_ver = [] invokeai_requires = requires('invokeai') torch_added = False torchvision_added = False torchaudio_added = False xformers_added = `$xformers_added for require in invokeai_requires: require = require.split(';')[0].strip() package_name = get_package_name(require) if package_name == 'torch' and not torch_added: pytorch_ver.append(require) torch_added = True if package_name == 'torchvision' and not torchvision_added: pytorch_ver.append(require) torchvision_added = True if package_name == 'torchaudio' and not torchaudio_added: pytorch_ver.append(require) torchaudio_added = True if package_name == 'xformers' and not xformers_added: pytorch_ver.append(require) xformers_added = True ver_list = ' '.join([str(x).strip() for x in pytorch_ver]) print(ver_list) `".Trim() return `$(python -c `"`$content`") } # InvokeAI Installer 更新检测 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 InvokeAI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -le `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 InvokeAI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 InvokeAI Installer 更新`" return } } else { Print-Msg `"检测到 InvokeAI Installer 有新版本可用`" } Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } Print-Msg `"当前 PyTorch 版本: `$torch_ver`" Print-Msg `"当前 xFormers 版本: `$xformers_ver`" } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过 InvokeAI Installer 更新检查`" } else { Check-InvokeAI-Installer-Update } Set-uv PyPI-Mirror-Status Get-PyTorch-And-xFormers-Version Print-Msg `"是否重新安装 PyTorch (yes/no)?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$arg = `"yes`" } else { `$arg = (Read-Host `"=========================================>`").Trim() } if (`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`") { Print-Msg `"卸载原有的 PyTorch`" python -m pip uninstall torch torchvision xformers -y python -m pip show invokeai --quiet 2> `$null if (!(`$?)) { Print-Msg `"检测到 InvokeAI 未安装, 尝试安装中`" if (`$InvokeAIPackage -ne `"InvokeAI`") { Print-Msg `"安装 InvokeAI 指定版本: `$InvokeAIPackage`" } if (`$USE_UV) { uv pip install `$InvokeAIPackage.ToString().Split() --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$InvokeAIPackage.ToString().Split() --no-deps --use-pep517 } } else { python -m pip install `$InvokeAIPackage.ToString().Split() --no-deps --use-pep517 } if (`$?) { # 检测是否下载成功 Print-Msg `"InvokeAI 安装成功`" } else { Print-Msg `"InvokeAI 安装失败, 无法进行 PyTorch 重装`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } } `$mirror_pip_index_url, `$mirror_pip_extra_index_url, `$mirror_pip_find_links, `$pytorch_mirror_type = Get-PyTorch-Mirror switch (`$pytorch_mirror_type) { xpu { `$ignore_xformers = `$true } cpu { `$ignore_xformers = `$true } Default { `$ignore_xformers = `$false } } if (`$ignore_xformers) { `$pytorch_package = Get-PyTorch-Package-Name -IgnorexFormers } else { `$pytorch_package = Get-PyTorch-Package-Name } # 备份镜像源配置 `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_uv_default_index = `$Env:UV_DEFAULT_INDEX `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index = `$Env:UV_INDEX `$tmp_pip_find_links = `$Env:PIP_FIND_LINKS `$tmp_uv_find_links = `$Env:UV_FIND_LINKS # 设置新的镜像源 `$Env:PIP_INDEX_URL = `$mirror_pip_index_url `$Env:UV_DEFAULT_INDEX = `$mirror_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$mirror_pip_extra_index_url `$Env:UV_INDEX = `$mirror_pip_extra_index_url `$Env:PIP_FIND_LINKS = `$mirror_pip_find_links `$Env:UV_FIND_LINKS = `$mirror_pip_find_links Print-Msg `"将要安装的 PyTorch / xFormers: `$pytorch_package`" Print-Msg `"重新安装 PyTorch`" if (`$USE_UV) { uv pip install `$pytorch_package.ToString().Split() if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$pytorch_package.ToString().Split() --use-pep517 } } else { python -m pip install `$pytorch_package.ToString().Split() --use-pep517 } if (`$?) { Print-Msg `"重新安装 PyTorch 成功`" } else { Print-Msg `"重新安装 PyTorch 失败, 请重新运行 PyTorch 重装脚本`" } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -BuildMode 启用 InvokeAI Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 InvokeAI Installer 更新检查 -DisableAutoApplyUpdate 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # InvokeAI Installer 更新检测 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 InvokeAI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -le `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 InvokeAI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 InvokeAI Installer 更新`" return } } else { Print-Msg `"检测到 InvokeAI Installer 有新版本可用`" } Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/nai1-artist_all_in_one_merge.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/Counterfeit-V3.0_fp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cetusMix_Whalefall2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ex2K_sse2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/kohakuV5_rev2.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinamix_meinaV11.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/oukaStar_10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/rabbit_v6.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/sweetSugarSyndrome_rev15.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/AnythingV5Ink_ink.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinapastel_v6Pastel.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/qteamixQ_omegaFp16.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-lora/resolve/master/sdxl/sd_xl_offset_example-lora_1.0.safetensors`", `"SDXL`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl_edit.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/AnythingXL_xl.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/abyssorangeXLElse_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animaPencilXL_v200.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/bluePencilXL_v401.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/nekorayxl_v06W3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/CounterfeitXL-V1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null # SD 3 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips_t5xxlfp8.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_fp8_scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_turbo.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/emi3.safetensors`", `"SD 3`", `"checkpoints`")) | Out-Null # SD 3 Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_g.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_l.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp16.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn_scaled.safetensors`", `"SD 3 Text Encoder`", `"text_encoders`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux_dev_fp8_scaled_diffusion_model.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4-v2.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q2_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q3_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q6_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q8_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-F16.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-fp8.safetensors`", `"FLUX`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q2_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q3_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_1.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_K_S.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q6_K.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q8_0.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-F16.gguf`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev_fp8_scaled.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-kontext_fp8_scaled.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-kontext-dev.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/chroma-unlocked-v50.safetensors`", `"FLUX`", `"diffusion_models`")) | Out-Null # FLUX Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_L.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q6_K.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q8_0.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f16.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f32.gguf`", `"FLUX Text Encoder`", `"text_encoders`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"vae`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null # VAE approx `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/model.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sdxl.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sd3.pt`", `"VAE approx`", `"vae_approx`")) | Out-Null # Upscale `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/Codeformer/codeformer-v0.1.0.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/16xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x-ITF-SkinDiffDetail-Lite-v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-BrightenRedux_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-YandereInpaint_375000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKDDetoon_97500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Poisson-Detailed_108000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Uniform-Detailed_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x-UltraSharp.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_CountryRoads_377000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Fatality_Comix_260000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Siax_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-Artisoftject_210000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere-Lite_280k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere_300k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-YandereNeoXL_200k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKDSuperscale_Artisoft_120000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NickelbackFS_72000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Nickelback_70000G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_RealisticRescaler_100000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Valar_v1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_fatal_Anime_500000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_foolhardy_Remacri.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8xPSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Superscale_150000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Typescale_175k.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/A_ESRGAN_Single.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGAN.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGANx2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRNet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/ESRGAN_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/LADDIER1_282500_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Neutral_115000_swaG.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharp_101000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharper_103000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Detailed_155000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Soft_190000_G.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/WaifuGAN_v3_30000.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/lollypop.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/sudo_rife4_269.662_testV1_scale1.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/detection_Resnet50_Final.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_bisenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_parsenet.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x2_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X2_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X4_64.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_CompressedSR_X4_48.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth`", `"Upscale`", `"upscale_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/SwinIR_4x.pth`", `"Upscale`", `"upscale_models`")) | Out-Null # Embedding `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/EasyNegativeV2.safetensors`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist-anime.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-hands-5.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-image-v2-39000.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad_prompt_version2.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/ng_deepnegative_v1_75t.pt`", `"Embedding`", `"embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/verybadimagenegative_v1.3.pt`", `"Embedding`", `"embeddings`")) | Out-Null # SD 1.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_ip2p_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_shuffle_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1e_sd15_tile_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1p_sd15_depth_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_canny_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_inpaint_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_lineart_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_mlsd_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_normalbae_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_openpose_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_scribble_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_seg_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_softedge_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15s2_lineart_anime_fp16.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_brightness.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_illumination.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_qrcode_monster.safetensors`", `"SD 1.5 ControlNet`", `"controlnet`")) | Out-Null # SDXL ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/monster-labs-control_v1p_sdxl_qrcode_monster.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/mistoLine_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/destitech-controlnet-inpaint-dreamer-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/control-lora/resolve/master/control-lora-recolor-rank128-sdxl.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/xinsir-controlnet-union-sdxl-1.0-promax.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/kohakuXLControlnet_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/animagineXL40_canny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLCanny_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineart_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLDepth_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLSoftedge_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineartRrealistic_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLShuffle_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLOpenPose_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLTile_v10.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv0.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_canny_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_depth_midas_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_tile_fp16.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsCanny.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartAnime.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsNormalMidas.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsSoftedgeHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsMangaLine.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartRealistic.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidasV11.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribbleHed.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribblePidinet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_openposeModel.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsTile.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/NoobAI_Inpainting_ControlNet.safetensors`", `"SDXL ControlNet`", `"controlnet`")) | Out-Null # SD 3.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_blur.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_canny.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd3_controlnet/resolve/master/sd3.5_large_controlnet_depth.safetensors`", `"SD 3.5 ControlNet`", `"controlnet`")) | Out-Null # FLUX ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-redux-dev.safetensors`", `"FLUX ControlNet`", `"style_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q3_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_1.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q4_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_1.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q5_K_S.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q6_K.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-Q8_0.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank128.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank256.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank32.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank4.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank64.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-fill-dev-lora-rank8.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-canny-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-F16-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q4_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q5_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-fp16-Q8_0-GGUF.gguf`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev-lora.safetensors`", `"FLUX ControlNet`", `"loras`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-depth-dev.safetensors`", `"FLUX ControlNet`", `"diffusion_models`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-canny-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-depth-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-hed-controlnet-v3.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Depth.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Surface-Normals.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-jasperai-Controlnet-Upscaler.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-instantx-controlnet-union.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-mistoline.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-dev-shakker-labs-controlnet-union-pro.safetensors`", `"FLUX ControlNet`", `"controlnet`")) | Out-Null # CLIP Vision `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_g.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_h.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_vitl.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/sigclip_vision_patch14_384.safetensors`", `"CLIP Vision`", `"clip_vision`")) | Out-Null # IP Adapter `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_light.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_plus.pth`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_vit-G.safetensors`", `"SD 1.5 IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter-plus_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/noobIPAMARK1_mark1.safetensors`", `"SDXL IP Adapter`", `"ipadapter`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux_controlnet/resolve/master/flux1-xlabs-ip-adapter.safetensors`", `"FLUX IP Adapter`", `"controlnet`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count `$Global:model_path_list = New-Object System.Collections.ArrayList for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" `$model_full_path = Join-Path -Path `"`$path`" -ChildPath `"`$model_name`" `$model_path_list.Add(`"`$model_full_path`") | Out-Null } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"=========================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # InvokeAI 模型导入脚本 function Write-InvokeAI-Import-Model-Script { `$content = `" import os import asyncio import argparse from pathlib import Path from typing import Union from invokeai.app.services.model_manager.model_manager_default import ModelManagerService from invokeai.app.services.model_install.model_install_common import InstallStatus from invokeai.app.services.model_records.model_records_sql import ModelRecordServiceSQL from invokeai.app.services.download.download_default import DownloadQueueService from invokeai.app.services.events.events_fastapievents import FastAPIEventService from invokeai.app.services.config.config_default import get_config from invokeai.app.services.shared.sqlite.sqlite_util import init_db from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage from invokeai.backend.util.logging import InvokeAILogger from invokeai.app.services.invoker import Invoker invokeai_logger = InvokeAILogger.get_logger('InvokeAI Installer') def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser() normalized_filepath = lambda filepath: str(Path(filepath).absolute().as_posix()) parser.add_argument('--invokeai-path', type = normalized_filepath, default = os.path.join(os.getcwd(), 'invokeai'), help = 'InvokeAI 根路径') parser.add_argument('--model-path', type=str, nargs='+', help = '安装的模型路径列表') parser.add_argument('--no-link', action='store_true', help = '不使用链接模式, 直接将模型安装在 InvokeAI 目录中') return parser.parse_args() def get_invokeai_model_manager() -> ModelManagerService: invokeai_logger.info('初始化 InvokeAI 模型管理服务中') configuration = get_config() output_folder = configuration.outputs_path image_files = DiskImageFileStorage(f'{output_folder}/images') logger = InvokeAILogger.get_logger('InvokeAI', config=configuration) db = init_db(config=configuration, logger=logger, image_files=image_files) event_handler_id = 1234 loop = asyncio.get_event_loop() events=FastAPIEventService(event_handler_id, loop=loop) model_manager = ModelManagerService.build_model_manager( app_config=configuration, model_record_service=ModelRecordServiceSQL(db=db, logger=logger), download_queue=DownloadQueueService(app_config=configuration, event_bus=events), events=FastAPIEventService(event_handler_id, loop=loop) ) invokeai_logger.info('初始化 InvokeAI 模型管理服务完成') return model_manager def import_model(model_manager: ModelManagerService, inplace: bool, model_path: Union[str, Path]) -> bool: file_name = os.path.basename(model_path) try: invokeai_logger.info(f'导入 {file_name} 模型到 InvokeAI 中') job = model_manager.install.heuristic_import( source=str(model_path), inplace=inplace ) result = model_manager.install.wait_for_job(job) if result.status == InstallStatus.COMPLETED: invokeai_logger.info(f'导入 {file_name} 模型到 InvokeAI 成功') return True else: invokeai_logger.error(f'导入 {file_name} 模型到 InvokeAI 时出现了错误: {result.error}') return False except Exception as e: invokeai_logger.error(f'导入 {file_name} 模型到 InvokeAI 时出现了错误: {e}') return False def main() -> None: args = get_args() if not os.environ.get('INVOKEAI_ROOT'): os.environ['INVOKEAI_ROOT'] = args.invokeai_path model_list = args.model_path install_model_to_local = args.no_link install_result = [] count = 0 task_sum = len(model_list) if task_sum == 0: invokeai_logger.info('无需要导入的模型') return invokeai_logger.info('InvokeAI 根目录: {}'.format(os.environ.get('INVOKEAI_ROOT'))) model_manager = get_invokeai_model_manager() invokeai_logger.info('启动 InvokeAI 模型管理服务') model_manager.start(Invoker) invokeai_logger.info('就地安装 (仅本地) 模式: {}'.format('禁用' if install_model_to_local else '启用')) for model in model_list: count += 1 file_name = os.path.basename(model) invokeai_logger.info(f'[{count}/{task_sum}] 添加模型: {file_name}') result = import_model( model_manager=model_manager, inplace=not install_model_to_local, model_path=model ) install_result.append([model, file_name, result]) invokeai_logger.info('关闭 InvokeAI 模型管理服务') model_manager.stop(Invoker) invokeai_logger.info('导入 InvokeAI 模型结果') print('-' * 70) for _, file, status in install_result: status = '导入成功' if status else '导入失败' print(f'- {file}: {status}') print('-' * 70) has_failed = False for _, _, x in install_result: if not x: has_failed = True break if has_failed: invokeai_logger.warning('导入失败的模型列表和模型路径') print('-' * 70) for model, file_name, status in install_result: if not status: print(f'- {file_name}: {model}') print('-' * 70) invokeai_logger.warning(f'导入失败的模型可尝试通过在 InvokeAI 的模型管理 -> 添加模型 -> 链接和本地路径, 手动输入模型路径并添加') invokeai_logger.info('导入模型结束') if __name__ == '__main__': main() `".Trim() Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/cache/import_model.py`" -Value `$content } # 导入模型到 InvokeAI function Import-Model-To-InvokeAI (`$model_list) { if (`$model_list.Count -eq 0) { return } `$script_args = New-Object System.Collections.ArrayList `$script_args.Add(`"--invokeai-path`") | Out-Null `$script_args.Add(`"`$Env:INVOKEAI_ROOT`") | Out-Null `$script_args.Add(`"--model-path`") | Out-Null for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$script_args.Add(`"`$content`") | Out-Null } Write-InvokeAI-Import-Model-Script Print-Msg `"执行模型导入脚本中`" python `"`$PSScriptRoot/cache/import_model.py`" @script_args if (`$?) { Print-Msg `"执行模型导入脚本完成`" } else { Print-Msg `"执行模型导入脚本出现错误, 可能是 InvokeAI 运行环境出现问题, 可尝试重新运行 InvokeAI Installer 进行修复`" } } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"InvokeAI Installer 构建模式已启用, 跳过 InvokeAI Installer 更新检查`" } else { Check-InvokeAI-Installer-Update } Check-Aria2-Version `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/models/`$(`$content[2])`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list Import-Model-To-InvokeAI `$model_path_list } Print-Msg `"退出模型下载脚本`"\ if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # InvokeAI Installer 设置脚本 function Write-InvokeAI-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 InvokeAI Installer 自动检测更新设置 function Get-InvokeAI-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 InvokeAI Installer 自动应用更新设置 function Get-InvokeAI-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取自动创建快捷启动方式 function Get-Auto-Set-Launch-Shortcut-Setting { if (Test-Path `"`$PSScriptRoot/enable_shortcut.txt`") { return `"启用`" } else { return `"禁用`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 InvokeAI 运行环境检测配置 function Get-InvokeAI-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"=========================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # InvokeAI Installer 自动检查更新设置 function Update-InvokeAI-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 InvokeAI Installer 自动检测更新设置: `$(Get-InvokeAI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 InvokeAI Installer 自动更新检查`" Print-Msg `"2. 禁用 InvokeAI Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 InvokeAI Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 InvokeAI Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 InvokeAI Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # InvokeAI Installer 自动应用更新设置 function Update-InvokeAI-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 InvokeAI Installer 自动应用更新设置: `$(Get-InvokeAI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 InvokeAI Installer 自动应用更新`" Print-Msg `"2. 禁用 InvokeAI Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 InvokeAI Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 InvokeAI Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 自动创建 InvokeAI 快捷启动方式设置 function Auto-Set-Launch-Shortcut-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动创建 InvokeAI 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动创建 InvokeAI 快捷启动方式`" Print-Msg `"2. 禁用自动创建 InvokeAI 快捷启动方式`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { New-Item -ItemType File -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force > `$null Print-Msg `"启用自动创建 InvokeAI 快捷启动方式成功`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用自动创建 InvokeAI 快捷启动方式成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 InvokeAI 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://ghproxy.1888866.xyz/github.com`" Print-Msg `" https://slink.ltd/https://github.com`" Print-Msg `" https://github.boki.moe/github.com`" Print-Msg `" https://github.moeyy.xyz/https://github.com`" Print-Msg `" https://gh-proxy.net/https://github.com`" Print-Msg `" https://gh-proxy.ygxz.in/https://github.com`" Print-Msg `" https://wget.la/https://github.com`" Print-Msg `" https://kkgithub.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 InvokeAI Installer 更新 function Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -gt `$INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 有新版本可用`" Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 InvokeAI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"InvokeAI Installer 已是最新版本`" } } # InvokeAI 运行环境检测设置 function InvokeAI-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 InvokeAI 运行环境检测设置: `$(Get-InvokeAI-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 InvokeAI 运行环境检测`" Print-Msg `"2. 禁用 InvokeAI 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 InvokeAI 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 InvokeAI 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if (Test-Path `"`$PSScriptRoot/python/python.exe`") { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if (Test-Path `"`$PSScriptRoot/git/bin/git.exe`") { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if (Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } python -m pip show invokeai --quiet 2> `$null if (`$?) { `$invokeai_status = `"已安装`" } else { `$invokeai_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"InvokeAI: `$invokeai_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 InvokeAI Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 InvokeAI Installer 文档 function Get-InvokeAI-Installer-Help-Docs { Print-Msg `"调用浏览器打开 InvokeAI Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md`" } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"InvokeAI Installer 自动检查更新: `$(Get-InvokeAI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"InvokeAI Installer 自动应用更新: `$(Get-InvokeAI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"自动创建 InvokeAI 快捷启动方式: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"InvokeAI 运行环境检测设置: `$(Get-InvokeAI-Env-Check-Setting)`" Print-Msg `"InvokeAI 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 InvokeAI Installer 自动检查更新设置`" Print-Msg `"5. 进入 InvokeAI Installer 自动应用更新设置`" Print-Msg `"6. 进入自动创建 InvokeAI 快捷启动方式设置`" Print-Msg `"7. 进入 Github 镜像源设置`" Print-Msg `"8. 进入 PyPI 镜像源设置`" Print-Msg `"9. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"10. 进入 InvokeAI 运行环境检测设置`" Print-Msg `"11. 进入 InvokeAI 内核路径前缀设置`" Print-Msg `"12. 更新 InvokeAI Installer 管理脚本`" Print-Msg `"13. 检查环境完整性`" Print-Msg `"14. 查看 InvokeAI Installer 文档`" Print-Msg `"15. 退出 InvokeAI Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-InvokeAI-Installer-Auto-Check-Update-Setting break } 5 { Update-InvokeAI-Installer-Auto-Apply-Update-Setting break } 6 { Auto-Set-Launch-Shortcut-Setting break } 7 { Update-Github-Mirror-Setting break } 8 { PyPI-Mirror-Setting break } 9 { PyTorch-CUDA-Memory-Alloc-Setting break } 10 { InvokeAI-Env-Check-Setting break } 11 { Update-Core-Prefix-Setting break } 12 { Check-InvokeAI-Installer-Update break } 13 { Check-Env break } 14 { Get-InvokeAI-Installer-Help-Docs break } 15 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 InvokeAI Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror ) & { `$prefix_list = @(`"invokeai`", `"InvokeAI`", `"core`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"invokeai`" } # InvokeAI Installer 版本和检查更新间隔 `$Env:INVOKEAI_INSTALLER_VERSION = $INVOKEAI_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$Env:PATH = `"`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:INVOKEAI_ROOT = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:INVOKEAI_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableGithubMirror 禁用 InvokeAI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示信息 function global:prompt { `"`$(Write-Host `"[InvokeAI Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:INVOKEAI_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # InvokeAI Installer 更新检测 function global:Check-InvokeAI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/invokeai_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/invokeai_installer/invokeai_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/invokeai_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:INVOKEAI_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 InvokeAI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/invokeai_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/invokeai_installer.ps1`" | Select-String -Pattern `"INVOKEAI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 InvokeAI Installer 更新中`" } else { Print-Msg `"检查 InvokeAI Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:INVOKEAI_INSTALLER_VERSION) { Print-Msg `"InvokeAI Installer 有新版本可用`" Print-Msg `"调用 InvokeAI Installer 进行更新中`" . `"`$Env:CACHE_HOME/invokeai_installer.ps1`" -InstallPath `"`$Env:INVOKEAI_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 InvokeAI Installer 管理脚本以应用更新, 回车退出 InvokeAI Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"InvokeAI Installer 已是最新版本`" } } # 启用 Github 镜像源 function global:Test-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$Env:INVOKEAI_INSTALLER_ROOT/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$Env:INVOKEAI_INSTALLER_ROOT/.gitconfig`") { Remove-Item -Path `"`$Env:INVOKEAI_INSTALLER_ROOT/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$Env:INVOKEAI_INSTALLER_ROOT/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } if ((Test-Path `"`$Env:INVOKEAI_INSTALLER_ROOT/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { # 使用自定义 Github 镜像源 if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$Env:INVOKEAI_INSTALLER_ROOT/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `$i/licyk/empty `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 安装 InvokeAI 自定义节点 function global:Install-InvokeAI-Node (`$url) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$node_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" `$cache_path = `"`$Env:CACHE_HOME/`${node_name}_tmp`" `$path = `"`$Env:INVOKEAI_ROOT/nodes/`$node_name`" if (!(Test-Path `"`$path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"安装 `$node_name 自定义节点中`" # 清理缓存路径 if (Test-Path `"`$cache_path`") { Remove-Item -Path `"`$cache_path`" -Force -Recurse } git clone --recurse-submodules `$url `"`$cache_path`" if (`$?) { # 清理空文件夹 if (Test-Path `"`$path`") { `$random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path `"`$path`" -Destination `"`$Env:CACHE_HOME/`$random_string`" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path `"`$([System.IO.Path]::GetDirectoryName(`$path))`" -Force > `$null Move-Item -Path `"`$cache_path`" -Destination `"`$path`" -Force Print-Msg `"`$node_name 自定义节点安装成功`" } else { Print-Msg `"`$node_name 自定义节点安装失败`" } } else { Print-Msg `"`$node_name 自定义节点已安装`" } } # Git 下载命令 function global:Git-Clone (`$url, `$path) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$repo_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" if (`$path.Length -ne 0) { `$repo_path = `$path } else { `$repo_path = `"`$(`$(Get-Location).ToString())/`$repo_name`" } if (!(Test-Path `"`$repo_path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$repo_path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"下载 `$repo_name 中`" git clone --recurse-submodules `$url `"`$path`" if (`$?) { Print-Msg `"`$repo_name 下载成功`" } else { Print-Msg `"`$repo_name 下载失败`" } } else { Print-Msg `"`$repo_name 已存在`" } } # 列出已安装的 InvokeAI 自定义节点 function global:List-Node { `$node_list = Get-ChildItem -Path `"`$Env:INVOKEAI_INSTALLER_ROOT/`$Env:CORE_PREFIX/nodes`" | Select-Object -ExpandProperty FullName Print-Msg `"当前 InvokeAI 已安装的自定义节点`" `$count = 0 ForEach (`$i in `$node_list) { if (Test-Path `"`$i`" -PathType Container) { `$count += 1 `$name = [System.IO.Path]::GetFileNameWithoutExtension(`"`$i`") Print-Msg `"- `$name`" } } Print-Msg `"InvokeAI 自定义节点路径: `$([System.IO.Path]::GetFullPath(`"`$Env:INVOKEAI_INSTALLER_ROOT/`$Env:CORE_PREFIX/nodes`"))`" Print-Msg `"InvokeAI 自定义节点数量: `$count`" } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:INVOKEAI_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 InvokeAI Installer 内置命令 function global:List-CMD { Write-Host `" ================================== InvokeAI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 InvokeAI Installer 内置命令: Update-uv Update-Aria2 Check-InvokeAI-Installer-Update Install-InvokeAI-Node Git-Clone Test-Github-Mirror List-Node Get-Core-Prefix List-CMD 更多帮助信息可在 InvokeAI Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md `" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 InvokeAI Installer 版本 function Get-InvokeAI-Installer-Version { `$ver = `$([string]`$Env:INVOKEAI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"InvokeAI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror PyPI-Mirror-Status Print-Msg `"激活 InvokeAI Env`" Print-Msg `"更多帮助信息可在 InvokeAI Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activates.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[InvokeAI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 InvokeAI Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== InvokeAI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 InvokeAI 的简单使用文档。 使用 InvokeAI Installer 进行安装并安装成功后,将在当前目录生成 InvokeAI 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - launch.ps1:启动 InvokeAI。 - update.ps1:更新 InvokeAI。 - update_node.ps1:更新 InvokeAI 自定义节点。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 models 文件夹中。 - reinstall_pytorch.ps1:重装 PyTorch 脚本,解决 PyTorch 无法正常使用或者 xFormers 版本不匹配导致无法调用的问题。 - settings.ps1:管理 InvokeAI Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、InvokeAI 的命令。 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、InvokeAI 的命令。 - launch_invokeai_installer.ps1:获取最新的 InvokeAI Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径,InvokeAI 安装的位置在此处,如果需要重装 InvokeAI,可将该文件夹删除,并使用 InvokeAI Installer 重新部署 InvokeAI。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - invokeai:InvokeAI 存放模型、图片、配置文件等的文件夹。 - models:使用模型下载脚本下载模型时模型的存放位置。 详细的 InvokeAI Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md InvokeAI 的使用教程: SDNote:https://sdnote.netlify.app/guide/invokeai/ InvokeAI 官方文档 1:https://invoke-ai.github.io/InvokeAI InvokeAI 官方文档 2:https://support.invoke.ai/support/solutions InvokeAI 官方视频教程:https://www.youtube.com/@invokeai Reddit 社区:https://www.reddit.com/r/invokeai ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one InvokeAI 项目地址:https://github.com/invoke-ai/InvokeAI ==================================================================== ########## 用户协议 ########## 使用该软件代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Launch-Script Write-Update-Script Write-Update-Node-Script Write-Launch-InvokeAI-Install-Script Write-Env-Activate-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-InvokeAI-Installer-Settings-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-InvokeAI-Installer-Config { Print-Msg "为 InvokeAI Installer 管理脚本复制 InvokeAI Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 InvokeAI 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 InvokeAI Installer, 更多的说明请阅读 InvokeAI Installer 使用文档" Print-Msg "InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-InvokeAI-Installer-Config if ($BuildMode) { Use-Build-Mode Print-Msg "InvokeAI 环境构建完成, 路径: $InstallPath" } else { Print-Msg "InvokeAI 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 InvokeAI 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 InvokeAI Installer 使用文档" Print-Msg "InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md" Print-Msg "退出 InvokeAI Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorchReinstall) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($InvokeAIPackage) { $launch_args.Add("-InvokeAIPackage", $InvokeAIPackage) } if ($PyTorchMirrorType) { $launch_args.Add("-PyTorchMirrorType", $PyTorchMirrorType) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($InvokeAIPackage) { $launch_args.Add("-InvokeAIPackage", $InvokeAIPackage) } if ($PyTorchMirrorType) { $launch_args.Add("-PyTorchMirrorType", $PyTorchMirrorType) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 InvokeAI 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithUpdateNode) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 InvokeAI 自定义节点更新脚本中" . "$InstallPath/update_node.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($EnableShortcut) { $launch_args.Add("-EnableShortcut", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 InvokeAI 启动脚本中" . "$InstallPath/launch.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-InvokeAI-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 InvokeAI 的绝对路径>] [-InvokeAIPackage <安装 InvokeAI 的软件包名>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-BuildMode] [-BuildWithUpdate] [-BuildWithUpdateNode] [-BuildWithLaunch] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-NoCleanCache] [-DisableAutoApplyUpdate] 参数: -Help 获取 InvokeAI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 invokeai -InstallPath <安装 InvokeAI 的绝对路径> 指定 InvokeAI Installer 安装 InvokeAI 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 InvokeAI Installer 安装 InvokeAI 到 D:\Donwload 这个路径 -InvokeAIPackage <安装 InvokeAI 的软件包名> 指定 InvokeAI Installer 安装的 InvokeAI 版本 例如: .\$($script:MyInvocation.MyCommand.Name) -InvokeAIPackage InvokeAI==5.0.2, 这将指定 InvokeAI Installer 安装 InvokeAI 5.0.2 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -UseUpdateMode 指定 InvokeAI Installer 使用更新模式, 只对 InvokeAI Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 InvokeAI Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 InvokeAI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 InvokeAI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -BuildMode 启用 InvokeAI Installer 构建模式, 在基础安装流程结束后将调用 InvokeAI Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 InvokeAI Installer 的执行, 而是直接退出 当指定调用多个 InvokeAI Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorchReinstall 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - update_node.ps1 (对应 -BuildWithUpdateNode 参数) - launch.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 update.ps1 脚本, 更新 InvokeAI 内核 -BuildWithUpdateNode (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 update_node.ps1 脚本, 更新 InvokeAI 自定义节点 -BuildWithLaunch (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 launch.ps1 脚本, 执行启动 InvokeAI 前的环境检查流程, 但跳过启动 InvokeAI -BuildWithTorchReinstall (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 reinstall_pytorch.ps1 脚本, 卸载并重新安装 PyTorch -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 InvokeAI Installer 构建模式) InvokeAI Installer 执行完基础安装流程后调用 InvokeAI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 InvokeAI Installer 更新检查 -DisableHuggingFaceMirror (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -EnableShortcut (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 创建 InvokeAI 启动快捷方式 -DisableCUDAMalloc (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 InvokeAI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 InvokeAI Installer 检查 InvokeAI 运行环境中存在的问题, 禁用后可能会导致 InvokeAI 环境中存在的问题无法被发现并修复 -DisableGithubMirror (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 Fooocus Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate (仅在 InvokeAI Installer 构建模式下生效, 并且只作用于 InvokeAI Installer 管理脚本) 禁用 InvokeAI Installer 自动应用新版本更新 更多的帮助信息请阅读 InvokeAI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/invokeai_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-InvokeAI-Installer-Version Get-InvokeAI-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "InvokeAI Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/invokeai_installer.ps1
PowerShell
agpl-3.0
398,615
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "SD-Trainer"), [string]$PyTorchMirrorType, [string]$InstallBranch, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithLaunch, [int]$BuildWithTorch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [int]$BuildWitchBranch, [string]$PyTorchPackage, [string]$xFormersPackage, [switch]$InstallHanamizuki, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [string]$UseCustomHuggingFaceMirror, [string]$LaunchArg, [switch]$EnableShortcut, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("core", "lora-scripts", "lora_scripts", "sd-trainer", "SD-Trainer", "sd_trainer", "lora-scripts", "lora-scripts-v1.5.1", "lora-scripts-v1.6.2", "lora-scripts-v1.7.3", "lora-scripts-v1.8.1", "lora-scripts-v1.9.0-cu124", "lora-scripts-v1.10.0", "lora-scripts-v1.12.0") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "core" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # SD-Trainer Installer 版本和检查更新间隔 $SD_TRAINER_INSTALLER_VERSION = 314 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_ADDR } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_FIND_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121/torch_stable.html" $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # Github 镜像源列表 $GITHUB_MIRROR_LIST = @( "https://ghfast.top/https://github.com", "https://mirror.ghproxy.com/https://github.com", "https://ghproxy.net/https://github.com", "https://gh.api.99988866.xyz/https://github.com", "https://gh-proxy.com/https://github.com", "https://ghps.cc/https://github.com", "https://gh.idayer.com/https://github.com", "https://ghproxy.1888866.xyz/github.com", "https://slink.ltd/https://github.com", "https://github.boki.moe/github.com", "https://github.moeyy.xyz/https://github.com", "https://gh-proxy.net/https://github.com", "https://gh-proxy.ygxz.in/https://github.com", "https://wget.la/https://github.com", "https://kkgithub.com", "https://gitclone.com/github.com" ) # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # SD-Trainer 仓库地址 $SD_TRAINER_REPO = if ((Test-Path "$PSScriptRoot/install_sd_trainer.txt") -or ($InstallBranch -eq "sd_trainer")) { "https://github.com/Akegarasu/lora-scripts" } elseif ((Test-Path "$PSScriptRoot/install_kohya_gui.txt") -or ($InstallBranch -eq "kohya_gui")) { "https://github.com/bmaltais/kohya_ss" } else { "https://github.com/Akegarasu/lora-scripts" } # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $PYTHON_SCRIPTS_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $GIT_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/git/bin" $Env:PATH = "$PYTHON_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_EXTRA_PATH$([System.IO.Path]::PathSeparator)$GIT_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[SD-Trainer Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { $ver = $([string]$SD_TRAINER_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "SD-Trainer Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / 命令行参数 -DisableProxy, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / 命令行参数 -UseCustomProxy, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / 命令行参数 -DisableUV, 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # Github 镜像测试 function Set-Github-Mirror { $Env:GIT_CONFIG_GLOBAL = "$InstallPath/.gitconfig" # 设置 Git 配置文件路径 if (Test-Path "$InstallPath/.gitconfig") { Remove-Item -Path "$InstallPath/.gitconfig" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory "*" git config --global core.longpaths true if ((Test-Path "$PSScriptRoot/disable_gh_mirror.txt") -or ($DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg "检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / 命令行参数 -DisableGithubMirror, 禁用 Github 镜像源" return } # 使用自定义 Github 镜像源 if ((Test-Path "$PSScriptRoot/gh_mirror.txt") -or ($UseCustomGithubMirror)) { if ($UseCustomGithubMirror) { $github_mirror = $UseCustomGithubMirror } else { $github_mirror = Get-Content "$PSScriptRoot/gh_mirror.txt" } git config --global url."$github_mirror".insteadOf "https://github.com" Print-Msg "检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / 命令行参数 -UseCustomGithubMirror, 已读取 Github 镜像源配置文件并设置 Github 镜像源" return } # 自动检测可用镜像源并使用 $status = 0 ForEach($i in $GITHUB_MIRROR_LIST) { Print-Msg "测试 Github 镜像源: $i" if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } git clone "$i/licyk/empty" "$Env:CACHE_HOME/github-mirror-test" --quiet if ($?) { Print-Msg "该 Github 镜像源可用" $github_mirror = $i $status = 1 break } else { Print-Msg "镜像源不可用, 更换镜像源进行测试" } } if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } if ($status -eq 0) { Print-Msg "无可用 Github 镜像源, 取消使用 Github 镜像源" } else { Print-Msg "设置 Github 镜像源" git config --global url."$github_mirror".insteadOf "https://github.com" } } # 安装 SD-Trainer function Install-SD-Trainer { $status = 0 if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX")) { $status = 1 } else { $items = Get-ChildItem "$InstallPath/$Env:CORE_PREFIX" if ($items.Count -eq 0) { $status = 1 } } $path = "$InstallPath/$Env:CORE_PREFIX" $cache_path = "$Env:CACHE_HOME/lora-scripts_tmp" if ($status -eq 1) { Print-Msg "正在下载 SD-Trainer" # 清理缓存路径 if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } git clone --recurse-submodules $SD_TRAINER_REPO "$cache_path" if ($?) { # 检测是否下载成功 # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Print-Msg "SD-Trainer 安装成功" } else { Print-Msg "SD-Trainer 安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "SD-Trainer 已安装" } Print-Msg "安装 SD-Trainer 子模块中" git -C "$InstallPath/$Env:CORE_PREFIX" submodule init git -C "$InstallPath/$Env:CORE_PREFIX" submodule update if ($?) { Print-Msg "SD-Trainer 子模块安装成功" } else { Print-Msg "SD-Trainer 子模块安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 设置 PyTorch 镜像源 function Get-PyTorch-Mirror ($pytorch_package) { # 获取 PyTorch 的版本 $torch_part = @($pytorch_package -split ' ' | Where-Object { $_ -like "torch==*" })[0] if ($PyTorchMirrorType) { Print-Msg "使用指定的 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } elseif ($torch_part) { # 获取 PyTorch 镜像源类型 if ($torch_part.split("+") -eq $torch_part) { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' if __name__ == '__main__': print(get_pytorch_mirror_type('$torch_part', use_xpu=True)) ".Trim() $mirror_type = $(python -c "$content") } else { $mirror_type = $torch_part.Split("+")[-1] } Print-Msg "PyTorch 镜像源类型: $mirror_type" } else { Print-Msg "未获取到 PyTorch 版本, 无法确定镜像源类型, 可能导致 PyTorch 安装失败" $mirror_type = "null" } # 设置对应的镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 为 PyTorch 获取合适的 CUDA 版本类型 function Get-Appropriate-CUDA-Version-Type { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def select_avaliable_type() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() if compare_versions(cuda_support_ver, '13.0') >= 0: return 'cu130' elif compare_versions(cuda_support_ver, '12.9') >= 0: return 'cu129' elif compare_versions(cuda_support_ver, '12.8') >= 0: return 'cu128' elif compare_versions(cuda_support_ver, '12.6') >= 0: return 'cu126' elif compare_versions(cuda_support_ver, '12.4') >= 0: return 'cu124' elif compare_versions(cuda_support_ver, '12.1') >= 0: return 'cu121' elif compare_versions(cuda_support_ver, '11.8') >= 0: return 'cu118' elif compare_versions(cuda_comp_cap, '10.0') > 0: return 'cu128' # RTX 50xx elif compare_versions(cuda_comp_cap, '0.0') > 0: return 'cu118' # 其他 Nvidia 显卡 else: gpus = get_gpu_list() if any([ x for x in gpus if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): return 'xpu' if any([ x for x in gpus if 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): return 'cu118' return 'cpu' if __name__ == '__main__': print(select_avaliable_type()) ".Trim() return $(python -c "$content") } # 获取合适的 PyTorch / xFormers 版本 function Get-PyTorch-And-xFormers-Package { Print-Msg "设置 PyTorch 和 xFormers 版本" if ($PyTorchPackage) { # 使用自定义的 PyTorch / xFormers 版本 if ($xFormersPackage){ return $PyTorchPackage, $xFormersPackage } else { return $PyTorchPackage, $null } } if ($PyTorchMirrorType) { Print-Msg "根据 $PyTorchMirrorType 类型的 PyTorch 镜像源配置 PyTorch 组合" $appropriate_cuda_version = $PyTorchMirrorType } else { $appropriate_cuda_version = Get-Appropriate-CUDA-Version-Type } switch ($appropriate_cuda_version) { cu130 { $pytorch_package = "torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130" $xformers_package = "xformers==0.0.33" break } cu129 { $pytorch_package = "torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129" $xformers_package = "xformers==0.0.32.post2" break } cu128 { $pytorch_package = "torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128" $xformers_package = "xformers==0.0.33" break } cu126 { $pytorch_package = "torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126" $xformers_package = "xformers==0.0.33" break } cu124 { $pytorch_package = "torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124" $xformers_package = "xformers==0.0.29.post3" break } cu121 { $pytorch_package = "torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121" $xformers_package = "xformers===0.0.27" break } cu118 { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } xpu { $pytorch_package = "torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu" $xformers_package = $null break } cpu { $pytorch_package = "torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu" $xformers_package = $null break } Default { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } } return $pytorch_package, $xformers_package } # 安装 PyTorch function Install-PyTorch { $pytorch_package, $xformers_package = Get-PyTorch-And-xFormers-Package $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror $pytorch_package # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch: $pytorch_package" Print-Msg "将要安装的 xFormers: $xformers_package" Print-Msg "检测是否需要安装 PyTorch" python -m pip show torch --quiet 2> $null if (!($?)) { Print-Msg "安装 PyTorch 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() } } else { python -m pip install $pytorch_package.ToString().Split() } if ($?) { Print-Msg "PyTorch 安装成功" } else { Print-Msg "PyTorch 安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch 已安装, 无需再次安装" } Print-Msg "检测是否需要安装 xFormers" python -m pip show xformers --quiet 2> $null if (!($?)) { if ($xformers_package) { Print-Msg "安装 xFormers 中" if ($USE_UV) { uv pip install $xformers_package.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $xformers_package.ToString().Split() --no-deps } } else { python -m pip install $xformers_package.ToString().Split() --no-deps } if ($?) { Print-Msg "xFormers 安装成功" } else { Print-Msg "xFormers 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg "xFormers 已安装, 无需再次安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 SD-Trainer 依赖 function Install-SD-Trainer-Dependence { # 记录脚本所在路径 $current_path = $(Get-Location).ToString() Set-Location "$InstallPath/$Env:CORE_PREFIX" Print-Msg "安装 SD-Trainer 依赖中" if ($USE_UV) { uv pip install -r requirements.txt if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install -r requirements.txt } } else { python -m pip install -r requirements.txt } if ($?) { Print-Msg "SD-Trainer 依赖安装成功" } else { Print-Msg "SD-Trainer 依赖安装失败, 终止 SD-Trainer 安装进程, 可尝试重新运行 SD-Trainer Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } Set-Location "$current_path" } # 安装 function Check-Install { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null Print-Msg "检测是否安装 Python" if ((Test-Path "$InstallPath/python/python.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } # 切换 uv 指定的 Python if (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe") { $Env:UV_PYTHON = "$InstallPath/$Env:CORE_PREFIX/python/python.exe" } Print-Msg "检测是否安装 Git" if ((Test-Path "$InstallPath/git/bin/git.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if ((Test-Path "$InstallPath/git/bin/aria2c.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/aria2c.exe")) { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Set-Github-Mirror Install-SD-Trainer Install-PyTorch Install-SD-Trainer-Dependence # 设置默认启动参数 if (!(Test-Path "$InstallPath/launch_args.txt")) { Print-Msg "设置默认 SD-Trainer 启动参数" if ((Test-Path "$PSScriptRoot/install_sd_trainer.txt") -or ($InstallBranch -eq "sd_trainer")) { $content = "--skip-prepare-onnxruntime" } elseif ((Test-Path "$PSScriptRoot/install_kohya_gui.txt") -or ($InstallBranch -eq "kohya_gui")) { $content = "--inbrowser --language zh-CN --noverify" } else { $content = "--skip-prepare-onnxruntime" } Set-Content -Encoding UTF8 -Path "$InstallPath/launch_args.txt" -Value $content } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 启动脚本 function Write-Launch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableUV, [string]`$LaunchArg, [switch]`$EnableShortcut, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableUV] [-LaunchArg <SD-Trainer 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer Installer 更新检查 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableUV 禁用 SD-Trainer Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -LaunchArg <SD-Trainer 启动参数> 设置 SD-Trainer 自定义启动参数, 如启用 --disable-offload-from-vram 和 --disable-analytics, 则使用 -LaunchArg ```"--disable-offload-from-vram --disable-analytics```" 进行启用 -EnableShortcut 创建 SD-Trainer 启动快捷方式 -DisableCUDAMalloc 禁用 SD-Trainer Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 SD-Trainer Installer 检查 SD-Trainer 运行环境中存在的问题, 禁用后可能会导致 SD-Trainer 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # SD-Trainer Installer 更新检测 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # SD-Trainer 启动参数 function Get-SD-Trainer-Launch-Args { `$arguments = New-Object System.Collections.ArrayList if ((Test-Path `"`$PSScriptRoot/launch_args.txt`") -or (`$LaunchArg)) { if (`$LaunchArg) { `$launch_args = `$LaunchArg } else { `$launch_args = Get-Content `"`$PSScriptRoot/launch_args.txt`" } if (`$launch_args.Trim().Split().Length -le 1) { `$arguments = `$launch_args.Trim().Split() } else { `$arguments = [regex]::Matches(`$launch_args, '(`"[^`"]*`"|''[^'']*''|\S+)') | ForEach-Object { `$_.Value -replace '^[`"'']|[`"'']`$', '' } } Print-Msg `"检测到本地存在 launch_args.txt 启动参数配置文件 / -LaunchArg 命令行参数, 已读取该启动参数配置文件并应用启动参数`" Print-Msg `"使用的启动参数: `$arguments`" } return `$arguments } # 设置 SD-Trainer 的快捷启动方式 function Create-SD-Trainer-Shortcut { # 设置快捷方式名称 if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"Akegarasu/lora-scripts`") -or (`$branch -eq `"Akegarasu/lora-scripts.git`")) { `$filename = `"SD-Trainer`" } elseif ((`$branch -eq `"bmaltais/kohya_ss`") -or (`$branch -eq `"bmaltais/kohya_ss.git`")) { `$filename = `"Kohya-GUI`" } else { `$filename = `"SD-Trainer`" } } else { `$filename = `"SD-Trainer`" } `$url = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/sd_trainer_icon.ico`" `$shortcut_icon = `"`$PSScriptRoot/sd_trainer_icon.ico`" if ((!(Test-Path `"`$PSScriptRoot/enable_shortcut.txt`")) -and (!(`$EnableShortcut))) { return } Print-Msg `"检测到 enable_shortcut.txt 配置文件 / -EnableShortcut 命令行参数, 开始检查 SD-Trainer 快捷启动方式中`" if (!(Test-Path `"`$shortcut_icon`")) { Print-Msg `"获取 SD-Trainer 图标中`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/sd_trainer_icon.ico`" if (!(`$?)) { Print-Msg `"获取 SD-Trainer 图标失败, 无法创建 SD-Trainer 快捷启动方式`" return } } Print-Msg `"更新 SD-Trainer 快捷启动方式`" `$shell = New-Object -ComObject WScript.Shell `$desktop = [System.Environment]::GetFolderPath(`"Desktop`") `$shortcut_path = `"`$desktop\`$filename.lnk`" `$shortcut = `$shell.CreateShortcut(`$shortcut_path) `$shortcut.TargetPath = `"`$PSHome\powershell.exe`" `$launch_script_path = `$(Get-Item `"`$PSScriptRoot/launch.ps1`").FullName `$shortcut.Arguments = `"-ExecutionPolicy Bypass -File ```"`$launch_script_path```"`" `$shortcut.IconLocation = `$shortcut_icon # 保存到桌面 `$shortcut.Save() `$start_menu_path = `"`$Env:APPDATA/Microsoft/Windows/Start Menu/Programs`" `$taskbar_path = `"`$Env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar`" # 保存到开始菜单 Copy-Item -Path `"`$shortcut_path`" -Destination `"`$start_menu_path`" -Force # 固定到任务栏 # Copy-Item -Path `"`$shortcut_path`" -Destination `"`$taskbar_path`" -Force # `$shell = New-Object -ComObject Shell.Application # `$shell.Namespace([System.IO.Path]::GetFullPath(`$taskbar_path)).ParseName((Get-Item `$shortcut_path).Name).InvokeVerb('taskbarpin') } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 检查 SD-Trainer 依赖完整性 function Check-SD-Trainer-Requirements { `$content = `" import inspect import platform import re import os import sys import copy import logging import argparse import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--requirement-path```", type=_normalized_filepath, default=None, help=```"依赖文件路径```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"Requirement Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True def validate_requirements(requirement_path: str | Path) -> bool: ```"```"```"检测环境依赖是否完整 Args: requirement_path (str | Path): 依赖文件路径 Returns: bool: 如果有缺失依赖则返回````False```` ```"```"```" origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) for package in requires: if not is_package_installed(package): return False return True def main() -> None: requirement_path = COMMAND_ARGS.requirement_path if not os.path.isfile(requirement_path): logger.error(```"依赖文件未找到, 无法检查运行环境```") sys.exit(1) logger.debug(```"检测运行环境中```") print(validate_requirements(requirement_path)) logger.debug(```"环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 SD-Trainer 内核依赖完整性中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_sd_trainer_requirement.py`" -Value `$content `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements_versions.txt`" if (!(Test-Path `"`$dep_path`")) { `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements.txt`" } if (!(Test-Path `"`$dep_path`")) { Print-Msg `"未检测到 SD-Trainer 依赖文件, 跳过依赖完整性检查`" return } `$status = `$(python `"`$Env:CACHE_HOME/check_sd_trainer_requirement.py`" --requirement-path `"`$dep_path`") if (`$status -eq `"False`") { Print-Msg `"检测到 SD-Trainer 内核有依赖缺失, 安装 SD-Trainer 依赖中`" if (`$USE_UV) { uv pip install -r `"`$dep_path`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$dep_path`" } } else { python -m pip install -r `"`$dep_path`" } if (`$?) { Print-Msg `"SD-Trainer 依赖安装成功`" } else { Print-Msg `"SD-Trainer 依赖安装失败, 这将会导致 SD-Trainer 缺失依赖无法正常运行`" } } else { Print-Msg `"SD-Trainer 无缺失依赖`" } } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 Numpy 版本 function Check-Numpy-Version { `$content = `" import importlib.metadata from importlib.metadata import version try: ver = int(version('numpy').split('.')[0]) except: ver = -1 if ver > 1: print(True) else: print(False) `".Trim() Print-Msg `"检查 Numpy 版本中`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"检测到 Numpy 版本大于 1, 这可能导致部分组件出现异常, 尝试重装中`" if (`$USE_UV) { uv pip install `"numpy==1.26.4`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `"numpy==1.26.4`" } } else { python -m pip install `"numpy==1.26.4`" } if (`$?) { Print-Msg `"Numpy 重新安装成功`" } else { Print-Msg `"Numpy 重新安装失败, 这可能导致部分功能异常`" } } else { Print-Msg `"Numpy 无版本问题`" } } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 accelerate 可执行文件可用性 function Check-Accelerate-Executable-File { if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`") { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if (((`$branch -ne `"bmaltais/kohya_ss`") -and (`$branch -ne `"bmaltais/kohya_ss.git`"))) { return } } if (!(Get-Command accelerate -ErrorAction SilentlyContinue)) { return } Print-Msg `"检查 accelerate 可执行文件可用性`" accelerate --help > `$null 2>&1 if (`$?) { Print-Msg `"accelerate 可执行文件可用`" return } Print-Msg `"accelerate 不可用, 尝试重新安装中`" `$content = `" from importlib.metadata import version try: print('accelerate==' + version('accelerate')) except Exception as _: print('accelerate') `".Trim() `$accelerate_package = `$(python -c `"`$content`") python -m pip uninstall accelerate -y if (`$USE_UV) { uv pip install `$accelerate_package if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$accelerate_package } } else { python -m pip install `$accelerate_package } if (`$?) { Print-Msg `"accelerate 重新安装成功`" } else { Print-Msg `"accelerate 重新安装失败, 这可能导致部分功能异常`" } } # 检查 SD-Trainer 运行环境 function Check-SD-Trainer-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 SD-Trainer 运行环境检测, 这可能会导致 SD-Trainer 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 SD-Trainer 运行环境中`" } Check-Accelerate-Executable-File Check-SD-Trainer-Requirements Fix-PyTorch Check-Onnxruntime-GPU Check-Numpy-Version Check-MS-VCPP-Redistributable Print-Msg `"SD-Trainer 运行环境检查完成`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过 SD-Trainer Installer 更新检查`" } else { Check-SD-Trainer-Installer-Update } Set-HuggingFace-Mirror Set-uv PyPI-Mirror-Status if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 SD-Trainer 是否已正确安装, 或者尝试运行 SD-Trainer Installer 进行修复`" Read-Host | Out-Null return } `$launch_args = Get-SD-Trainer-Launch-Args # 记录上次的路径 `$current_path = `$(Get-Location).ToString() Set-Location `"`$PSScriptRoot/`$Env:CORE_PREFIX`" # 检测使用的启动脚本 if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/gui.py`") { `$launch_script = `"gui.py`" } elseif (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/kohya_gui.py`") { `$launch_script = `"kohya_gui.py`" } else { `$launch_script = `"gui.py`" } Create-SD-Trainer-Shortcut Check-SD-Trainer-Env Set-PyTorch-CUDA-Memory-Alloc if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过启动 SD-Trainer`" } else { Print-Msg `"启动 SD-Trainer 中`" python `$launch_script.ToString() `$launch_args `$req = `$? if (`$req) { Print-Msg `"SD-Trainer 正常退出`" } else { Print-Msg `"SD-Trainer 出现异常, 已退出`" } Read-Host | Out-Null } Set-Location `"`$current_path`" } ################### Main ".Trim() if (Test-Path "$InstallPath/launch.ps1") { Print-Msg "更新 launch.ps1 中" } else { Print-Msg "生成 launch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer Installer 更新检查 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD-Trainer Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # SD-Trainer Installer 更新检测 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过 SD-Trainer Installer 更新检查`" } else { Check-SD-Trainer-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 SD-Trainer 是否已正确安装, 或者尝试运行 SD-Trainer Installer 进行修复`" Read-Host | Out-Null return } Print-Msg `"拉取 SD-Trainer 更新内容中`" Fix-Git-Point-Off-Set `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$core_origin_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" fetch --recurse-submodules --all if (`$?) { Print-Msg `"应用 SD-Trainer 更新中`" `$commit_hash = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" reset --hard `"`$remote_branch`" --recurse-submodules `$core_latest_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$core_origin_ver -eq `$core_latest_ver) { Print-Msg `"SD-Trainer 已为最新版`" `$core_update_msg = `"已为最新版, 当前版本:`$core_origin_ver`" } else { Print-Msg `"SD-Trainer 更新成功`" `$core_update_msg = `"更新成功, 版本:`$core_origin_ver -> `$core_latest_ver`" } } else { Print-Msg `"拉取 SD-Trainer 更新内容失败`" Print-Msg `"更新 SD-Trainer 失败, 请检查控制台日志。可尝试重新运行 SD-Traine Installer 更新脚本进行重试`" } Print-Msg `"退出 SD-Trainer 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 分支切换脚本 function Write-Switch-Branch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWitchBranch, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchBranch <SD-Trainer 分支编号>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer Installer 构建模式 -BuildWitchBranch <SD-Trainer 分支编号> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 switch_branch.ps1 脚本, 根据 SD-Trainer 分支编号切换到对应的 SD-Trainer 分支 SD-Trainer 分支编号可运行 switch_branch.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer Installer 更新检查 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD-Trainer Installer自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # SD-Trainer Installer 更新检测 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 获取 SD-Trainer 分支 function Get-SD-Trainer-Branch { `$remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null) if (`$ref -eq `$null) { `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h`") } return `"`$(`$remote.Split(`"/`")[-2])/`$(`$remote.Split(`"/`")[-1]) `$([System.IO.Path]::GetFileName(`$ref))`" } # 切换 SD-Trainer 分支 function Switch-SD-Trainer-Branch (`$remote, `$branch, `$use_submod) { `$sd_trainer_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$preview_url = `$(git -C `"`$sd_trainer_path`" remote get-url origin) Set-Github-Mirror # 设置 Github 镜像源 Print-Msg `"SD-Trainer 远程源替换: `$preview_url -> `$remote`" git -C `"`$sd_trainer_path`" remote set-url origin `"`$remote`" # 替换远程源 # 处理 Git 子模块 if (`$use_submod) { Print-Msg `"更新 SD-Trainer 的 Git 子模块信息`" git -C `"`$sd_trainer_path`" submodule update --init --recursive } else { Print-Msg `"禁用 SD-Trainer 的 Git 子模块`" git -C `"`$sd_trainer_path`" submodule deinit --all -f } Print-Msg `"拉取 SD-Trainer 远程源更新`" git -C `"`$sd_trainer_path`" fetch # 拉取远程源内容 if (`$?) { if (`$use_submod) { Print-Msg `"清理原有的 Git 子模块`" git -C `"`$sd_trainer_path`" submodule deinit --all -f } Print-Msg `"切换 SD-Trainer 分支至 `$branch`" # 本地分支不存在时创建一个分支 git -C `"`$sd_trainer_path`" show-ref --verify --quiet `"refs/heads/`${branch}`" if (!(`$?)) { git -C `"`$sd_trainer_path`" branch `"`${branch}`" } git -C `"`$sd_trainer_path`" checkout `"`${branch}`" --force # 切换分支 Print-Msg `"应用 SD-Trainer 远程源的更新`" if (`$use_submod) { Print-Msg `"更新 SD-Trainer 的 Git 子模块信息`" git -C `"`$sd_trainer_path`" reset --hard `"origin/`$branch`" git -C `"`$sd_trainer_path`" submodule deinit --all -f git -C `"`$sd_trainer_path`" submodule update --init --recursive } if (`$use_submod) { git -C `"`$sd_trainer_path`" reset --recurse-submodules --hard `"origin/`$branch`" # 切换到最新的提交内容上 } else { git -C `"`$sd_trainer_path`" reset --hard `"origin/`$branch`" # 切换到最新的提交内容上 } Print-Msg `"切换 SD-Trainer 分支成功`" } else { Print-Msg `"拉取 SD-Trainer 远程源更新失败, 取消分支切换`" Print-Msg `"尝试回退 SD-Trainer 的更改`" git -C `"`$sd_trainer_path`" remote set-url origin `"`$preview_url`" if (`$use_submod) { git -C `"`$sd_trainer_path`" submodule deinit --all -f } else { git -C `"`$sd_trainer_path`" submodule update --init --recursive } Print-Msg `"回退 SD-Trainer 分支更改完成`" Print-Msg `"切换 SD-Trainer 分支更改失败, 可尝试重新运行 SD-Trainer 分支切换脚本`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过 SD-Trainer Installer 更新检查`" } else { Check-SD-Trainer-Installer-Update } if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 SD-Trainer 是否已正确安装, 或者尝试运行 SD-Trainer Installer 进行修复`" Read-Host | Out-Null return } `$content = `" ----------------------------------------------------- - 1、Akegarasu - SD-Trainer 分支 - 2、bmaltais - Kohya GUI 分支 ----------------------------------------------------- `".Trim() `$to_exit = 0 while (`$True) { Print-Msg `"SD-Trainer 分支列表`" `$go_to = 0 Write-Host `$content Print-Msg `"当前 SD-Trainer 分支: `$(Get-SD-Trainer-Branch)`" Print-Msg `"请选择 SD-Trainer 分支`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车, 或者输入 exit 退出 SD-Trainer 分支切换脚本`" Print-Msg `"2. 切换分支后, 需要清除原来的启动参数, 因为 Akegarasu/SD-Trainer 分支的启动参数和 bmaltais/Kohya GUI 参数互不兼容, 可通过 settings.ps1 脚本中的启动参数设置进行清除`" if (`$BuildMode) { `$arg = `$BuildWitchBranch } else { `$arg = (Read-Host `"===========================================>`").Trim() } switch (`$arg) { 1 { `$remote = `"https://github.com/Akegarasu/lora-scripts`" `$branch = `"main`" `$branch_name = `"Akegarasu - SD-Trainer 分支`" `$use_submod = `$true `$go_to = 1 } 2 { `$remote = `"https://github.com/bmaltais/kohya_ss`" `$branch = `"master`" `$branch_name = `"bmaltais - Kohya GUI 分支`" `$use_submod = `$true `$go_to = 1 } exit { Print-Msg `"退出 SD-Trainer 分支切换脚本`" `$to_exit = 1 `$go_to = 1 } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否切换 SD-Trainer 分支到 `$branch_name ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$operate = `"yes`" } else { `$operate = (Read-Host `"===========================================>`").Trim() } if (`$operate -eq `"yes`" -or `$operate -eq `"y`" -or `$operate -eq `"YES`" -or `$operate -eq `"Y`") { Print-Msg `"开始切换 SD-Trainer 分支`" Switch-SD-Trainer-Branch `$remote `$branch `$use_submod } else { Print-Msg `"取消切换 SD-Trainer 分支`" } Print-Msg `"退出 SD-Trainer 分支切换脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/switch_branch.ps1") { Print-Msg "更新 switch_branch.ps1 中" } else { Print-Msg "生成 switch_branch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/switch_branch.ps1" -Value $content } # 获取安装脚本 function Write-Launch-SD-Trainer-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [string]`$InstallBranch, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 SD-Trainer Installer function Download-SD-Trainer-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 SD-Trainer Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/sd_trainer_installer.ps1`" if (`$?) { Print-Msg `"下载 SD-Trainer Installer 脚本成功`" break } else { Print-Msg `"下载 SD-Trainer Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 SD-Trainer Installer 脚本`" } else { Print-Msg `"下载 SD-Trainer Installer 脚本失败, 可尝试重新运行 SD-Trainer Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { `$arg.Add(`"-DisableGithubMirror`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } `$arg.Add(`"-UseCustomGithubMirror`", `$github_mirror) } } if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"Akegarasu/lora-scripts`") -or (`$branch -eq `"Akegarasu/lora-scripts.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_trainer`") } elseif ((`$branch -eq `"bmaltais/kohya_ss`") -or (`$branch -eq `"bmaltais/kohya_ss.git`")) { `$arg.Add(`"-InstallBranch`", `"kohya_gui`") } } elseif ((Test-Path `"`$PSScriptRoot/install_sd_trainer.txt`") -or (`$InstallBranch -eq `"sd_trainer`")) { `$arg.Add(`"-InstallBranch`", `"sd_trainer`") } elseif ((Test-Path `"`$PSScriptRoot/install_kohya_gui.txt`") -or (`$InstallBranch -eq `"kohya_gui`")) { `$arg.Add(`"-InstallBranch`", `"kohya_gui`") } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Set-Proxy `$status = Download-SD-Trainer-Installer if (`$status) { Print-Msg `"运行 SD-Trainer Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/sd_trainer_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 SD-Trainer Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_sd_trainer_installer.ps1") { Print-Msg "更新 launch_sd_trainer_installer.ps1 中" } else { Print-Msg "生成 launch_sd_trainer_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_sd_trainer_installer.ps1" -Value $content } # 重装 PyTorch 脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWithTorch, [switch]`$BuildWithTorchReinstall, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableUV, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-DisablePyPIMirror] [-DisableUpdate] [-DisableUV] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer Installer 构建模式 -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式, 并且添加 -BuildWithTorch) 在 SD-Trainer Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer Installer 更新检查 -DisableUV 禁用 SD-Trainer Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableAutoApplyUpdate 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # SD-Trainer Installer 更新检测 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 xFormers 版本 function Get-xFormers-Version { `$content = `" from importlib.metadata import version try: ver = version('xformers') except: ver = None print(ver) `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 获取驱动支持的最高 CUDA 版本 function Get-Drive-Support-CUDA-Version { Print-Msg `"获取显卡驱动支持的最高 CUDA 版本`" if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) { `$cuda_ver = `$(nvidia-smi -q | Select-String -Pattern 'CUDA Version\s*:\s*([\d.]+)').Matches.Groups[1].Value } else { `$cuda_ver = `"未知`" } return `$cuda_ver } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } return `$torch_ver, `$xformers_ver } # 获取 HashTable 的值 function Get-HashValue { param( [hashtable]`$Hashtable, [string]`$Key, [object]`$Default = `$null ) if (`$Hashtable.ContainsKey(`$Key)) { return `$Hashtable[`$Key] } else { return `$Default } } # 获取可用的 PyTorch 类型 function Get-Avaliable-PyTorch-Type { `$content = `" import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 CUDA_TYPE = [ 'cu113', 'cu117', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu129', 'cu130', ] def get_avaliable_device() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() device_list = ['cpu'] if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): device_list.append('xpu') if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): device_list.append('directml') if compare_versions(cuda_comp_cap, '10.0') > 0: for ver in CUDA_TYPE: if compare_versions(ver, str(int(12.8 * 10))) >= 0: device_list.append(ver) else: for ver in CUDA_TYPE: if compare_versions(ver, str(int(cuda_support_ver * 10))) <= 0: device_list.append(ver) return ','.join(list(set(device_list))) if __name__ == '__main__': print(get_avaliable_device()) `".Trim() Print-Msg `"获取可用的 PyTorch 类型`" `$res = `$(python -c `"`$content`") return `$res -split ',' | ForEach-Object { `$_.Trim() } } # 获取 PyTorch 列表 function Get-PyTorch-List { `$pytorch_list = New-Object System.Collections.ArrayList `$supported_type = Get-Avaliable-PyTorch-Type # >>>>>>>>>> Start `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==1.12.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CUDA 11.3) + xFormers 0.0.14`" `"type`" = `"cu113`" `"supported`" = `"cu113`" -in `$supported_type `"torch`" = `"torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==1.12.1+cu113`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.13.1+cpu torchvision==0.14.1+cpu torchaudio==0.13.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 torch-directml==0.1.13.1.dev230413`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CUDA 11.7) + xFormers 0.0.16`" `"type`" = `"cu117`" `"supported`" = `"cu117`" -in `$supported_type `"torch`" = `"torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==1.13.1+cu117`" `"xformers`" = `"xformers==0.0.18`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.0 torch-directml==0.2.0.dev230426`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.0.0a0+gite9ebda2 torchvision==0.15.2a0+fa99a53 intel_extension_for_pytorch==2.0.110+gitc6ea20b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CUDA 11.8) + xFormers 0.0.18`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.0+cu118`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.1+cpu torchvision==0.15.2+cpu torchaudio==2.0.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CUDA 11.8) + xFormers 0.0.22`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.1+cu118`" `"xformers`" = `"xformers==0.0.22`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.0+cpu torchvision==0.16.0+cpu torchaudio==2.1.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi torchaudio==2.1.0a0+cxx11.abi intel_extension_for_pytorch==2.1.10+xpu`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Core Ultra)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+git7bcf7da torchvision==0.16.0+fbb4cc5 torchaudio==2.1.0+6ea1133 intel_extension_for_pytorch==2.1.20+git4849f3b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.1+cpu torchvision==0.16.1+cpu torchaudio==2.1.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 11.8) + xFormers 0.0.23`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu118 torchvision==0.16.1+cu118 torchaudio==2.1.1+cu118`" `"xformers`" = `"xformers==0.0.23+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 12.1) + xFormers 0.0.23`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu121 torchvision==0.16.1+cu121 torchaudio==2.1.1+cu121`" `"xformers`" = `"xformers===0.0.23`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.2+cpu torchvision==0.16.2+cpu torchaudio==2.1.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 11.8) + xFormers 0.0.23.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118`" `"xformers`" = `"xformers==0.0.23.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 12.1) + xFormers 0.0.23.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu121 torchvision==0.16.2+cu121 torchaudio==2.1.2+cu121`" `"xformers`" = `"xformers===0.0.23.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 11.8) + xFormers 0.0.24`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu118 torchvision==0.17.0+cu118 torchaudio==2.2.0+cu118`" `"xformers`" = `"xformers==0.0.24+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 12.1) + xFormers 0.0.24`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu121 torchvision==0.17.0+cu121 torchaudio==2.2.0+cu121`" `"xformers`" = `"xformers===0.0.24`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.1+cpu torchvision==0.17.1+cpu torchaudio==2.2.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 11.8) + xFormers 0.0.25`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu118 torchvision==0.17.1+cu118 torchaudio==2.2.1+cu118`" `"xformers`" = `"xformers==0.0.25+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 torch-directml==0.2.1.dev240521`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 12.1) + xFormers 0.0.25`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121`" `"xformers`" = `"xformers===0.0.25`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.2+cpu torchvision==0.17.2+cpu torchaudio==2.2.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 11.8) + xFormers 0.0.25.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu118 torchvision==0.17.2+cu118 torchaudio==2.2.2+cu118`" `"xformers`" = `"xformers==0.0.25.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 12.1) + xFormers 0.0.25.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu121 torchvision==0.17.2+cu121 torchaudio==2.2.2+cu121`" `"xformers`" = `"xformers===0.0.25.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.0+cpu torchvision==0.18.0+cpu torchaudio==2.3.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 11.8) + xFormers 0.0.26.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" `"xformers`" = `"xformers==0.0.26.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 12.1) + xFormers 0.0.26.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121`" `"xformers`" = `"xformers===0.0.26.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.1+cpu torchvision==0.18.1+cpu torchaudio==2.3.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 torch-directml==0.2.3.dev240715`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 11.8) + xFormers 0.0.27`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118`" `"xformers`" = `"xformers==0.0.27+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 12.1) + xFormers 0.0.27`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121`" `"xformers`" = `"xformers===0.0.27`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.0+cpu torchvision==0.19.0+cpu torchaudio==2.4.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 11.8) + xFormers 0.0.27.post2`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu118 torchvision==0.19.0+cu118 torchaudio==2.4.0+cu118`" `"xformers`" = `"xformers==0.0.27.post2+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 12.1) + xFormers 0.0.27.post2`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu121 torchvision==0.19.0+cu121 torchaudio==2.4.0+cu121`" `"xformers`" = `"xformers==0.0.27.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.1+cpu torchvision==0.19.1+cpu torchaudio==2.4.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CUDA 12.4) + xFormers 0.0.28.post1`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.4.1+cu124 torchvision==0.19.1+cu124 torchaudio==2.4.1+cu124`" `"xformers`" = `"xformers==0.0.28.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.0+cpu torchvision==0.20.0+cpu torchaudio==2.5.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CUDA 12.4) + xFormers 0.0.28.post2`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.0+cu124 torchvision==0.20.0+cu124 torchaudio==2.5.0+cu124`" `"xformers`" = `"xformers==0.0.28.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.1+cpu torchvision==0.20.1+cpu torchaudio==2.5.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CUDA 12.4) + xFormers 0.0.28.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124`" `"xformers`" = `"xformers==0.0.28.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+cpu torchvision==0.21.0+cpu torchaudio==2.6.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+xpu torchvision==0.21.0+xpu torchaudio==2.6.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.4) + xFormers 0.0.29.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.6) + xFormers 0.0.29.post3`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu126 torchvision==0.21.0+cu126 torchaudio==2.6.0+cu126`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+cpu torchvision==0.22.0+cpu torchaudio==2.7.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+xpu torchvision==0.22.0+xpu torchaudio==2.7.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu118 torchvision==0.22.0+cu118 torchaudio==2.7.0+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.6) + xFormers 0.0.30`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu126 torchvision==0.22.0+cu126 torchaudio==2.7.0+cu126`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.8) + xFormers 0.0.30`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu128 torchvision==0.22.0+cu128 torchaudio==2.7.0+cu128`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+cpu torchvision==0.22.1+cpu torchaudio==2.7.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+xpu torchvision==0.22.1+xpu torchaudio==2.7.1+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu118 torchvision==0.22.1+cu118 torchaudio==2.7.1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.6) + xFormers 0.0.31.post1`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu126 torchvision==0.22.1+cu126 torchaudio==2.7.1+cu126`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.8) + xFormers 0.0.31.post1`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu128 torchvision==0.22.1+cu128 torchaudio==2.7.1+cu128`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+cpu torchvision==0.23.0+cpu torchaudio==2.8.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+xpu torchvision==0.23.0+xpu torchaudio==2.8.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu128 torchvision==0.23.0+cu128 torchaudio==2.8.0+cu128`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.9)`" `"type`" = `"cu129`" `"supported`" = `"cu129`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129`" # `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 13.0)`" `"type`" = `"cu130`" `"supported`" = `"cu130`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU130 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null # <<<<<<<<<< End return `$pytorch_list } # 列出 PyTorch 列表 function List-PyTorch (`$pytorch_list) { Print-Msg `"PyTorch 版本列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"版本序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"PyTorch 版本`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"支持当前设备情况`" -ForegroundColor Blue for (`$i = 0; `$i -lt `$pytorch_list.Count; `$i++) { `$pytorch_hashtables = `$pytorch_list[`$i] `$count += 1 `$name = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"name`" `$supported = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"supported`" Write-Host `"- `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline if (`$supported) { Write-Host `"(支持✓)`" -ForegroundColor Green } else { Write-Host `"(不支持×)`" -ForegroundColor Red } } Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过 SD-Trainer Installer 更新检查`" } else { Check-SD-Trainer-Installer-Update } Set-uv PyPI-Mirror-Status `$pytorch_list = Get-PyTorch-List `$go_to = 0 `$to_exit = 0 `$torch_ver = `"`" `$xformers_ver = `"`" `$cuda_support_ver = Get-Drive-Support-CUDA-Version `$current_torch_ver, `$current_xformers_ver = Get-PyTorch-And-xFormers-Version `$after_list_model_option = `"`" while (`$True) { switch (`$after_list_model_option) { display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" List-PyTorch `$pytorch_list Print-Msg `"当前 PyTorch 版本: `$current_torch_ver`" Print-Msg `"当前 xFormers 版本: `$current_xformers_ver`" Print-Msg `"当前显卡驱动支持的最高 CUDA 版本: `$cuda_support_ver`" Print-Msg `"请选择 PyTorch 版本`" Print-Msg `"提示:`" Print-Msg `"1. PyTorch 版本通常来说选择最新版的即可`" Print-Msg `"2. 驱动支持的最高 CUDA 版本需要大于或等于要安装的 PyTorch 中所带的 CUDA 版本, 若驱动支持的最高 CUDA 版本低于要安装的 PyTorch 中所带的 CUDA 版本, 可尝试更新显卡驱动, 或者选择 CUDA 版本更低的 PyTorch`" Print-Msg `"3. 输入数字后回车, 或者输入 exit 退出 PyTorch 重装脚本`" if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建已启用, 指定安装的 PyTorch 序号: `$BuildWithTorch`" `$arg = `$BuildWithTorch `$go_to = 1 } else { `$arg = (Read-Host `"===========================================>`").Trim() } switch (`$arg) { exit { Print-Msg `"退出 PyTorch 重装脚本`" `$to_exit = 1 `$go_to = 1 } Default { try { # 检测输入是否符合列表 `$i = [int]`$arg if (!((`$i -ge 1) -and (`$i -le `$pytorch_list.Count))) { `$after_list_model_option = `"display_input_error`" break } `$pytorch_info = `$pytorch_list[(`$i - 1)] `$combination_name = Get-HashValue -Hashtable `$pytorch_info -Key `"name`" `$torch_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"torch`" `$xformers_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"xformers`" `$index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"index_mirror`" `$extra_index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"extra_index_mirror`" `$find_links = Get-HashValue -Hashtable `$pytorch_info -Key `"find_links`" if (`$null -ne `$index_mirror) { `$Env:PIP_INDEX_URL = `$index_mirror `$Env:UV_DEFAULT_INDEX = `$index_mirror } if (`$null -ne `$extra_index_mirror) { `$Env:PIP_EXTRA_INDEX_URL = `$extra_index_mirror `$Env:UV_INDEX = `$extra_index_mirror } if (`$null -ne `$find_links) { `$Env:PIP_FIND_LINKS = `$find_links `$Env:UV_FIND_LINKS = `$find_links } } catch { `$after_list_model_option = `"display_input_error`" break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否选择仅强制重装 ? (通常情况下不需要)`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { if (`$BuildWithTorchReinstall) { `$use_force_reinstall = `"yes`" } else { `$use_force_reinstall = `"no`" } } else { `$use_force_reinstall = (Read-Host `"===========================================>`").Trim() } if (`$use_force_reinstall -eq `"yes`" -or `$use_force_reinstall -eq `"y`" -or `$use_force_reinstall -eq `"YES`" -or `$use_force_reinstall -eq `"Y`") { `$force_reinstall_arg = `"--force-reinstall`" `$force_reinstall_status = `"启用`" } else { `$force_reinstall_arg = New-Object System.Collections.ArrayList `$force_reinstall_status = `"禁用`" } Print-Msg `"当前的选择: `$combination_name`" Print-Msg `"PyTorch: `$torch_ver`" Print-Msg `"xFormers: `$xformers_ver`" Print-Msg `"仅强制重装: `$force_reinstall_status`" Print-Msg `"是否确认安装?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$install_torch = `"yes`" } else { `$install_torch = (Read-Host `"===========================================>`").Trim() } if (`$install_torch -eq `"yes`" -or `$install_torch -eq `"y`" -or `$install_torch -eq `"YES`" -or `$install_torch -eq `"Y`") { Print-Msg `"重装 PyTorch 中`" if (`$USE_UV) { uv pip install `$torch_ver.ToString().Split() `$force_reinstall_arg if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } } else { python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } if (`$?) { Print-Msg `"安装 PyTorch 成功`" } else { Print-Msg `"安装 PyTorch 失败, 终止 PyTorch 重装进程`" Read-Host | Out-Null exit 1 } if (`$null -ne `$xformers_ver) { Print-Msg `"重装 xFormers 中`" if (`$USE_UV) { `$current_xf_ver = Get-xFormers-Version if (`$xformers_ver.Split(`"=`")[-1] -ne `$current_xf_ver) { Print-Msg `"卸载原有 xFormers 中`" python -m pip uninstall xformers -y } uv pip install `$xformers_ver `$force_reinstall_arg --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } } else { python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } if (`$?) { Print-Msg `"安装 xFormers 成功`" } else { Print-Msg `"安装 xFormers 失败, 终止 PyTorch 重装进程`" Read-Host | Out-Null exit 1 } } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 SD-Trainer Installer 更新检查 -DisableAutoApplyUpdate 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # SD-Trainer Installer 更新检测 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`" -Force } elseif ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"unet`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"vae`")) | Out-Null # FLUX CLIP `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"===========================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer Installer 构建模式已启用, 跳过 SD-Trainer Installer 更新检查`" } else { Check-SD-Trainer-Installer-Update } Check-Aria2-Version `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/models`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list } Print-Msg `"退出模型下载脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # SD-Trainer Installer 设置脚本 function Write-SD-Trainer-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # 获取 SD-Trainer Installer 自动检测更新设置 function Get-SD-Trainer-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 SD-Trainer Installer 自动应用更新设置 function Get-SD-Trainer-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取启动参数设置 function Get-Launch-Args-Setting { if (Test-Path `"`$PSScriptRoot/launch_args.txt`") { return Get-Content `"`$PSScriptRoot/launch_args.txt`" } else { return `"无`" } } # 获取自动创建快捷启动方式 function Get-Auto-Set-Launch-Shortcut-Setting { if (Test-Path `"`$PSScriptRoot/enable_shortcut.txt`") { return `"启用`" } else { return `"禁用`" } } # 获取 PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 SD-Trainer 运行环境检测配置 function Get-SD-Trainer-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"===========================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 SD-Trainer 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://ghproxy.1888866.xyz/github.com`" Print-Msg `" https://slink.ltd/https://github.com`" Print-Msg `" https://github.boki.moe/github.com`" Print-Msg `" https://github.moeyy.xyz/https://github.com`" Print-Msg `" https://gh-proxy.net/https://github.com`" Print-Msg `" https://gh-proxy.ygxz.in/https://github.com`" Print-Msg `" https://wget.la/https://github.com`" Print-Msg `" https://kkgithub.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD-Trainer Installer 自动检查更新设置 function Update-SD-Trainer-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer Installer 自动检测更新设置: `$(Get-SD-Trainer-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer Installer 自动更新检查`" Print-Msg `"2. 禁用 SD-Trainer Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 SD-Trainer Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD-Trainer Installer 自动应用更新设置 function Update-SD-Trainer-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer Installer 自动应用更新设置: `$(Get-SD-Trainer-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer Installer 自动应用更新`" Print-Msg `"2. 禁用 SD-Trainer Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD-Trainer 启动参数设置 function Update-SD-Trainer-Launch-Args-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 设置 SD-Trainer 启动参数`" Print-Msg `"2. 删除 SD-Trainer 启动参数`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入 SD-Trainer 启动参数`" Print-Msg `"提示:`" Print-Msg `"1. 保存启动参数后原有的启动参数将被覆盖`" Print-Msg `"2. SD-Trainer 可用的启动参数可阅读: https://github.com/Akegarasu/lora-scripts?tab=readme-ov-file#program-arguments`" Print-Msg `"3. Kohya GUI 可用的启动参数可阅读: https://github.com/bmaltais/kohya_ss?tab=readme-ov-file#starting-gui-service`" Print-Msg `"输入启动参数后回车保存`" `$sd_trainer_launch_args = Get-User-Input Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/launch_args.txt`" -Value `$sd_trainer_launch_args Print-Msg `"设置 SD-Trainer 启动参数成功, 使用的 SD-Trainer 启动参数为: `$sd_trainer_launch_args`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/launch_args.txt`" -Force -Recurse 2> `$null Print-Msg `"删除 SD-Trainer 启动参数成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 自动创建 SD-Trainer 快捷启动方式设置 function Auto-Set-Launch-Shortcut-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动创建 SD-Trainer 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动创建 SD-Trainer 快捷启动方式`" Print-Msg `"2. 禁用自动创建 SD-Trainer 快捷启动方式`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { New-Item -ItemType File -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force > `$null Print-Msg `"启用自动创建 SD-Trainer 快捷启动方式成功`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用自动创建 SD-Trainer 快捷启动方式成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 SD-Trainer Installer 更新 function Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -gt `$SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 有新版本可用`" Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"SD-Trainer Installer 已是最新版本`" } } # SD-Trainer 运行环境检测设置 function SD-Trainer-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer 运行环境检测设置: `$(Get-SD-Trainer-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer 运行环境检测`" Print-Msg `"2. 禁用 SD-Trainer 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if ((Test-Path `"`$PSScriptRoot/python/python.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`")) { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/git.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`")) { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/gui.py`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/kohya_gui.py`")) { `$sd_trainer_status = `"已安装`" } else { `$sd_trainer_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"SD-Trainer: `$sd_trainer_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 SD-Trainer Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 SD-Trainer Installer 文档 function Get-SD-Trainer-Installer-Help-Docs { Print-Msg `"调用浏览器打开 SD-Trainer Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"SD-Trainer Installer 自动检查更新: `$(Get-SD-Trainer-Installer-Auto-Check-Update-Setting)`" Print-Msg `"SD-Trainer Installer 自动应用更新: `$(Get-SD-Trainer-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"SD-Trainer 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"自动创建 SD-Trainer 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"SD-Trainer 运行环境检测设置: `$(Get-SD-Trainer-Env-Check-Setting)`" Print-Msg `"SD-Trainer 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 Github 镜像源设置`" Print-Msg `"5. 进入 SD-Trainer Installer 自动检查更新设置`" Print-Msg `"6. 进入 SD-Trainer Installer 自动应用更新设置`" Print-Msg `"7. 进入 SD-Trainer 启动参数设置`" Print-Msg `"8. 进入自动创建 SD-Trainer 快捷启动方式设置`" Print-Msg `"9. 进入 PyPI 镜像源设置`" Print-Msg `"10. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"11. 进入 SD-Trainer 运行环境检测设置`" Print-Msg `"12. 进入 SD-Trainer 内核路径前缀设置`" Print-Msg `"13. 更新 SD-Trainer Installer 管理脚本`" Print-Msg `"14. 检查环境完整性`" Print-Msg `"15. 查看 SD-Trainer Installer 文档`" Print-Msg `"16. 退出 SD-Trainer Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-Github-Mirror-Setting break } 5 { Update-SD-Trainer-Installer-Auto-Check-Update-Setting break } 6 { Update-SD-Trainer-Installer-Auto-Apply-Update-Setting break } 7 { Update-SD-Trainer-Launch-Args-Setting break } 8 { Auto-Set-Launch-Shortcut-Setting break } 9 { PyPI-Mirror-Setting break } 10 { PyTorch-CUDA-Memory-Alloc-Setting break } 11 { SD-Trainer-Env-Check-Setting break } 12 { Update-Core-Prefix-Setting break } 13 { Check-SD-Trainer-Installer-Update break } 14 { Check-Env break } 15 { Get-SD-Trainer-Installer-Help-Docs break } 16 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 SD-Trainer Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror ) & { `$prefix_list = @(`"core`", `"lora-scripts`", `"lora_scripts`", `"sd-trainer`", `"SD-Trainer`", `"sd_trainer`", `"lora-scripts`", `"lora-scripts-v1.5.1`", `"lora-scripts-v1.6.2`", `"lora-scripts-v1.7.3`", `"lora-scripts-v1.8.1`", `"lora-scripts-v1.9.0-cu124`", `"lora-scripts-v1.10.0`", `"lora-scripts-v1.12.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer Installer 版本和检查更新间隔 `$Env:SD_TRAINER_INSTALLER_VERSION = $SD_TRAINER_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:SD_TRAINER_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableGithubMirror 禁用 SD-Trainer Installer自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示符信息 function global:prompt { `"`$(Write-Host `"[SD-Trainer Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:SD_TRAINER_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # SD-Trainer Installer 更新检测 function global:Check-SD-Trainer-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_installer/sd_trainer_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:SD_TRAINER_INSTALLER_VERSION) { Print-Msg `"SD-Trainer Installer 有新版本可用`" Print-Msg `"调用 SD-Trainer Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_installer.ps1`" -InstallPath `"`$Env:SD_TRAINER_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 SD-Trainer Installer 管理脚本以应用更新, 回车退出 SD-Trainer Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"SD-Trainer Installer 已是最新版本`" } } # 安装绘世启动器 function global:Install-Hanamizuki { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe`", `"https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`", `"https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`" ) `$i = 0 if (!(Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX 未找到, 无法安装绘世启动器, 请检查 SD-Trainer 是否已正确安装, 或者尝试运行 SD-Trainer Installer 进行修复`" return } New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if (Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`") { Print-Msg `"绘世启动器已安装, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" } else { ForEach (`$url in `$urls) { Print-Msg `"下载绘世启动器中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" Move-Item -Path `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`" -Force Print-Msg `"绘世启动器安装成功, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载绘世启动器中`" } else { Print-Msg `"下载绘世启动器失败`" return } } } } `$content = `" @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=lora-scripts if exist ```"%~dp0%DefaultCorePrefix%```" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if ```"%%i```"==```"-CorePrefix```" ( set NextIsValue=1 ) ) ) if exist ```"%CorePrefixFile%```" ( for /f ```"delims=```" %%i in ('powershell -command ```"Get-Content -Path '%CorePrefixFile%'```"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f ```"delims=```" %%i in ('powershell -command ```"```$current_path = '%CurrentPath%'.Trim('/').Trim('\'); ```$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(```$origin_core_prefix)) { ```$to_path = ```$origin_core_prefix; ```$from_uri = New-Object System.Uri(```$current_path.Replace('\', '/') + '/'); ```$to_uri = New-Object System.Uri(```$to_path.Replace('\', '/')); ```$origin_core_prefix = ```$from_uri.MakeRelativeUri(```$to_uri).ToString().Trim('/') }; Write-Host ```$origin_core_prefix```"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist ```"%RootPath%```" ( cd /d ```"%RootPath%```" ) else ( echo %CorePrefix% not found echo Please check if SD-Trainer is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d ```"%CurrentPath%```" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d ```"%CurrentPath%```" pause exit 1 ) `".Trim() Set-Content -Encoding Default -Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/hanamizuki.bat`" -Value `$content Print-Msg `"检查绘世启动器运行环境`" if (!(Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`")) { if (Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/python`") { Print-Msg `"尝试将 Python 移动至 `$Env:SD_TRAINER_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/python`" `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Python 路径移动成功`" } else { Print-Msg `"Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境`" Print-Msg `"请关闭所有占用 Python 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 SD-Trainer Installer 修复环境`" } } if (!(Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/git/bin/git.exe`")) { if (Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/git`") { Print-Msg `"尝试将 Git 移动至 `$Env:SD_TRAINER_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/git`" `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Git 路径移动成功`" } else { Print-Msg `"Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境`" Print-Msg `"请关闭所有占用 Git 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 SD-Trainer Installer 修复环境`" } } Print-Msg `"检查绘世启动器运行环境结束`" } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:SD_TRAINER_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 SD-Trainer Installer 内置命令 function global:List-CMD { Write-Host `" ================================== SD-Trainer Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 SD-Trainer Installer 内置命令: Update-uv Update-Aria2 Check-SD-Trainer-Installer-Update Install-Hanamizuki Get-Core-Prefix List-CMD 更多帮助信息可在 SD-Trainer Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md `" } # 显示 SD-Trainer Installer 版本 function Get-SD-Trainer-Installer-Version { `$ver = `$([string]`$Env:SD_TRAINER_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer Installer 版本: v`${major}.`${minor}.`${micro}`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror Set-Github-Mirror PyPI-Mirror-Status if (Test-Path `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$Env:SD_TRAINER_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`" } Print-Msg `"激活 SD-Trainer Env`" Print-Msg `"更多帮助信息可在 SD-Trainer Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activate.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 SD-Trainer Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== SD-Trainer Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 SD-Trainer 的简单使用文档。 使用 SD-Trainer Installer 进行安装并安装成功后,将在当前目录生成 SD-Trainer 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - launch.ps1:启动 SD-Trainer。 - update.ps1:更新 SD-Trainer。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 models 文件夹中。 - reinstall_pytorch.ps1:重新安装 PyTorch 的脚本,在 PyTorch 出问题或者需要切换 PyTorch 版本时可使用。 - switch_branch.ps1:切换 SD-Trainer 分支。 - settings.ps1:管理 SD-Trainer Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - launch_sd_trainer_installer.ps1:获取最新的 SD-Trainer Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - lora-scripts / core:SD-Trainer 内核。 - models:使用模型下载脚本下载模型时模型的存放位置。 详细的 SD-Trainer Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md 其他的一些训练模型的教程: https://sd-moadel-doc.maozi.io https://rentry.org/59xed3 https://civitai.com/articles/2056 https://civitai.com/articles/124/lora-analogy-about-lora-trainning-and-using https://civitai.com/articles/143/some-shallow-understanding-of-lora-training-lora https://civitai.com/articles/632/why-this-lora-can-not-bring-good-result-lora https://civitai.com/articles/726/an-easy-way-to-make-a-cosplay-lora-cosplay-lora https://civitai.com/articles/2135/lora-quality-improvement-some-experiences-about-datasets-and-captions-lora https://civitai.com/articles/2297/ways-to-make-a-character-lora-that-is-easier-to-change-clothes-lora 更多详细的帮助可在下面的链接查看。 推荐的哔哩哔哩 UP 主: 青龙圣者:https://space.bilibili.com/219296 秋葉aaaki:https://space.bilibili.com/12566101 琥珀青葉:https://space.bilibili.com/507303431 观看这些 UP 主的视频可获得一些训练模型的教程。 ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one SD-Trainer 项目地址:https://github.com/Akegarasu/lora-scripts Kohya GUI 项目地址:https://github.com/bmaltais/kohya_ss ==================================================================== ########## 用户协议 ########## 使用该软件代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Launch-Script Write-Update-Script Write-Switch-Branch-Script Write-Launch-SD-Trainer-Install-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-SD-Trainer-Installer-Settings-Script Write-Env-Activate-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script Write-Hanamizuki-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-SD-Trainer-Installer-Config { Print-Msg "为 SD-Trainer Installer 管理脚本复制 SD-Trainer Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($DisableGithubMirror)) -and (Test-Path "$PSScriptRoot/disable_gh_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_gh_mirror.txt -> $InstallPath/disable_gh_mirror.txt" } elseif ((!($DisableGithubMirror)) -and (!($UseCustomGithubMirror)) -and (Test-Path "$PSScriptRoot/gh_mirror.txt") -and (!(Test-Path "$PSScriptRoot/disable_gh_mirror.txt"))) { Copy-Item -Path "$PSScriptRoot/gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/gh_mirror.txt -> $InstallPath/gh_mirror.txt" } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 写入启动绘世启动器脚本 function Write-Hanamizuki-Script { param ( [switch]$Force ) $content = " @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=lora-scripts if exist `"%~dp0%DefaultCorePrefix%`" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if `"%%i`"==`"-CorePrefix`" ( set NextIsValue=1 ) ) ) if exist `"%CorePrefixFile%`" ( for /f `"delims=`" %%i in ('powershell -command `"Get-Content -Path '%CorePrefixFile%'`"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f `"delims=`" %%i in ('powershell -command `"`$current_path = '%CurrentPath%'.Trim('/').Trim('\'); `$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix; `$from_uri = New-Object System.Uri(`$current_path.Replace('\', '/') + '/'); `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')); `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') }; Write-Host `$origin_core_prefix`"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist `"%RootPath%`" ( cd /d `"%RootPath%`" ) else ( echo %CorePrefix% not found echo Please check if SD-Trainer is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d `"%CurrentPath%`" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d `"%CurrentPath%`" pause exit 1 ) ".Trim() if ((!($Force)) -and (!(Test-Path "$InstallPath/hanamizuki.bat"))) { return } if (Test-Path "$InstallPath/hanamizuki.bat") { Print-Msg "更新 hanamizuki.bat 中" } else { Print-Msg "生成 hanamizuki.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/hanamizuki.bat" -Value $content } # 安装绘世启动器 function Install-Hanamizuki { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe", "https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe", "https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe" ) $i = 0 if (!($InstallHanamizuki)) { return } New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null if (Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe") { Print-Msg "绘世启动器已安装, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" } else { ForEach ($url in $urls) { Print-Msg "下载绘世启动器中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/hanamizuki_tmp.exe" Move-Item -Path "$Env:CACHE_HOME/hanamizuki_tmp.exe" "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe" -Force Print-Msg "绘世启动器安装成功, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载绘世启动器中" } else { Print-Msg "下载绘世启动器失败" return } } } } } # 配置绘世启动器运行环境 function Configure-Hanamizuki-Env { if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe")) { return } Write-Hanamizuki-Script -Force Print-Msg "检查绘世启动器运行环境" if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { if (Test-Path "$InstallPath/python") { Print-Msg "尝试将 Python 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/python" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Python 路径移动成功" } else { Print-Msg "Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境" Print-Msg "请关闭所有占用 Python 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 SD-Trainer Installer 修复环境" } } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { if (Test-Path "$InstallPath/git") { Print-Msg "尝试将 Git 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/git" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Git 路径移动成功" } else { Print-Msg "Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境" Print-Msg "请关闭所有占用 Git 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 SD-Trainer Installer 修复环境" } } Print-Msg "检查绘世启动器运行环境结束" } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 SD-Trainer 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 SD-Trainer Installer, 更多的说明请阅读 SD-Trainer Installer 使用文档" Print-Msg "SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" if ((Test-Path "$PSScriptRoot/install_sd_trainer.txt") -or ($InstallBranch -eq "sd_trainer")) { Print-Msg "检测到 install_sd_trainer.txt 配置文件 / 命令行参数 -InstallBranch sd_trainer, 选择安装 Akegarasu/SD-Trainer" } elseif ((Test-Path "$PSScriptRoot/install_kohya_gui.txt") -or ($InstallBranch -eq "kohya_gui")) { Print-Msg "检测到 install_kohya_gui.txt 配置文件 / 命令行参数 -InstallBranch kohya_gui, 选择安装 bmaltais/Kohya GUI" } else { Print-Msg "未指定安装的训练器, 默认选择安装 Akegarasu/SD-Trainer" } Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-SD-Trainer-Installer-Config if ($BuildMode) { Use-Build-Mode Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "SD-Trainer 环境构建完成, 路径: $InstallPath" } else { Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "SD-Trainer 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 SD-Trainer 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 SD-Trainer Installer 使用文档" Print-Msg "SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md" Print-Msg "退出 SD-Trainer Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWithTorch", $BuildWithTorch) if ($BuildWithTorchReinstall) { $launch_args.Add("-BuildWithTorchReinstall", $true) } if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWitchBranch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchBranch", $BuildWitchBranch) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer 分支切换脚本中" . "$InstallPath/switch_branch.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($LaunchArg) { $launch_args.Add("-LaunchArg", $LaunchArg) } if ($EnableShortcut) { $launch_args.Add("-EnableShortcut", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer 启动脚本中" . "$InstallPath/launch.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-SD-Trainer-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 SD-Trainer 的绝对路径>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-InstallBranch <安装的 SD-Trainer 分支>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-BuildMode] [-BuildWithUpdate] [-BuildWithLaunch] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-BuildWitchBranch <SD-Trainer 分支编号>] [-PyTorchPackage <PyTorch 软件包>] [-InstallHanamizuki] [-NoCleanCache] [-xFormersPackage <xFormers 软件包>] [-DisableUpdate] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-LaunchArg <SD-Trainer 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -InstallPath <安装 SD-Trainer 的绝对路径> 指定 SD-Trainer Installer 安装 SD-Trainer 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 SD-Trainer Installer 安装 SD-Trainer 到 D:\Donwload 这个路径 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -InstallBranch <安装的 SD-Trainer 分支> 指定 SD-Trainer Installer 安装的 SD-Trainer 分支 (sd_trainer, kohya_gui) 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallBranch `"kohya_gui`", 这将指定 SD-Trainer Installer 安装 bmaltais/Kohya GUI 分支 未指定该参数时, 默认安装 Akegarasu/SD-Trainer 分支 支持指定安装的分支如下: sd_trainer: Akegarasu/SD-Trainer kohya_gui: bmaltais/Kohya GUI -UseUpdateMode 指定 SD-Trainer Installer 使用更新模式, 只对 SD-Trainer Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 SD-Trainer Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 SD-Trainer Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableGithubMirror 禁用 SD-Trainer Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -BuildMode 启用 SD-Trainer Installer 构建模式, 在基础安装流程结束后将调用 SD-Trainer Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 SD-Trainer Installer 的执行, 而是直接退出 当指定调用多个 SD-Trainer Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorch, -BuildWithTorchReinstall 参数) - switch_branch.ps1 (对应 -BuildWitchBranch 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - launch.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 update.ps1 脚本, 更新 SD-Trainer 内核 -BuildWithLaunch (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 launch.ps1 脚本, 执行启动 SD-Trainer 前的环境检查流程, 但跳过启动 SD-Trainer -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式, 并且添加 -BuildWithTorch) 在 SD-Trainer Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -BuildWitchBranch <SD-Trainer 分支编号> (需添加 -BuildMode 启用 SD-Trainer Installer 构建模式) SD-Trainer Installer 执行完基础安装流程后调用 SD-Trainer Installer 的 switch_branch.ps1 脚本, 根据 SD-Trainer 分支编号切换到对应的 SD-Trainer 分支 SD-Trainer 分支编号可运行 switch_branch.ps1 脚本进行查看 -PyTorchPackage <PyTorch 软件包> (需要同时搭配 -xFormersPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 PyTorch 版本, 如 -PyTorchPackage `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" -xFormersPackage <xFormers 软件包> (需要同时搭配 -PyTorchPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 xFormers 版本, 如 -xFormersPackage `"xformers===0.0.26.post1+cu118`" -InstallHanamizuki 安装绘世启动器, 并生成 hanamizuki.bat 用于启动绘世启动器 -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 禁用 SD-Trainer Installer 更新检查 -DisableHuggingFaceMirror (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -LaunchArg <SD-Trainer 启动参数> (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 设置 SD-Trainer 自定义启动参数, 如启用 --skip-prepare-environment 和 --dev, 则使用 -LaunchArg `"--skip-prepare-environment --dev`" 进行启用 -EnableShortcut (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 创建 SD-Trainer 启动快捷方式 -DisableCUDAMalloc (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 禁用 SD-Trainer Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 禁用 SD-Trainer Installer 检查 SD-Trainer 运行环境中存在的问题, 禁用后可能会导致 SD-Trainer 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate (仅在 SD-Trainer Installer 构建模式下生效, 并且只作用于 SD-Trainer Installer 管理脚本) 禁用 SD-Trainer Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-SD-Trainer-Installer-Version Get-SD-Trainer-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "SD-Trainer Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/sd_trainer_installer.ps1
PowerShell
agpl-3.0
453,413
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "SD-Trainer-Script"), [string]$PyTorchMirrorType, [string]$InstallBranch, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithLaunch, [int]$BuildWithTorch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [int]$BuildWitchBranch, [string]$PyTorchPackage, [string]$xFormersPackage, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [string]$UseCustomHuggingFaceMirror, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("core", "sd-scripts", "SimpleTuner", "ai-toolkit", "finetrainers", "diffusion-pipe", "musubi-tuner") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "core" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # SD-Trainer-Script Installer 版本和检查更新间隔 $SD_TRAINER_SCRIPT_INSTALLER_VERSION = 201 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { "$PIP_EXTRA_INDEX_ADDR_ORI $PIP_EXTRA_INDEX_ADDR" } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_FIND_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121/torch_stable.html" $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # Github 镜像源列表 $GITHUB_MIRROR_LIST = @( "https://ghfast.top/https://github.com", "https://mirror.ghproxy.com/https://github.com", "https://ghproxy.net/https://github.com", "https://gh.api.99988866.xyz/https://github.com", "https://gh-proxy.com/https://github.com", "https://ghps.cc/https://github.com", "https://gh.idayer.com/https://github.com", "https://ghproxy.1888866.xyz/github.com", "https://slink.ltd/https://github.com", "https://github.boki.moe/github.com", "https://github.moeyy.xyz/https://github.com", "https://gh-proxy.net/https://github.com", "https://gh-proxy.ygxz.in/https://github.com", "https://wget.la/https://github.com", "https://kkgithub.com", "https://gitclone.com/github.com" ) # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # SD-Trainer-Script 仓库地址 $SD_TRAINER_SCRIPT_REPO = if ((Test-Path "$PSScriptRoot/install_sd_scripts.txt") -or ($InstallBranch -eq "sd_scripts")) { "https://github.com/kohya-ss/sd-scripts" } elseif ((Test-Path "$PSScriptRoot/install_simple_tuner.txt") -or ($InstallBranch -eq "simple_tuner")) { "https://github.com/bghira/SimpleTuner" } elseif ((Test-Path "$PSScriptRoot/install_ai_toolkit.txt") -or ($InstallBranch -eq "ai_toolkit")) { "https://github.com/ostris/ai-toolkit" } elseif ((Test-Path "$PSScriptRoot/install_finetrainers.txt") -or ($InstallBranch -eq "finetrainers")) { "https://github.com/a-r-r-o-w/finetrainers" } elseif ((Test-Path "$PSScriptRoot/install_diffusion_pipe.txt") -or ($InstallBranch -eq "diffusion_pipe")) { "https://github.com/tdrussell/diffusion-pipe" } elseif ((Test-Path "$PSScriptRoot/install_musubi_tuner.txt") -or ($InstallBranch -eq "musubi_tuner")) { "https://github.com/kohya-ss/musubi-tuner" } else { "https://github.com/kohya-ss/sd-scripts" } # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $PYTHON_SCRIPTS_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $GIT_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/git/bin" $Env:PATH = "$PYTHON_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_EXTRA_PATH$([System.IO.Path]::PathSeparator)$GIT_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[SD-Trainer-Script Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { $ver = $([string]$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "SD-Trainer-Script Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / 命令行参数 -DisableProxy, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / 命令行参数 -UseCustomProxy, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / 命令行参数 -DisableUV, 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # Github 镜像测试 function Set-Github-Mirror { $Env:GIT_CONFIG_GLOBAL = "$InstallPath/.gitconfig" # 设置 Git 配置文件路径 if (Test-Path "$InstallPath/.gitconfig") { Remove-Item -Path "$InstallPath/.gitconfig" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory "*" git config --global core.longpaths true if ((Test-Path "$PSScriptRoot/disable_gh_mirror.txt") -or ($DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg "检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / 命令行参数 -DisableGithubMirror, 禁用 Github 镜像源" return } # 使用自定义 Github 镜像源 if ((Test-Path "$PSScriptRoot/gh_mirror.txt") -or ($UseCustomGithubMirror)) { if ($UseCustomGithubMirror) { $github_mirror = $UseCustomGithubMirror } else { $github_mirror = Get-Content "$PSScriptRoot/gh_mirror.txt" } git config --global url."$github_mirror".insteadOf "https://github.com" Print-Msg "检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / 命令行参数 -UseCustomGithubMirror, 已读取 Github 镜像源配置文件并设置 Github 镜像源" return } # 自动检测可用镜像源并使用 $status = 0 ForEach($i in $GITHUB_MIRROR_LIST) { Print-Msg "测试 Github 镜像源: $i" if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } git clone "$i/licyk/empty" "$Env:CACHE_HOME/github-mirror-test" --quiet if ($?) { Print-Msg "该 Github 镜像源可用" $github_mirror = $i $status = 1 break } else { Print-Msg "镜像源不可用, 更换镜像源进行测试" } } if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } if ($status -eq 0) { Print-Msg "无可用 Github 镜像源, 取消使用 Github 镜像源" } else { Print-Msg "设置 Github 镜像源" git config --global url."$github_mirror".insteadOf "https://github.com" } } # 安装 SD-Trainer-Script function Install-SD-Trainer-Script { $status = 0 if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX")) { $status = 1 } else { $items = Get-ChildItem "$InstallPath/$Env:CORE_PREFIX" if ($items.Count -eq 0) { $status = 1 } } $path = "$InstallPath/$Env:CORE_PREFIX" $cache_path = "$Env:CACHE_HOME/sd-scripts_tmp" if ($status -eq 1) { Print-Msg "正在下载 SD-Trainer-Script" # 清理缓存路径 if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } git clone --recurse-submodules $SD_TRAINER_SCRIPT_REPO "$cache_path" if ($?) { # 检测是否下载成功 # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Print-Msg "SD-Trainer-Script 安装成功" } else { Print-Msg "SD-Trainer-Script 安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "SD-Trainer-Script 已安装" } Print-Msg "安装 SD-Trainer-Script 子模块中" git -C "$InstallPath/$Env:CORE_PREFIX" submodule init git -C "$InstallPath/$Env:CORE_PREFIX" submodule update if ($?) { Print-Msg "SD-Trainer-Script 子模块安装成功" } else { Print-Msg "SD-Trainer-Script 子模块安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 设置 PyTorch 镜像源 function Get-PyTorch-Mirror ($pytorch_package) { # 获取 PyTorch 的版本 $torch_part = @($pytorch_package -split ' ' | Where-Object { $_ -like "torch==*" })[0] if ($PyTorchMirrorType) { Print-Msg "使用指定的 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } elseif ($torch_part) { # 获取 PyTorch 镜像源类型 if ($torch_part.split("+") -eq $torch_part) { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' if __name__ == '__main__': print(get_pytorch_mirror_type('$torch_part', use_xpu=True)) ".Trim() $mirror_type = $(python -c "$content") } else { $mirror_type = $torch_part.Split("+")[-1] } Print-Msg "PyTorch 镜像源类型: $mirror_type" } else { Print-Msg "未获取到 PyTorch 版本, 无法确定镜像源类型, 可能导致 PyTorch 安装失败" $mirror_type = "null" } # 设置对应的镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 为 PyTorch 获取合适的 CUDA 版本类型 function Get-Appropriate-CUDA-Version-Type { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def select_avaliable_type() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() if compare_versions(cuda_support_ver, '13.0') >= 0: return 'cu130' elif compare_versions(cuda_support_ver, '12.9') >= 0: return 'cu129' elif compare_versions(cuda_support_ver, '12.8') >= 0: return 'cu128' elif compare_versions(cuda_support_ver, '12.6') >= 0: return 'cu126' elif compare_versions(cuda_support_ver, '12.4') >= 0: return 'cu124' elif compare_versions(cuda_support_ver, '12.1') >= 0: return 'cu121' elif compare_versions(cuda_support_ver, '11.8') >= 0: return 'cu118' elif compare_versions(cuda_comp_cap, '10.0') > 0: return 'cu128' # RTX 50xx elif compare_versions(cuda_comp_cap, '0.0') > 0: return 'cu118' # 其他 Nvidia 显卡 else: gpus = get_gpu_list() if any([ x for x in gpus if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): return 'xpu' if any([ x for x in gpus if 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): return 'cu118' return 'cpu' if __name__ == '__main__': print(select_avaliable_type()) ".Trim() return $(python -c "$content") } # 获取合适的 PyTorch / xFormers 版本 function Get-PyTorch-And-xFormers-Package { Print-Msg "设置 PyTorch 和 xFormers 版本" if ($PyTorchPackage) { # 使用自定义的 PyTorch / xFormers 版本 if ($xFormersPackage){ return $PyTorchPackage, $xFormersPackage } else { return $PyTorchPackage, $null } } if ($PyTorchMirrorType) { Print-Msg "根据 $PyTorchMirrorType 类型的 PyTorch 镜像源配置 PyTorch 组合" $appropriate_cuda_version = $PyTorchMirrorType } else { $appropriate_cuda_version = Get-Appropriate-CUDA-Version-Type } switch ($appropriate_cuda_version) { cu130 { $pytorch_package = "torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130" $xformers_package = "xformers==0.0.33" break } cu129 { $pytorch_package = "torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129" $xformers_package = "xformers==0.0.32.post2" break } cu128 { $pytorch_package = "torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128" $xformers_package = "xformers==0.0.33" break } cu126 { $pytorch_package = "torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126" $xformers_package = "xformers==0.0.33" break } cu124 { $pytorch_package = "torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124" $xformers_package = "xformers==0.0.29.post3" break } cu121 { $pytorch_package = "torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121" $xformers_package = "xformers===0.0.27" break } cu118 { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } xpu { $pytorch_package = "torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu" $xformers_package = $null break } cpu { $pytorch_package = "torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu" $xformers_package = $null break } Default { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } } return $pytorch_package, $xformers_package } # 安装 PyTorch function Install-PyTorch { $pytorch_package, $xformers_package = Get-PyTorch-And-xFormers-Package $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror $pytorch_package # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch: $pytorch_package" Print-Msg "将要安装的 xFormers: $xformers_package" Print-Msg "检测是否需要安装 PyTorch" python -m pip show torch --quiet 2> $null if (!($?)) { Print-Msg "安装 PyTorch 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() } } else { python -m pip install $pytorch_package.ToString().Split() } if ($?) { Print-Msg "PyTorch 安装成功" } else { Print-Msg "PyTorch 安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch 已安装, 无需再次安装" } Print-Msg "检测是否需要安装 xFormers" python -m pip show xformers --quiet 2> $null if (!($?)) { if ($xformers_package) { Print-Msg "安装 xFormers 中" if ($USE_UV) { uv pip install $xformers_package.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $xformers_package.ToString().Split() --no-deps } } else { python -m pip install $xformers_package.ToString().Split() --no-deps } if ($?) { Print-Msg "xFormers 安装成功" } else { Print-Msg "xFormers 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg "xFormers 已安装, 无需再次安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 SD-Trainer-Script 依赖 function Install-SD-Trainer-Script-Dependence { # 记录脚本所在路径 $current_path = $(Get-Location).ToString() Set-Location "$InstallPath/$Env:CORE_PREFIX" $no_requirements_file = $false if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/requirements.txt")) { $no_requirements_file = $true } Print-Msg "安装 SD-Trainer-Script 依赖中" if ($USE_UV) { if ($no_requirements_file) { uv pip install -e . } else { uv pip install -r requirements.txt } if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" if ($no_requirements_file) { python -m pip install -e . } else { python -m pip install -r requirements.txt } } } else { if ($no_requirements_file) { python -m pip install -e . } else { python -m pip install -r requirements.txt } } if ($?) { Print-Msg "SD-Trainer-Script 依赖安装成功" } else { Print-Msg "SD-Trainer-Script 依赖安装失败, 终止 SD-Trainer-Script 安装进程, 可尝试重新运行 SD-Trainer-Script Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } Set-Location "$current_path" } # 安装 Python 软件包 function Install-Python-Package ($pkg) { Print-Msg "安装 $pkg 软件包中" if ($USE_UV) { uv pip install $pkg.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pkg.ToString().Split() } } else { python -m pip install $pkg.ToString().Split() } if ($?) { Print-Msg "安装 $pkg 软件包安装成功" } else { Print-Msg "安装 $pkg 软件包安装失败, 终止 SD-Trainer-Scripts 安装进程, 可尝试重新运行 SD-Trainer-Scripts Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 安装 function Check-Install { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null Print-Msg "检测是否安装 Python" if ((Test-Path "$InstallPath/python/python.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } Print-Msg "检测是否安装 Git" if ((Test-Path "$InstallPath/git/bin/git.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if ((Test-Path "$InstallPath/git/bin/aria2c.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/aria2c.exe")) { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Set-Github-Mirror Install-SD-Trainer-Script Install-PyTorch Install-SD-Trainer-Script-Dependence Install-Python-Package "lycoris-lora dadaptation open-clip-torch wandb tensorboard" # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 训练模板脚本 function Write-Train-Script { $content = "################################################# # 初始化基础环境变量, 以正确识别到运行环境 & `"`$PSScriptRoot/init.ps1`" Set-Location `$PSScriptRoot # 此处的代码不要修改或者删除, 否则可能会出现意外情况 # # SD-Trainer-Script 环境初始化后提供以下变量便于使用 # # `${ROOT_PATH} 当前目录 # `${SD_SCRIPTS_PATH} 训练脚本所在目录 # `${DATASET_PATH} 数据集目录 # `${MODEL_PATH} 模型下载器下载的模型路径 # `${GIT_EXEC} Git 路径 # `${PYTHON_EXEC} Python 解释器路径 # # 下方可编写训练代码 # 编写训练命令可参考: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md#%E7%BC%96%E5%86%99%E8%AE%AD%E7%BB%83%E8%84%9A%E6%9C%AC # 编写结束后, 该文件必须使用 UTF-8 with BOM 编码保存 ################################################# ################################################# Write-Host `"训练结束, 退出训练脚本`" Read-Host | Out-Null # 训练结束后保持控制台不被关闭 ".Trim() if (!(Test-Path "$InstallPath/train.ps1")) { Print-Msg "生成 train.ps1 中" Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/train.ps1" -Value $content } } # 初始化脚本 function Write-Library-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableUV, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableUV] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer-Script Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer-Script Installer 更新检查 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableUV 禁用 SD-Trainer-Script Installer使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableCUDAMalloc 禁用 SD-Trainer-Script Installer通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 SD-Trainer-Script Installer 检查 SD-Trainer-Script 运行环境中存在的问题, 禁用后可能会导致 SD-Trainer-Script 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # SD-Trainer-Script Installer 更新检测 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer-Script Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer-Script Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 从 pyproject.toml 中解析出依赖列表 function Get-Requirement-From-PyProject-File (`$pyproj_toml_path, `$save_path, `$deps_type = `"pip`") { `$content = Get-Content -Path `$pyproj_toml_path -Raw if (`$deps_type -eq `"pip`") { `$dependencies = `$content | Select-String -Pattern '(?ms)\bdependencies\s*=\s*\[(.*?)\]' | ForEach-Object { `$_.Matches.Groups[1].Value } `$clean_deps = `$dependencies -split '\r?\n' | Where-Object { `$_.Trim() -ne '' -and -not `$_.Trim().StartsWith('#') -and `$_.Contains('`"') } | ForEach-Object { (`$_.Split('#')[0].Trim() -replace '`"|,', '').Trim() } } elseif (`$deps_type -eq `"poetry`") { `$exclude_packages = @('python') `$deps_content = [regex]::Match( `$content, '(?ms)\[tool\.poetry\.dependencies\](.*?)(?=\n\[|\Z)' ).Groups[1].Value `$clean_deps = `$deps_content -split '\r?\n' | ForEach-Object { `$line = `$_.Trim() if (-not `$line) { return } if (`$line -match '^([\w-]+)\s*=\s*`"([^`"]+)`"') { `$package = `$matches[1] if (`$exclude_packages -contains `$package) { return } `$version = `$matches[2] -replace '^\^' if (`$version -eq '*') { `$package } else { if (`$version -match '^[<>=!]') { `"`$package`$version`" } else { `"`$package==`$version`" } } } elseif (`$line -match '^([\w-]+)\s*=\s*{\s*.*version\s*=\s*`"([^`"]+)`".*?}') { `$package = `$matches[1] if (`$exclude_packages -contains `$package) { return } `$version = `$matches[2] -replace '^\^' if (`$version -eq '*') { `$package } else { if (`$version -match '^[<>=!]') { `"`$package`$version`" } else { `"`$package==`$version`" } } } elseif (`$line -match '^([\w-]+)\s*=\s*{') { `$package = `$matches[1] if (`$exclude_packages -contains `$package) { return } `$package } } | Where-Object { `$_ } } `$utf8_encoding = New-Object System.Text.UTF8Encoding(`$false) `$stream_writer = [System.IO.StreamWriter]::new(`"`$save_path`", `$false, `$utf8_encoding) foreach (`$dependency in `$clean_deps) { `$stream_writer.WriteLine(`$dependency) } `$stream_writer.Close() } # 解析 kohya-ss/musubi-tuner 分支的依赖列表 function Get-PyProject-Requirement { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"kohya-ss/musubi-tuner`") -or (`$branch -eq `"kohya-ss/musubi-tuner.git`")) { `$pyproj_toml_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/pyproject.toml`" `$req_path = `"`$Env:CACHE_HOME/requirements.txt`" Get-Requirement-From-PyProject-File `"`$pyproj_toml_path`" `"`$req_path`" } return `$req_path } # 检查 SD-Trainer-Scripts 依赖完整性 function Check-SD-Trainer-Scripts-Requirements { `$content = `" import inspect import platform import re import os import sys import copy import logging import argparse import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--requirement-path```", type=_normalized_filepath, default=None, help=```"依赖文件路径```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"Requirement Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True def validate_requirements(requirement_path: str | Path) -> bool: ```"```"```"检测环境依赖是否完整 Args: requirement_path (str | Path): 依赖文件路径 Returns: bool: 如果有缺失依赖则返回````False```` ```"```"```" origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) for package in requires: if not is_package_installed(package): return False return True def main() -> None: requirement_path = COMMAND_ARGS.requirement_path if not os.path.isfile(requirement_path): logger.error(```"依赖文件未找到, 无法检查运行环境```") sys.exit(1) logger.debug(```"检测运行环境中```") print(validate_requirements(requirement_path)) logger.debug(```"环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 SD-Trainer-Scripts 内核依赖完整性中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_sd_trainer_requirement.py`" -Value `$content `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements_versions.txt`" if (!(Test-Path `"`$dep_path`")) { `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements.txt`" } if (!(Test-Path `"`$dep_path`")) { `$dep_path = Get-PyProject-Requirement } if (!(Test-Path `"`$dep_path`")) { Print-Msg `"未检测到 SD-Trainer-Scripts 依赖文件, 跳过依赖完整性检查`" return } `$status = `$(python `"`$Env:CACHE_HOME/check_sd_trainer_requirement.py`" --requirement-path `"`$dep_path`") if (`$status -eq `"False`") { Print-Msg `"检测到 SD-Trainer-Scripts 内核有依赖缺失, 安装 SD-Trainer-Scripts 依赖中`" if (`$USE_UV) { uv pip install -r `"`$dep_path`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$dep_path`" } } else { python -m pip install -r `"`$dep_path`" } if (`$?) { Print-Msg `"SD-Trainer-Scripts 依赖安装成功`" } else { Print-Msg `"SD-Trainer-Scripts 依赖安装失败, 这将会导致 SD-Trainer-Scripts 缺失依赖无法正常运行`" } } else { Print-Msg `"SD-Trainer-Scripts 无缺失依赖`" } } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 Numpy 版本 function Check-Numpy-Version { `$content = `" import importlib.metadata from importlib.metadata import version try: ver = int(version('numpy').split('.')[0]) except: ver = -1 if ver > 1: print(True) else: print(False) `".Trim() Print-Msg `"检查 Numpy 版本中`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"检测到 Numpy 版本大于 1, 这可能导致部分组件出现异常, 尝试重装中`" if (`$USE_UV) { uv pip install `"numpy==1.26.4`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `"numpy==1.26.4`" } } else { python -m pip install `"numpy==1.26.4`" } if (`$?) { Print-Msg `"Numpy 重新安装成功`" } else { Print-Msg `"Numpy 重新安装失败, 这可能导致部分功能异常`" } } else { Print-Msg `"Numpy 无版本问题`" } } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 SD-Trainer-Script 运行环境 function Check-SD-Trainer-Script-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 SD-Trainer-Script 运行环境检测, 这可能会导致 SD-Trainer-Script 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 SD-Trainer-Script 运行环境中`" } Check-SD-Trainer-Scripts-Requirements Fix-PyTorch Check-Onnxruntime-GPU Check-Numpy-Version Check-MS-VCPP-Redistributable Print-Msg `"SD-Trainer-Script 运行环境检查完成`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建模式已启用, 跳过 SD-Trainer-Script Installer 更新检查`" } else { Check-SD-Trainer-Script-Installer-Update } Set-HuggingFace-Mirror Set-uv PyPI-Mirror-Status `$current_path = `$(Get-Location).ToString() Set-Location `"`$PSScriptRoot/`$Env:CORE_PREFIX`" Check-SD-Trainer-Script-Env Set-Location `"`$current_path`" Set-PyTorch-CUDA-Memory-Alloc `$Global:ROOT_PATH = `$PSScriptRoot `$Global:SD_SCRIPTS_PATH = [System.IO.Path]::GetFullPath(`"`$ROOT_PATH/`$Env:CORE_PREFIX`") `$Global:DATASET_PATH = [System.IO.Path]::GetFullPath(`"`$ROOT_PATH/datasets`") `$Global:MODEL_PATH = [System.IO.Path]::GetFullPath(`"`$ROOT_PATH/models`") `$Global:OUTPUT_PATH = [System.IO.Path]::GetFullPath(`"`$ROOT_PATH/outputs`") `$Global:GIT_EXEC = [System.IO.Path]::GetFullPath(`$(Get-Command git -ErrorAction SilentlyContinue).Source) `$Global:PYTHON_EXEC = [System.IO.Path]::GetFullPath(`$(Get-Command python -ErrorAction SilentlyContinue).Source) Print-Msg `"可用的预设变量`" Print-Msg `"ROOT_PATH: `$ROOT_PATH`" Print-Msg `"SD_SCRIPTS_PATH: `$SD_SCRIPTS_PATH`" Print-Msg `"DATASET_PATH: `$DATASET_PATH`" Print-Msg `"MODEL_PATH: `$MODEL_PATH`" Print-Msg `"OUTPUT_PATH: `$OUTPUT_PATH`" Print-Msg `"GIT_EXEC: `$GIT_EXEC`" Print-Msg `"PYTHON_EXEC: `$PYTHON_EXEC`" Print-Msg `"初始化环境完成`" } ################### Main ".Trim() if (Test-Path "$InstallPath/init.ps1") { Print-Msg "更新 init.ps1 中" } else { Print-Msg "生成 init.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/init.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `"`$PIP_EXTRA_INDEX_ADDR_ORI `$PIP_EXTRA_INDEX_ADDR`" } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer-Script Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer-Script Installer 更新检查 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD-Trainer-Script Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # SD-Trainer-Script Installer 更新检测 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer-Script Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer-Script Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建模式已启用, 跳过 SD-Trainer-Script Installer 更新检查`" } else { Check-SD-Trainer-Script-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 SD-Trainer-Script 是否已正确安装, 或者尝试运行 SD-Trainer-Script Installer 进行修复`" Read-Host | Out-Null return } Print-Msg `"拉取 SD-Trainer-Script 更新内容中`" Fix-Git-Point-Off-Set `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$core_origin_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" fetch --recurse-submodules --all if (`$?) { Print-Msg `"应用 SD-Trainer-Script 更新中`" `$commit_hash = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" reset --hard `"`$remote_branch`" --recurse-submodules `$core_latest_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$core_origin_ver -eq `$core_latest_ver) { Print-Msg `"SD-Trainer-Script 已为最新版`" `$core_update_msg = `"已为最新版, 当前版本:`$core_origin_ver`" } else { Print-Msg `"SD-Trainer-Script 更新成功`" `$core_update_msg = `"更新成功, 版本:`$core_origin_ver -> `$core_latest_ver`" } } else { Print-Msg `"拉取 SD-Trainer-Script 更新内容失败`" Print-Msg `"更新 SD-Trainer-Script 失败, 请检查控制台日志。可尝试重新运行 SD-Trainer-Script Installer 更新脚本进行重试`" } Print-Msg `"退出 SD-Trainer-Script 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 分支切换脚本 function Write-Switch-Branch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWitchBranch, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchBranch <SD-Trainer-Script 分支编号>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer-Script Installer 构建模式 -BuildWitchBranch <SD-Trainer-Script 分支编号> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 switch_branch.ps1 脚本, 根据 SD-Trainer-Script 分支编号切换到对应的 SD-Trainer-Script 分支 SD-Trainer-Script 分支编号可运行 switch_branch.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer-Script Installer 更新检查 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD-Trainer-Script Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # SD-Trainer-Script Installer 更新检测 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer-Script Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer-Script Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 获取 SD-Trainer-Script 分支 function Get-SD-Trainer-Script-Branch { `$remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null) if (`$ref -eq `$null) { `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h`") } return `"`$(`$remote.Split(`"/`")[-2])/`$(`$remote.Split(`"/`")[-1]) `$([System.IO.Path]::GetFileName(`$ref))`" } # 切换 SD-Trainer-Script 分支 function Switch-SD-Trainer-Script-Branch (`$remote, `$branch, `$use_submod) { `$sd_trainer_script_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$preview_url = `$(git -C `"`$sd_trainer_script_path`" remote get-url origin) Set-Github-Mirror # 设置 Github 镜像源 Print-Msg `"SD-Trainer-Script 远程源替换: `$preview_url -> `$remote`" git -C `"`$sd_trainer_script_path`" remote set-url origin `"`$remote`" # 替换远程源 # 处理 Git 子模块 if (`$use_submod) { Print-Msg `"更新 SD-Trainer-Script 的 Git 子模块信息`" git -C `"`$sd_trainer_script_path`" submodule update --init --recursive } else { Print-Msg `"禁用 SD-Trainer-Script 的 Git 子模块`" git -C `"`$sd_trainer_script_path`" submodule deinit --all -f } Print-Msg `"拉取 SD-Trainer-Script 远程源更新`" git -C `"`$sd_trainer_script_path`" fetch # 拉取远程源内容 if (`$?) { if (`$use_submod) { Print-Msg `"清理原有的 Git 子模块`" git -C `"`$sd_trainer_script_path`" submodule deinit --all -f } Print-Msg `"切换 SD-Trainer-Script 分支至 `$branch`" # 本地分支不存在时创建一个分支 git -C `"`$sd_trainer_script_path`" show-ref --verify --quiet `"refs/heads/`${branch}`" if (!(`$?)) { git -C `"`$sd_trainer_script_path`" branch `"`${branch}`" } git -C `"`$sd_trainer_script_path`" checkout `"`${branch}`" --force # 切换分支 Print-Msg `"应用 SD-Trainer-Script 远程源的更新`" if (`$use_submod) { Print-Msg `"更新 SD-Trainer-Script 的 Git 子模块信息`" git -C `"`$sd_trainer_script_path`" reset --hard `"origin/`$branch`" git -C `"`$sd_trainer_script_path`" submodule deinit --all -f git -C `"`$sd_trainer_script_path`" submodule update --init --recursive } if (`$use_submod) { git -C `"`$sd_trainer_script_path`" reset --recurse-submodules --hard `"origin/`$branch`" # 切换到最新的提交内容上 } else { git -C `"`$sd_trainer_script_path`" reset --hard `"origin/`$branch`" # 切换到最新的提交内容上 } Print-Msg `"切换 SD-Trainer-Script 分支成功`" } else { Print-Msg `"拉取 SD-Trainer-Script 远程源更新失败, 取消分支切换`" Print-Msg `"尝试回退 SD-Trainer-Script 的更改`" git -C `"`$sd_trainer_script_path`" remote set-url origin `"`$preview_url`" if (`$use_submod) { git -C `"`$sd_trainer_script_path`" submodule deinit --all -f } else { git -C `"`$sd_trainer_script_path`" submodule update --init --recursive } Print-Msg `"回退 SD-Trainer-Script 分支更改完成`" Print-Msg `"切换 SD-Trainer-Script 分支更改失败, 可尝试重新运行 SD-Trainer-Script 分支切换脚本`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建模式已启用, 跳过 SD-Trainer-Script Installer 更新检查`" } else { Check-SD-Trainer-Script-Installer-Update } if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 SD-Trainer-Script 是否已正确安装, 或者尝试运行 SD-Trainer-Script Installer 进行修复`" Read-Host | Out-Null return } `$content = `" ----------------------------------------------------- - 1、kohya-ss - sd-scripts 主分支 - 2、kohya-ss - sd-scripts 测试分支 - 3、bghira - SimpleTuner 分支 - 4、ostris - ai-toolkit 分支 - 5、a-r-r-o-w - finetrainers 分支 - 6、tdrussell - diffusion-pipe 分支 - 7、kohya-ss - musubi-tuner 分支 ----------------------------------------------------- `".Trim() `$to_exit = 0 while (`$True) { Print-Msg `"SD-Trainer-Script 分支列表`" `$go_to = 0 Write-Host `$content Print-Msg `"当前 SD-Trainer-Script 分支: `$(Get-SD-Trainer-Script-Branch)`" Print-Msg `"请选择 SD-Trainer-Script 分支`" Print-Msg `"提示: 输入数字后回车, 或者输入 exit 退出 SD-Trainer-Script 分支切换脚本`" if (`$BuildMode) { `$arg = `$BuildWitchBranch `$go_to = 1 } else { `$arg = (Read-Host `"==================================================>`").Trim() } switch (`$arg) { 1 { `$remote = `"https://github.com/kohya-ss/sd-scripts`" `$branch = `"main`" `$branch_name = `"kohya-ss - sd-scripts 主分支`" `$use_submod = `$false `$go_to = 1 } 2 { `$remote = `"https://github.com/kohya-ss/sd-scripts`" `$branch = `"dev`" `$branch_name = `"kohya-ss - sd-scripts 测试分支`" `$use_submod = `$false `$go_to = 1 } 3 { `$remote = `"https://github.com/bghira/SimpleTuner`" `$branch = `"main`" `$branch_name = `"bghira - SimpleTuner 分支`" `$use_submod = `$false `$go_to = 1 } 4 { `$remote = `"https://github.com/ostris/ai-toolkit`" `$branch = `"main`" `$branch_name = `"ostris - ai-toolkit 分支`" `$use_submod = `$true `$go_to = 1 } 5 { `$remote = `"https://github.com/a-r-r-o-w/finetrainers`" `$branch = `"main`" `$branch_name = `"a-r-r-o-w - finetrainers 分支`" `$use_submod = `$false `$go_to = 1 } 6 { `$remote = `"https://github.com/tdrussell/diffusion-pipe`" `$branch = `"main`" `$branch_name = `"tdrussell - diffusion-pipe 分支`" `$use_submod = `$true `$go_to = 1 } 7 { `$remote = `"https://github.com/kohya-ss/musubi-tuner`" `$branch = `"main`" `$branch_name = `"kohya-ss - musubi-tuner 分支`" `$use_submod = `$false `$go_to = 1 } exit { Print-Msg `"退出 SD-Trainer-Script 分支切换脚本`" `$to_exit = 1 `$go_to = 1 } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否切换 SD-Trainer-Script 分支到 `$branch_name ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$operate = `"yes`" } else { `$operate = (Read-Host `"==================================================>`").Trim() } if (`$operate -eq `"yes`" -or `$operate -eq `"y`" -or `$operate -eq `"YES`" -or `$operate -eq `"Y`") { Print-Msg `"开始切换 SD-Trainer-Script 分支`" Switch-SD-Trainer-Script-Branch `$remote `$branch `$use_submod } else { Print-Msg `"取消切换 SD-Trainer-Script 分支`" } Print-Msg `"退出 SD-Trainer-Script 分支切换脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/switch_branch.ps1") { Print-Msg "更新 switch_branch.ps1 中" } else { Print-Msg "生成 switch_branch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/switch_branch.ps1" -Value $content } # 获取安装脚本 function Write-Launch-SD-Trainer-Script-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [string]`$InstallBranch, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 SD-Trainer-Script Installer function Download-SD-Trainer-Script-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 SD-Trainer-Script Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/sd_trainer_script_installer.ps1`" if (`$?) { Print-Msg `"下载 SD-Trainer-Script Installer 脚本成功`" break } else { Print-Msg `"下载 SD-Trainer-Script Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 SD-Trainer-Script Installer 脚本`" } else { Print-Msg `"下载 SD-Trainer-Script Installer 脚本失败, 可尝试重新运行 SD-Trainer-Script Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { `$arg.Add(`"-DisableGithubMirror`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } `$arg.Add(`"-UseCustomGithubMirror`", `$github_mirror) } } if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"kohya-ss/sd-scripts`") -or (`$branch -eq `"kohya-ss/sd-scripts.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_scripts`") } elseif ((`$branch -eq `"bghira/SimpleTuner`") -or (`$branch -eq `"bghira/SimpleTuner.git`")) { `$arg.Add(`"-InstallBranch`", `"simple_tuner`") } elseif ((`$branch -eq `"ostris/ai-toolkit`") -or (`$branch -eq `"ostris/ai-toolkit.git`")) { `$arg.Add(`"-InstallBranch`", `"ai_toolkit`") } elseif ((`$branch -eq `"a-r-r-o-w/finetrainers`") -or (`$branch -eq `"a-r-r-o-w/finetrainers.git`")) { `$arg.Add(`"-InstallBranch`", `"finetrainers`") } elseif ((`$branch -eq `"tdrussell/diffusion-pipe`") -or (`$branch -eq `"tdrussell/diffusion-pipe.git`")) { `$arg.Add(`"-InstallBranch`", `"diffusion_pipe`") } elseif ((`$branch -eq `"kohya-ss/musubi-tuner`") -or (`$branch -eq `"kohya-ss/musubi-tuner.git`")) { `$arg.Add(`"-InstallBranch`", `"musubi_tuner`") } } elseif ((Test-Path `"`$PSScriptRoot/install_sd_scripts.txt`") -or (`$InstallBranch -eq `"sd_scripts`")) { `$arg.Add(`"-InstallBranch`", `"sd_scripts`") } elseif ((Test-Path `"`$PSScriptRoot/install_simple_tuner.txt`") -or (`$InstallBranch -eq `"simple_tuner`")) { `$arg.Add(`"-InstallBranch`", `"simple_tuner`") } elseif ((Test-Path `"`$PSScriptRoot/install_ai_toolkit.txt`") -or (`$InstallBranch -eq `"ai_toolkit`")) { `$arg.Add(`"-InstallBranch`", `"ai_toolkit`") } elseif ((Test-Path `"`$PSScriptRoot/install_finetrainers.txt`") -or (`$InstallBranch -eq `"finetrainers`")) { `$arg.Add(`"-InstallBranch`", `"finetrainers`") } elseif ((Test-Path `"`$PSScriptRoot/install_diffusion_pipe.txt`") -or (`$InstallBranch -eq `"diffusion_pipe`")) { `$arg.Add(`"-InstallBranch`", `"diffusion_pipe`") } elseif ((Test-Path `"`$PSScriptRoot/install_musubi_tuner.txt`") -or (`$InstallBranch -eq `"musubi_tuner`")) { `$arg.Add(`"-InstallBranch`", `"musubi_tuner`") } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Set-Proxy `$status = Download-SD-Trainer-Script-Installer if (`$status) { Print-Msg `"运行 SD-Trainer-Script Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/sd_trainer_script_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 SD-Trainer-Script Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_sd_trainer_script_installer.ps1") { Print-Msg "更新 launch_sd_trainer_script_installer.ps1 中" } else { Print-Msg "生成 launch_sd_trainer_script_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_sd_trainer_script_installer.ps1" -Value $content } # 重装 PyTorch 脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWithTorch, [switch]`$BuildWithTorchReinstall, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableUV, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-DisablePyPIMirror] [-DisableUpdate] [-DisableUV] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer-Script Installer 构建模式 -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD-Trainer-Script Installer构建模式, 并且添加 -BuildWithTorch) 在 SD-Trainer-Script Installer构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD-Trainer-Script Installer 更新检查 -DisableUV 禁用 SD-Trainer-Script Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableAutoApplyUpdate 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # SD-Trainer-Script Installer 更新检测 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer-Script Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer-Script Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 xFormers 版本 function Get-xFormers-Version { `$content = `" from importlib.metadata import version try: ver = version('xformers') except: ver = None print(ver) `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 获取驱动支持的最高 CUDA 版本 function Get-Drive-Support-CUDA-Version { Print-Msg `"获取显卡驱动支持的最高 CUDA 版本`" if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) { `$cuda_ver = `$(nvidia-smi -q | Select-String -Pattern 'CUDA Version\s*:\s*([\d.]+)').Matches.Groups[1].Value } else { `$cuda_ver = `"未知`" } return `$cuda_ver } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } return `$torch_ver, `$xformers_ver } # 获取 HashTable 的值 function Get-HashValue { param( [hashtable]`$Hashtable, [string]`$Key, [object]`$Default = `$null ) if (`$Hashtable.ContainsKey(`$Key)) { return `$Hashtable[`$Key] } else { return `$Default } } # 获取可用的 PyTorch 类型 function Get-Avaliable-PyTorch-Type { `$content = `" import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 CUDA_TYPE = [ 'cu113', 'cu117', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu129', 'cu130', ] def get_avaliable_device() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() device_list = ['cpu'] if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): device_list.append('xpu') if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): device_list.append('directml') if compare_versions(cuda_comp_cap, '10.0') > 0: for ver in CUDA_TYPE: if compare_versions(ver, str(int(12.8 * 10))) >= 0: device_list.append(ver) else: for ver in CUDA_TYPE: if compare_versions(ver, str(int(cuda_support_ver * 10))) <= 0: device_list.append(ver) return ','.join(list(set(device_list))) if __name__ == '__main__': print(get_avaliable_device()) `".Trim() Print-Msg `"获取可用的 PyTorch 类型`" `$res = `$(python -c `"`$content`") return `$res -split ',' | ForEach-Object { `$_.Trim() } } # 获取 PyTorch 列表 function Get-PyTorch-List { `$pytorch_list = New-Object System.Collections.ArrayList `$supported_type = Get-Avaliable-PyTorch-Type # >>>>>>>>>> Start `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==1.12.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CUDA 11.3) + xFormers 0.0.14`" `"type`" = `"cu113`" `"supported`" = `"cu113`" -in `$supported_type `"torch`" = `"torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==1.12.1+cu113`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.13.1+cpu torchvision==0.14.1+cpu torchaudio==0.13.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 torch-directml==0.1.13.1.dev230413`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CUDA 11.7) + xFormers 0.0.16`" `"type`" = `"cu117`" `"supported`" = `"cu117`" -in `$supported_type `"torch`" = `"torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==1.13.1+cu117`" `"xformers`" = `"xformers==0.0.18`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.0 torch-directml==0.2.0.dev230426`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.0.0a0+gite9ebda2 torchvision==0.15.2a0+fa99a53 intel_extension_for_pytorch==2.0.110+gitc6ea20b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CUDA 11.8) + xFormers 0.0.18`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.0+cu118`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.1+cpu torchvision==0.15.2+cpu torchaudio==2.0.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CUDA 11.8) + xFormers 0.0.22`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.1+cu118`" `"xformers`" = `"xformers==0.0.22`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.0+cpu torchvision==0.16.0+cpu torchaudio==2.1.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi torchaudio==2.1.0a0+cxx11.abi intel_extension_for_pytorch==2.1.10+xpu`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Core Ultra)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+git7bcf7da torchvision==0.16.0+fbb4cc5 torchaudio==2.1.0+6ea1133 intel_extension_for_pytorch==2.1.20+git4849f3b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.1+cpu torchvision==0.16.1+cpu torchaudio==2.1.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 11.8) + xFormers 0.0.23`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu118 torchvision==0.16.1+cu118 torchaudio==2.1.1+cu118`" `"xformers`" = `"xformers==0.0.23+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 12.1) + xFormers 0.0.23`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu121 torchvision==0.16.1+cu121 torchaudio==2.1.1+cu121`" `"xformers`" = `"xformers===0.0.23`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.2+cpu torchvision==0.16.2+cpu torchaudio==2.1.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 11.8) + xFormers 0.0.23.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118`" `"xformers`" = `"xformers==0.0.23.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 12.1) + xFormers 0.0.23.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu121 torchvision==0.16.2+cu121 torchaudio==2.1.2+cu121`" `"xformers`" = `"xformers===0.0.23.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 11.8) + xFormers 0.0.24`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu118 torchvision==0.17.0+cu118 torchaudio==2.2.0+cu118`" `"xformers`" = `"xformers==0.0.24+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 12.1) + xFormers 0.0.24`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu121 torchvision==0.17.0+cu121 torchaudio==2.2.0+cu121`" `"xformers`" = `"xformers===0.0.24`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.1+cpu torchvision==0.17.1+cpu torchaudio==2.2.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 11.8) + xFormers 0.0.25`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu118 torchvision==0.17.1+cu118 torchaudio==2.2.1+cu118`" `"xformers`" = `"xformers==0.0.25+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 torch-directml==0.2.1.dev240521`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 12.1) + xFormers 0.0.25`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121`" `"xformers`" = `"xformers===0.0.25`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.2+cpu torchvision==0.17.2+cpu torchaudio==2.2.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 11.8) + xFormers 0.0.25.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu118 torchvision==0.17.2+cu118 torchaudio==2.2.2+cu118`" `"xformers`" = `"xformers==0.0.25.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 12.1) + xFormers 0.0.25.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu121 torchvision==0.17.2+cu121 torchaudio==2.2.2+cu121`" `"xformers`" = `"xformers===0.0.25.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.0+cpu torchvision==0.18.0+cpu torchaudio==2.3.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 11.8) + xFormers 0.0.26.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" `"xformers`" = `"xformers==0.0.26.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 12.1) + xFormers 0.0.26.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121`" `"xformers`" = `"xformers===0.0.26.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.1+cpu torchvision==0.18.1+cpu torchaudio==2.3.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 torch-directml==0.2.3.dev240715`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 11.8) + xFormers 0.0.27`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118`" `"xformers`" = `"xformers==0.0.27+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 12.1) + xFormers 0.0.27`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121`" `"xformers`" = `"xformers===0.0.27`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.0+cpu torchvision==0.19.0+cpu torchaudio==2.4.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 11.8) + xFormers 0.0.27.post2`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu118 torchvision==0.19.0+cu118 torchaudio==2.4.0+cu118`" `"xformers`" = `"xformers==0.0.27.post2+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 12.1) + xFormers 0.0.27.post2`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu121 torchvision==0.19.0+cu121 torchaudio==2.4.0+cu121`" `"xformers`" = `"xformers==0.0.27.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.1+cpu torchvision==0.19.1+cpu torchaudio==2.4.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CUDA 12.4) + xFormers 0.0.28.post1`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.4.1+cu124 torchvision==0.19.1+cu124 torchaudio==2.4.1+cu124`" `"xformers`" = `"xformers==0.0.28.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.0+cpu torchvision==0.20.0+cpu torchaudio==2.5.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CUDA 12.4) + xFormers 0.0.28.post2`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.0+cu124 torchvision==0.20.0+cu124 torchaudio==2.5.0+cu124`" `"xformers`" = `"xformers==0.0.28.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.1+cpu torchvision==0.20.1+cpu torchaudio==2.5.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CUDA 12.4) + xFormers 0.0.28.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124`" `"xformers`" = `"xformers==0.0.28.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+cpu torchvision==0.21.0+cpu torchaudio==2.6.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+xpu torchvision==0.21.0+xpu torchaudio==2.6.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.4) + xFormers 0.0.29.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.6) + xFormers 0.0.29.post3`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu126 torchvision==0.21.0+cu126 torchaudio==2.6.0+cu126`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+cpu torchvision==0.22.0+cpu torchaudio==2.7.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+xpu torchvision==0.22.0+xpu torchaudio==2.7.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu118 torchvision==0.22.0+cu118 torchaudio==2.7.0+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.6) + xFormers 0.0.30`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu126 torchvision==0.22.0+cu126 torchaudio==2.7.0+cu126`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.8) + xFormers 0.0.30`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu128 torchvision==0.22.0+cu128 torchaudio==2.7.0+cu128`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+cpu torchvision==0.22.1+cpu torchaudio==2.7.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+xpu torchvision==0.22.1+xpu torchaudio==2.7.1+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu118 torchvision==0.22.1+cu118 torchaudio==2.7.1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.6) + xFormers 0.0.31.post1`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu126 torchvision==0.22.1+cu126 torchaudio==2.7.1+cu126`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.8) + xFormers 0.0.31.post1`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu128 torchvision==0.22.1+cu128 torchaudio==2.7.1+cu128`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+cpu torchvision==0.23.0+cpu torchaudio==2.8.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+xpu torchvision==0.23.0+xpu torchaudio==2.8.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu128 torchvision==0.23.0+cu128 torchaudio==2.8.0+cu128`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.9)`" `"type`" = `"cu129`" `"supported`" = `"cu129`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129`" # `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 13.0)`" `"type`" = `"cu130`" `"supported`" = `"cu130`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU130 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null # <<<<<<<<<< End return `$pytorch_list } # 列出 PyTorch 列表 function List-PyTorch (`$pytorch_list) { Print-Msg `"PyTorch 版本列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"版本序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"PyTorch 版本`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"支持当前设备情况`" -ForegroundColor Blue for (`$i = 0; `$i -lt `$pytorch_list.Count; `$i++) { `$pytorch_hashtables = `$pytorch_list[`$i] `$count += 1 `$name = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"name`" `$supported = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"supported`" Write-Host `"- `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline if (`$supported) { Write-Host `"(支持✓)`" -ForegroundColor Green } else { Write-Host `"(不支持×)`" -ForegroundColor Red } } Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建模式已启用, 跳过 SD-Trainer-Script Installer 更新检查`" } else { Check-SD-Trainer-Script-Installer-Update } Set-uv PyPI-Mirror-Status `$pytorch_list = Get-PyTorch-List `$go_to = 0 `$to_exit = 0 `$torch_ver = `"`" `$xformers_ver = `"`" `$cuda_support_ver = Get-Drive-Support-CUDA-Version `$current_torch_ver, `$current_xformers_ver = Get-PyTorch-And-xFormers-Version `$after_list_model_option = `"`" while (`$True) { switch (`$after_list_model_option) { display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" List-PyTorch `$pytorch_list Print-Msg `"当前 PyTorch 版本: `$current_torch_ver`" Print-Msg `"当前 xFormers 版本: `$current_xformers_ver`" Print-Msg `"当前显卡驱动支持的最高 CUDA 版本: `$cuda_support_ver`" Print-Msg `"请选择 PyTorch 版本`" Print-Msg `"提示:`" Print-Msg `"1. PyTorch 版本通常来说选择最新版的即可`" Print-Msg `"2. 驱动支持的最高 CUDA 版本需要大于或等于要安装的 PyTorch 中所带的 CUDA 版本, 若驱动支持的最高 CUDA 版本低于要安装的 PyTorch 中所带的 CUDA 版本, 可尝试更新显卡驱动, 或者选择 CUDA 版本更低的 PyTorch`" Print-Msg `"3. 输入数字后回车, 或者输入 exit 退出 PyTorch 重装脚本`" if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建已启用, 指定安装的 PyTorch 序号: `$BuildWithTorch`" `$arg = `$BuildWithTorch `$go_to = 1 } else { `$arg = (Read-Host `"==================================================>`").Trim() } switch (`$arg) { exit { Print-Msg `"退出 PyTorch 重装脚本`" `$to_exit = 1 `$go_to = 1 } Default { try { # 检测输入是否符合列表 `$i = [int]`$arg if (!((`$i -ge 1) -and (`$i -le `$pytorch_list.Count))) { `$after_list_model_option = `"display_input_error`" break } `$pytorch_info = `$pytorch_list[(`$i - 1)] `$combination_name = Get-HashValue -Hashtable `$pytorch_info -Key `"name`" `$torch_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"torch`" `$xformers_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"xformers`" `$index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"index_mirror`" `$extra_index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"extra_index_mirror`" `$find_links = Get-HashValue -Hashtable `$pytorch_info -Key `"find_links`" if (`$null -ne `$index_mirror) { `$Env:PIP_INDEX_URL = `$index_mirror `$Env:UV_DEFAULT_INDEX = `$index_mirror } if (`$null -ne `$extra_index_mirror) { `$Env:PIP_EXTRA_INDEX_URL = `$extra_index_mirror `$Env:UV_INDEX = `$extra_index_mirror } if (`$null -ne `$find_links) { `$Env:PIP_FIND_LINKS = `$find_links `$Env:UV_FIND_LINKS = `$find_links } } catch { `$after_list_model_option = `"display_input_error`" break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否选择仅强制重装 ? (通常情况下不需要)`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { if (`$BuildWithTorchReinstall) { `$use_force_reinstall = `"yes`" } else { `$use_force_reinstall = `"no`" } } else { `$use_force_reinstall = (Read-Host `"==================================================>`").Trim() } if (`$use_force_reinstall -eq `"yes`" -or `$use_force_reinstall -eq `"y`" -or `$use_force_reinstall -eq `"YES`" -or `$use_force_reinstall -eq `"Y`") { `$force_reinstall_arg = `"--force-reinstall`" `$force_reinstall_status = `"启用`" } else { `$force_reinstall_arg = New-Object System.Collections.ArrayList `$force_reinstall_status = `"禁用`" } Print-Msg `"当前的选择: `$combination_name`" Print-Msg `"PyTorch: `$torch_ver`" Print-Msg `"xFormers: `$xformers_ver`" Print-Msg `"仅强制重装: `$force_reinstall_status`" Print-Msg `"是否确认安装?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$install_torch = `"yes`" } else { `$install_torch = (Read-Host `"==================================================>`").Trim() } if (`$install_torch -eq `"yes`" -or `$install_torch -eq `"y`" -or `$install_torch -eq `"YES`" -or `$install_torch -eq `"Y`") { Print-Msg `"重装 PyTorch 中`" if (`$USE_UV) { uv pip install `$torch_ver.ToString().Split() `$force_reinstall_arg if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } } else { python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } if (`$?) { Print-Msg `"安装 PyTorch 成功`" } else { Print-Msg `"安装 PyTorch 失败, 终止 PyTorch 重装进程`" Read-Host | Out-Null exit 1 } if (`$null -ne `$xformers_ver) { Print-Msg `"重装 xFormers 中`" if (`$USE_UV) { `$current_xf_ver = Get-xFormers-Version if (`$xformers_ver.Split(`"=`")[-1] -ne `$current_xf_ver) { Print-Msg `"卸载原有 xFormers 中`" python -m pip uninstall xformers -y } uv pip install `$xformers_ver `$force_reinstall_arg --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } } else { python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } if (`$?) { Print-Msg `"安装 xFormers 成功`" } else { Print-Msg `"安装 xFormers 失败, 终止 PyTorch 重装进程`" Read-Host | Out-Null exit 1 } } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD-Trainer-Script Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 SD-Trainer-Script Installer 更新检查 -DisableAutoApplyUpdate 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # SD-Trainer-Script Installer 更新检测 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD-Trainer-Script Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -le `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD-Trainer-Script Installer 更新`" return } } else { Print-Msg `"检测到 SD-Trainer-Script Installer 有新版本可用`" } Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"checkpoints`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"checkpoints`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"checkpoints`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"unet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"unet`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"vae`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"vae`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"vae`")) | Out-Null # FLUX CLIP `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"clip`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"==================================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD-Trainer-Script Installer 构建模式已启用, 跳过 SD-Trainer-Script Installer 更新检查`" } else { Check-SD-Trainer-Script-Installer-Update } Check-Aria2-Version `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/models`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list } Print-Msg `"退出模型下载脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # SD-Trainer-Script Installer 设置脚本 function Write-SD-Trainer-Script-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # 获取 SD-Trainer-Script Installer 自动检测更新设置 function Get-SD-Trainer-Script-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 SD-Trainer-Script Installer 自动应用更新设置 function Get-SD-Trainer-Script-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 SD-Trainer-Script 运行环境检测配置 function Get-SD-Trainer-Script-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"==================================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 SD-Trainer-Script 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://ghproxy.1888866.xyz/github.com`" Print-Msg `" https://slink.ltd/https://github.com`" Print-Msg `" https://github.boki.moe/github.com`" Print-Msg `" https://github.moeyy.xyz/https://github.com`" Print-Msg `" https://gh-proxy.net/https://github.com`" Print-Msg `" https://gh-proxy.ygxz.in/https://github.com`" Print-Msg `" https://wget.la/https://github.com`" Print-Msg `" https://kkgithub.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD-Trainer-Script Installer 自动检查更新设置 function Update-SD-Trainer-Script-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer-Script Installer 自动检测更新设置: `$(Get-SD-Trainer-Script-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer-Script Installer 自动更新检查`" Print-Msg `"2. 禁用 SD-Trainer-Script Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 SD-Trainer-Script Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer-Script Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer-Script Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD-Trainer-Script Installer 自动应用更新设置 function Update-SD-Trainer-Script-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer-Script Installer 自动应用更新设置: `$(Get-SD-Trainer-Script-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer-Script Installer 自动应用更新`" Print-Msg `"2. 禁用 SD-Trainer-Script Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer-Script Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer-Script Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 SD-Trainer-Script Installer 更新 function Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -gt `$SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 有新版本可用`" Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD-Trainer-Script Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" } } # SD-Trainer-Script 运行环境检测设置 function SD-Trainer-Script-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD-Trainer-Script 运行环境检测设置: `$(Get-SD-Trainer-Script-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD-Trainer-Script 运行环境检测`" Print-Msg `"2. 禁用 SD-Trainer-Script 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD-Trainer-Script 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 SD-Trainer-Script 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if ((Test-Path `"`$PSScriptRoot/python/python.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`")) { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/git.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`")) { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 SD-Trainer-Script Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 SD-Trainer-Script Installer 文档 function Get-SD-Trainer-Script-Installer-Help-Docs { Print-Msg `"调用浏览器打开 SD-Trainer-Script Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md`" } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"SD-Trainer-Script Installer 自动检查更新: `$(Get-SD-Trainer-Script-Installer-Auto-Check-Update-Setting)`" Print-Msg `"SD-Trainer-Script Installer 自动应用更新: `$(Get-SD-Trainer-Script-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"SD-Trainer-Script 运行环境检测设置: `$(Get-SD-Trainer-Script-Env-Check-Setting)`" Print-Msg `"SD-Trainer-Script 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 Github 镜像源设置`" Print-Msg `"5. 进入 SD-Trainer-Script Installer 自动检查更新设置`" Print-Msg `"6. 进入 SD-Trainer-Script Installer 自动应用更新设置`" Print-Msg `"7. 进入 PyPI 镜像源设置`" Print-Msg `"8. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"9. 进入 SD-Trainer-Scripts 运行环境检测设置`" Print-Msg `"10. 进入 SD-Trainer-Script 内核路径前缀设置`" Print-Msg `"11. 更新 SD-Trainer-Script Installer 管理脚本`" Print-Msg `"12. 检查环境完整性`" Print-Msg `"13. 查看 SD-Trainer-Script Installer 文档`" Print-Msg `"14. 退出 SD-Trainer-Script Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-Github-Mirror-Setting break } 5 { Update-SD-Trainer-Script-Installer-Auto-Check-Update-Setting break } 6 { Update-SD-Trainer-Script-Installer-Auto-Apply-Update-Setting break } 7 { PyPI-Mirror-Setting break } 8 { PyTorch-CUDA-Memory-Alloc-Setting break } 9 { SD-Trainer-Script-Env-Check-Setting break } 10 { Update-Core-Prefix-Setting break } 11 { Check-SD-Trainer-Script-Installer-Update break } 12 { Check-Env break } 13 { Get-SD-Trainer-Script-Installer-Help-Docs break } 14 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 SD-Trainer-Script Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror ) & { `$prefix_list = @(`"core`", `"sd-scripts`", `"SimpleTuner`", `"ai-toolkit`", `"finetrainers`", `"diffusion-pipe`", `"musubi-tuner`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD-Trainer-Script Installer 版本和检查更新间隔 `$Env:SD_TRAINER_SCRIPT_INSTALLER_VERSION = $SD_TRAINER_SCRIPT_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:SD_TRAINER_SCRIPT_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableGithubMirror 禁用 SD-Trainer-Script Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示符信息 function global:prompt { `"`$(Write-Host `"[SD-Trainer-Script Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:SD_TRAINER_SCRIPT_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # SD-Trainer-Script Installer 更新检测 function global:Check-SD-Trainer-Script-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/sd_trainer_script_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/sd_trainer_script_installer/sd_trainer_script_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/sd_trainer_script_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:SD_TRAINER_SCRIPT_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD-Trainer-Script Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" | Select-String -Pattern `"SD_TRAINER_SCRIPT_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD-Trainer-Script Installer 更新中`" } else { Print-Msg `"检查 SD-Trainer-Script Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:SD_TRAINER_SCRIPT_INSTALLER_VERSION) { Print-Msg `"SD-Trainer-Script Installer 有新版本可用`" Print-Msg `"调用 SD-Trainer-Script Installer 进行更新中`" . `"`$Env:CACHE_HOME/sd_trainer_script_installer.ps1`" -InstallPath `"`$Env:SD_TRAINER_SCRIPT_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 SD-Trainer-Script Installer 管理脚本以应用更新, 回车退出 SD-Trainer-Script Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"SD-Trainer-Script Installer 已是最新版本`" } } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:SD_TRAINER_SCRIPT_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 SD-Trainer-Script Installer 内置命令 function global:List-CMD { Write-Host `" ================================== SD-Trainer-Script Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 SD-Trainer-Script Installer 内置命令: Update-uv Update-Aria2 Check-SD-Trainer-Script-Installer-Update Get-Core-Prefix List-CMD 更多帮助信息可在 SD-Trainer-Script Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md `" } # 显示 SD-Trainer-Script Installer 版本 function Get-SD-Trainer-Script-Installer-Version { `$ver = `$([string]`$Env:SD_TRAINER_SCRIPT_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD-Trainer-Script Installer 版本: v`${major}.`${minor}.`${micro}`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror Set-Github-Mirror PyPI-Mirror-Status Print-Msg `"激活 SD-Trainer-Script Env`" Print-Msg `"更多帮助信息可在 SD-Trainer-Script Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activate.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD-Trainer-Script Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 SD-Trainer-Script Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== SD-Trainer-Script Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 SD-Trainer-Script 的简单使用文档。 使用 SD-Trainer-Script Installer 进行安装并安装成功后,将在当前目录生成 SD-Trainer-Script 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - init.ps1:初始化 SD-Trainer-Script 运行环境。 - train.ps1:初始训练脚本,用于编写训练命令,训练命令编写方法可查看:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md#%E7%BC%96%E5%86%99%E8%AE%AD%E7%BB%83%E8%84%9A%E6%9C%AC - update.ps1:更新 SD-Trainer-Script。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 models 文件夹中。关于模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md。 - reinstall_pytorch.ps1:重新安装 PyTorch 的脚本,在 PyTorch 出问题或者需要切换 PyTorch 版本时可使用。 - switch_branch.ps1:切换 SD-Trainer-Script 分支。 - settings.ps1:管理 SD-Trainer-Script Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - launch_sd_trainer_script_installer.ps1:获取最新的 SD-Trainer-Script Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - sd-scripts / core:SD-Trainer-Script 内核。 - models:使用模型下载脚本下载模型时模型的存放位置。 详细的 SD-Trainer-Script Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md 其他的一些训练模型的教程: https://sd-moadel-doc.maozi.io https://rentry.org/59xed3 https://civitai.com/articles/2056 https://civitai.com/articles/124/lora-analogy-about-lora-trainning-and-using https://civitai.com/articles/143/some-shallow-understanding-of-lora-training-lora https://civitai.com/articles/632/why-this-lora-can-not-bring-good-result-lora https://civitai.com/articles/726/an-easy-way-to-make-a-cosplay-lora-cosplay-lora https://civitai.com/articles/2135/lora-quality-improvement-some-experiences-about-datasets-and-captions-lora https://civitai.com/articles/2297/ways-to-make-a-character-lora-that-is-easier-to-change-clothes-lora 推荐的哔哩哔哩 UP 主: 青龙圣者:https://space.bilibili.com/219296 秋葉aaaki:https://space.bilibili.com/12566101 琥珀青葉:https://space.bilibili.com/507303431 观看这些 UP 主的视频可获得一些训练模型的教程。 ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one sd-scripts 项目地址:https://github.com/kohya-ss/sd-scripts SimpleTuner 项目地址:https://github.com/bghira/SimpleTuner ai-toolkit 项目地址:https://github.com/ostris/ai-toolkit finetrainers 项目地址:https://github.com/a-r-r-o-w/finetrainers diffusion-pipe 项目地址:https://github.com/tdrussell/diffusion-pipe musubi-tuner 项目地址:https://github.com/kohya-ss/musubi-tuner ==================================================================== ########## 用户协议 ########## 使用该整合包代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Train-Script Write-Library-Script Write-Update-Script Write-Switch-Branch-Script Write-Launch-SD-Trainer-Script-Install-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-SD-Trainer-Script-Installer-Settings-Script Write-Env-Activate-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-SD-Trainer-Script-Installer-Config { Print-Msg "为 SD-Trainer-Script Installer 管理脚本复制 SD-Trainer-Script Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($DisableGithubMirror)) -and (Test-Path "$PSScriptRoot/disable_gh_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_gh_mirror.txt -> $InstallPath/disable_gh_mirror.txt" } elseif ((!($DisableGithubMirror)) -and (!($UseCustomGithubMirror)) -and (Test-Path "$PSScriptRoot/gh_mirror.txt") -and (!(Test-Path "$PSScriptRoot/disable_gh_mirror.txt"))) { Copy-Item -Path "$PSScriptRoot/gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/gh_mirror.txt -> $InstallPath/gh_mirror.txt" } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 SD-Trainer-Script 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 SD-Trainer-Script Installer, 更多的说明请阅读 SD-Trainer-Script Installer 使用文档" Print-Msg "SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" if ((Test-Path "$PSScriptRoot/install_sd_scripts.txt") -or ($InstallBranch -eq "sd_scripts")) { Print-Msg "检测到 install_sd_scripts.txt 配置文件 / 命令行参数 -InstallBranch sd_scripts, 选择安装 kohya-ss/sd-scripts" } elseif ((Test-Path "$PSScriptRoot/install_simple_tuner.txt") -or ($InstallBranch -eq "simple_tuner")) { Print-Msg "检测到 install_simple_tuner.txt 配置文件 / 命令行参数 -InstallBranch simple_tuner, 选择安装 bghira/SimpleTuner" } elseif ((Test-Path "$PSScriptRoot/install_ai_toolkit.txt") -or ($InstallBranch -eq "ai_toolkit")) { Print-Msg "检测到 install_ai_toolkit.txt 配置文件 / 命令行参数 -InstallBranch ai_toolkit, 选择安装 ostris/ai-toolkit" } elseif ((Test-Path "$PSScriptRoot/install_finetrainers.txt") -or ($InstallBranch -eq "finetrainers")) { Print-Msg "检测到 install_finetrainers.txt 配置文件 / 命令行参数 -InstallBranch finetrainers, 选择安装 a-r-r-o-w/finetrainers" } elseif ((Test-Path "$PSScriptRoot/install_diffusion_pipe.txt") -or ($InstallBranch -eq "diffusion_pipe")) { Print-Msg "检测到 install_diffusion_pipe.txt 配置文件 / 命令行参数 -InstallBranch diffusion_pipe, 选择安装 tdrussell/diffusion-pipe" } elseif ((Test-Path "$PSScriptRoot/install_musubi_tuner.txt") -or ($InstallBranch -eq "musubi_tuner")) { Print-Msg "检测到 install_musubi_tuner.txt 配置文件 / 命令行参数 -InstallBranch musubi_tuner, 选择安装 kohya-ss/musubi-tuner" } else { Print-Msg "未指定安装的训练器, 默认选择安装 kohya-ss/sd-scripts" } Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-SD-Trainer-Script-Installer-Config if ($BuildMode) { Use-Build-Mode Print-Msg "SD-Trainer-Script 环境构建完成, 路径: $InstallPath" } else { Print-Msg "SD-Trainer-Script 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 SD-Trainer-Script 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 SD-Trainer-Script Installer 使用文档" Print-Msg "SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md" Print-Msg "退出 SD-Trainer-Script Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWithTorch", $BuildWithTorch) if ($BuildWithTorchReinstall) { $launch_args.Add("-BuildWithTorchReinstall", $true) } if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWitchBranch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchBranch", $BuildWitchBranch) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer-Script 分支切换脚本中" . "$InstallPath/switch_branch.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer-Script 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 SD-Trainer-Script 启动脚本中" . "$InstallPath/init.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-SD-Trainer-Script-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 SD-Trainer-Script 的绝对路径>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-InstallBranch <安装的 SD-Trainer-Script 分支>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-BuildMode] [-BuildWithUpdate] [-BuildWithLaunch] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-BuildWitchBranch <SD-Trainer-Script 分支编号>] [-PyTorchPackage <PyTorch 软件包>] [-xFormersPackage <xFormers 软件包>] [-NoCleanCache] [-DisableUpdate] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD-Trainer-Script Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -InstallPath <安装 SD-Trainer-Script 的绝对路径> 指定 SD-Trainer-Script Installer 安装 SD-Trainer-Script 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 SD-Trainer-Script Installer 安装 SD-Trainer-Script 到 D:\Donwload 这个路径 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -InstallBranch <安装的 SD-Trainer-Script 分支> 指定 SD-Trainer-Script Installer 安装的 SD-Trainer-Script 分支 (sd_scripts, simple_tuner, ai_toolkit, finetrainers, diffusion_pipe, musubi_tuner) 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallBranch `"simple_tuner`", 这将指定 SD-Trainer-Script Installer 安装 bghira/SimpleTuner 分支 未指定该参数时, 默认安装 kohya-ss/sd-scripts 分支 支持指定安装的分支如下: sd_scripts: kohya-ss/sd-scripts simple_tuner: bghira/SimpleTuner ai_toolkit: ostris/ai-toolkit finetrainers: a-r-r-o-w/finetrainers diffusion_pipe: tdrussell/diffusion-pipe musubi_tuner: kohya-ss/musubi-tuner -UseUpdateMode 指定 SD-Trainer-Script Installer 使用更新模式, 只对 SD-Trainer-Script Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 SD-Trainer-Script Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD-Trainer-Script Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 SD-Trainer-Script Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableGithubMirror 禁用 SD-Trainer-Script Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -BuildMode 启用 SD-Trainer-Script Installer 构建模式, 在基础安装流程结束后将调用 SD-Trainer-Script Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 SD-Trainer-Script Installer 的执行, 而是直接退出 当指定调用多个 SD-Trainer-Script Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorch, -BuildWithTorchReinstall 参数) - switch_branch.ps1 (对应 -BuildWitchBranch 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - init.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 update.ps1 脚本, 更新 SD-Trainer-Script 内核 -BuildWithLaunch (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 init.ps1 脚本, 执行启动 SD-Trainer-Script 前的环境检查流程, 但跳过启动 SD-Trainer-Script -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式, 并且添加 -BuildWithTorch) 在 SD-Trainer-Script Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -BuildWitchBranch <SD-Trainer-Script 分支编号> (需添加 -BuildMode 启用 SD-Trainer-Script Installer 构建模式) SD-Trainer-Script Installer 执行完基础安装流程后调用 SD-Trainer-Script Installer 的 switch_branch.ps1 脚本, 根据 SD-Trainer-Script 分支编号切换到对应的 SD-Trainer-Script 分支 SD-Trainer-Script 分支编号可运行 switch_branch.ps1 脚本进行查看 -PyTorchPackage <PyTorch 软件包> (需要同时搭配 -xFormersPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 PyTorch 版本, 如 -PyTorchPackage `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" -xFormersPackage <xFormers 软件包> (需要同时搭配 -PyTorchPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 xFormers 版本, 如 -xFormersPackage `"xformers===0.0.26.post1+cu118`" -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 禁用 SD-Trainer-Script Installer 更新检查 -DisableHuggingFaceMirror (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -DisableCUDAMalloc (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 禁用 SD-Trainer-Script Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 禁用 SD-Trainer-Script Installer 检查 SD-Trainer-Script 运行环境中存在的问题, 禁用后可能会导致 SD-Trainer-Script 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate (仅在 SD-Trainer-Script Installer 构建模式下生效, 并且只作用于 SD-Trainer-Script Installer 管理脚本) 禁用 SD-Trainer-Script Installer 自动应用新版本更新 更多的帮助信息请阅读 SD-Trainer-Script Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/sd_trainer_script_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-SD-Trainer-Script-Installer-Version Get-SD-Trainer-Script-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "SD-Trainer-Script Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/sd_trainer_script_installer.ps1
PowerShell
agpl-3.0
442,744
param ( [switch]$Help, [string]$CorePrefix, [string]$InstallPath = (Join-Path -Path "$PSScriptRoot" -ChildPath "stable-diffusion-webui"), [string]$PyTorchMirrorType, [string]$InstallBranch, [switch]$UseUpdateMode, [switch]$DisablePyPIMirror, [switch]$DisableProxy, [string]$UseCustomProxy, [switch]$DisableUV, [switch]$DisableGithubMirror, [string]$UseCustomGithubMirror, [switch]$BuildMode, [switch]$BuildWithUpdate, [switch]$BuildWithUpdateExtension, [switch]$BuildWithLaunch, [int]$BuildWithTorch, [switch]$BuildWithTorchReinstall, [string]$BuildWitchModel, [int]$BuildWitchBranch, [switch]$NoPreDownloadExtension, [switch]$NoPreDownloadModel, [string]$PyTorchPackage, [string]$xFormersPackage, [switch]$InstallHanamizuki, [switch]$NoCleanCache, # 仅在管理脚本中生效 [switch]$DisableUpdate, [switch]$DisableHuggingFaceMirror, [string]$UseCustomHuggingFaceMirror, [string]$LaunchArg, [switch]$EnableShortcut, [switch]$DisableCUDAMalloc, [switch]$DisableEnvCheck, [switch]$DisableAutoApplyUpdate ) & { $prefix_list = @("core", "stable-diffusion-webui", "stable-diffusion-webui-forge", "stable-diffusion-webui-reForge", "sd-webui-forge-classic", "stable-diffusion-webui-amdgpu", "automatic", "sd_webui", "sd_webui_forge", "sd-webui-aki-v4.10", "sd-webui-aki-v4.11.1-cu128", "sd-webui-forge-aki-v1.0") if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } $origin_core_prefix = $origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted($origin_core_prefix)) { $to_path = $origin_core_prefix $from_uri = New-Object System.Uri($InstallPath.Replace('\', '/') + '/') $to_uri = New-Object System.Uri($to_path.Replace('\', '/')) $origin_core_prefix = $from_uri.MakeRelativeUri($to_uri).ToString().Trim('/') } $Env:CORE_PREFIX = $origin_core_prefix return } ForEach ($i in $prefix_list) { if (Test-Path "$InstallPath/$i") { $Env:CORE_PREFIX = $i return } } $Env:CORE_PREFIX = "core" } # 有关 PowerShell 脚本保存编码的问题: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.4#the-byte-order-mark # 在 PowerShell 5 中 UTF8 为 UTF8 BOM, 而在 PowerShell 7 中 UTF8 为 UTF8, 并且多出 utf8BOM 这个单独的选项: https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.5#-encoding $PS_SCRIPT_ENCODING = if ($PSVersionTable.PSVersion.Major -le 5) { "UTF8" } else { "utf8BOM" } # SD WebUI Installer 版本和检查更新间隔 $SD_WEBUI_INSTALLER_VERSION = 276 $UPDATE_TIME_SPAN = 3600 # PyPI 镜像源 $PIP_INDEX_ADDR = "https://mirrors.cloud.tencent.com/pypi/simple" $PIP_INDEX_ADDR_ORI = "https://pypi.python.org/simple" $PIP_EXTRA_INDEX_ADDR = "https://mirrors.cernet.edu.cn/pypi/web/simple" # $PIP_EXTRA_INDEX_ADDR_ORI = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_ADDR_ORI = "" # $PIP_FIND_ADDR = "https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR = "https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html" $PIP_FIND_ADDR_ORI = "https://download.pytorch.org/whl/torch_stable.html" $USE_PIP_MIRROR = if ((!(Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) -and (!($DisablePyPIMirror))) { $true } else { $false } $PIP_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_INDEX_ADDR } else { $PIP_INDEX_ADDR_ORI } $PIP_EXTRA_INDEX_MIRROR = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_ADDR } else { $PIP_EXTRA_INDEX_ADDR_ORI } $PIP_FIND_MIRROR = if ($USE_PIP_MIRROR) { $PIP_FIND_ADDR } else { $PIP_FIND_ADDR_ORI } $PIP_FIND_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121/torch_stable.html" $PIP_EXTRA_INDEX_MIRROR_PYTORCH = "https://download.pytorch.org/whl" $PIP_EXTRA_INDEX_MIRROR_CPU = "https://download.pytorch.org/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU = "https://download.pytorch.org/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118 = "https://download.pytorch.org/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121 = "https://download.pytorch.org/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124 = "https://download.pytorch.org/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126 = "https://download.pytorch.org/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128 = "https://download.pytorch.org/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129 = "https://download.pytorch.org/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130 = "https://download.pytorch.org/whl/cu130" $PIP_EXTRA_INDEX_MIRROR_CPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cpu" $PIP_EXTRA_INDEX_MIRROR_XPU_NJU = "https://mirror.nju.edu.cn/pytorch/whl/xpu" $PIP_EXTRA_INDEX_MIRROR_CU118_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu118" $PIP_EXTRA_INDEX_MIRROR_CU121_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu121" $PIP_EXTRA_INDEX_MIRROR_CU124_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu124" $PIP_EXTRA_INDEX_MIRROR_CU126_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu126" $PIP_EXTRA_INDEX_MIRROR_CU128_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu128" $PIP_EXTRA_INDEX_MIRROR_CU129_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu129" $PIP_EXTRA_INDEX_MIRROR_CU130_NJU = "https://mirror.nju.edu.cn/pytorch/whl/cu130" # Github 镜像源列表 $GITHUB_MIRROR_LIST = @( "https://ghfast.top/https://github.com", "https://mirror.ghproxy.com/https://github.com", "https://ghproxy.net/https://github.com", "https://gh.api.99988866.xyz/https://github.com", "https://gh-proxy.com/https://github.com", "https://ghps.cc/https://github.com", "https://gh.idayer.com/https://github.com", "https://ghproxy.1888866.xyz/github.com", "https://slink.ltd/https://github.com", "https://github.boki.moe/github.com", "https://github.moeyy.xyz/https://github.com", "https://gh-proxy.net/https://github.com", "https://gh-proxy.ygxz.in/https://github.com", "https://wget.la/https://github.com", "https://kkgithub.com", "https://gitclone.com/github.com" ) # uv 最低版本 $UV_MINIMUM_VER = "0.9.9" # Aria2 最低版本 $ARIA2_MINIMUM_VER = "1.37.0" # Stable Diffusion WebUI 仓库地址 $SD_WEBUI_REPO = if ((Test-Path "$PSScriptRoot/install_sd_webui.txt") -or ($InstallBranch -eq "sd_webui")) { "https://github.com/AUTOMATIC1111/stable-diffusion-webui" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge.txt") -or ($InstallBranch -eq "sd_webui_forge")) { "https://github.com/lllyasviel/stable-diffusion-webui-forge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_reforge.txt") -or ($InstallBranch -eq "sd_webui_reforge")) { "https://github.com/Panchovix/stable-diffusion-webui-reForge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge_classic.txt") -or ($InstallBranch -eq "sd_webui_forge_classic")) { "https://github.com/Haoming02/sd-webui-forge-classic" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_amdgpu.txt") -or ($InstallBranch -eq "sd_webui_amdgpu")) { "https://github.com/lshqqytiger/stable-diffusion-webui-amdgpu" } elseif ((Test-Path "$PSScriptRoot/install_sd_next.txt") -or ($InstallBranch -eq "sdnext")) { "https://github.com/vladmandic/sdnext" } else { "https://github.com/AUTOMATIC1111/stable-diffusion-webui" } # PATH $PYTHON_PATH = "$InstallPath/python" $PYTHON_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python" $PYTHON_SCRIPTS_PATH = "$InstallPath/python/Scripts" $PYTHON_SCRIPTS_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/python/Scripts" $GIT_PATH = "$InstallPath/git/bin" $GIT_EXTRA_PATH = "$InstallPath/$Env:CORE_PREFIX/git/bin" $Env:PATH = "$PYTHON_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_EXTRA_PATH$([System.IO.Path]::PathSeparator)$GIT_EXTRA_PATH$([System.IO.Path]::PathSeparator)$PYTHON_PATH$([System.IO.Path]::PathSeparator)$PYTHON_SCRIPTS_PATH$([System.IO.Path]::PathSeparator)$GIT_PATH$([System.IO.Path]::PathSeparator)$Env:PATH" # 环境变量 $Env:PIP_INDEX_URL = $PIP_INDEX_MIRROR $Env:PIP_EXTRA_INDEX_URL = $PIP_EXTRA_INDEX_MIRROR $Env:PIP_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_DEFAULT_INDEX = $PIP_INDEX_MIRROR $Env:UV_INDEX = $PIP_EXTRA_INDEX_MIRROR $Env:UV_FIND_LINKS = $PIP_FIND_MIRROR $Env:UV_LINK_MODE = "copy" $Env:UV_HTTP_TIMEOUT = 30 $Env:UV_CONCURRENT_DOWNLOADS = 50 $Env:UV_INDEX_STRATEGY = "unsafe-best-match" $Env:UV_CONFIG_FILE = "nul" $Env:PIP_CONFIG_FILE = "nul" $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 $Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 $Env:PIP_TIMEOUT = 30 $Env:PIP_RETRIES = 5 $Env:PIP_PREFER_BINARY = 1 $Env:PIP_YES = 1 $Env:PYTHONUTF8 = 1 $Env:PYTHONIOENCODING = "utf-8" $Env:PYTHONUNBUFFERED = 1 $Env:PYTHONNOUSERSITE = 1 $Env:PYTHONFAULTHANDLER = 1 $Env:PYTHONWARNINGS = "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning" $Env:GRADIO_ANALYTICS_ENABLED = "False" $Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 $Env:BITSANDBYTES_NOWELCOME = 1 $Env:ClDeviceGlobalMemSizeAvailablePercent = 100 $Env:CUDA_MODULE_LOADING = "LAZY" $Env:TORCH_CUDNN_V8_API_ENABLED = 1 $Env:USE_LIBUV = 0 $Env:SYCL_CACHE_PERSISTENT = 1 $Env:TF_CPP_MIN_LOG_LEVEL = 3 $Env:SAFETENSORS_FAST_GPU = 1 $Env:CACHE_HOME = "$InstallPath/cache" $Env:HF_HOME = "$InstallPath/cache/huggingface" $Env:MATPLOTLIBRC = "$InstallPath/cache" $Env:MODELSCOPE_CACHE = "$InstallPath/cache/modelscope/hub" $Env:MS_CACHE_HOME = "$InstallPath/cache/modelscope/hub" $Env:SYCL_CACHE_DIR = "$InstallPath/cache/libsycl_cache" $Env:TORCH_HOME = "$InstallPath/cache/torch" $Env:U2NET_HOME = "$InstallPath/cache/u2net" $Env:XDG_CACHE_HOME = "$InstallPath/cache" $Env:PIP_CACHE_DIR = "$InstallPath/cache/pip" $Env:PYTHONPYCACHEPREFIX = "$InstallPath/cache/pycache" $Env:TORCHINDUCTOR_CACHE_DIR = "$InstallPath/cache/torchinductor" $Env:TRITON_CACHE_DIR = "$InstallPath/cache/triton" $Env:UV_CACHE_DIR = "$InstallPath/cache/uv" $Env:UV_PYTHON = "$InstallPath/python/python.exe" # 消息输出 function Print-Msg ($msg) { Write-Host "[$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")]" -ForegroundColor Yellow -NoNewline Write-Host "[SD WebUI Installer]" -ForegroundColor Cyan -NoNewline Write-Host ":: " -ForegroundColor Blue -NoNewline Write-Host "$msg" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path "$PSScriptRoot/core_prefix.txt") -or ($CorePrefix)) { Print-Msg "检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀" if ($CorePrefix) { $origin_core_prefix = $CorePrefix } else { $origin_core_prefix = Get-Content "$PSScriptRoot/core_prefix.txt" } if ([System.IO.Path]::IsPathRooted($origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg "转换绝对路径为内核路径前缀: $origin_core_prefix -> $Env:CORE_PREFIX" } } Print-Msg "当前内核路径前缀: $Env:CORE_PREFIX" Print-Msg "完整内核路径: $InstallPath\$Env:CORE_PREFIX" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { $ver = $([string]$SD_WEBUI_INSTALLER_VERSION).ToCharArray() $major = ($ver[0..($ver.Length - 3)]) $minor = $ver[-2] $micro = $ver[-1] Print-Msg "SD WebUI Installer 版本: v${major}.${minor}.${micro}" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if ($USE_PIP_MIRROR) { Print-Msg "使用 PyPI 镜像源" } else { Print-Msg "检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源" } } # 代理配置 function Set-Proxy { $Env:NO_PROXY = "localhost,127.0.0.1,::1" # 检测是否禁用自动设置镜像源 if ((Test-Path "$PSScriptRoot/disable_proxy.txt") -or ($DisableProxy)) { Print-Msg "检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理" return } $internet_setting = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" if ((Test-Path "$PSScriptRoot/proxy.txt") -or ($UseCustomProxy)) { # 本地存在代理配置 if ($UseCustomProxy) { $proxy_value = $UseCustomProxy } else { $proxy_value = Get-Content "$PSScriptRoot/proxy.txt" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理" } elseif ($internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 $proxy_addr = $($internet_setting.ProxyServer) # 提取代理地址 if (($proxy_addr -match "http=(.*?);") -or ($proxy_addr -match "https=(.*?);")) { $proxy_value = $matches[1] # 去除 http / https 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "http://${proxy_value}" } elseif ($proxy_addr -match "socks=(.*)") { $proxy_value = $matches[1] # 去除 socks 前缀 $proxy_value = $proxy_value.ToString().Replace("http://", "").Replace("https://", "") $proxy_value = "socks://${proxy_value}" } else { $proxy_value = "http://${proxy_addr}" } $Env:HTTP_PROXY = $proxy_value $Env:HTTPS_PROXY = $proxy_value Print-Msg "检测到系统设置了代理, 已读取系统中的代理配置并设置代理" } } # 设置 uv 的使用状态 function Set-uv { if ((Test-Path "$PSScriptRoot/disable_uv.txt") -or ($DisableUV)) { Print-Msg "检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器" $Global:USE_UV = $false } else { Print-Msg "默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度" Print-Msg "当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装" $Global:USE_UV = $true } } # 检查 uv 是否需要更新 function Check-uv-Version { $content = " import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '$UV_MINIMUM_VER' print(is_uv_need_update()) ".Trim() Print-Msg "检测 uv 是否需要更新" $status = $(python -c "$content") if ($status -eq "True") { Print-Msg "更新 uv 中" python -m pip install -U "uv>=$UV_MINIMUM_VER" if ($?) { Print-Msg "uv 更新成功" } else { Print-Msg "uv 更新失败, 可能会造成 uv 部分功能异常" } } else { Print-Msg "uv 无需更新" } } # 下载并解压 Python function Install-Python { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/python-3.11.11-amd64.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/python-3.11.11-amd64.zip" ) $cache_path = "$Env:CACHE_HOME/python_tmp" $path = "$InstallPath/python" $i = 0 # 下载 Python ForEach ($url in $urls) { Print-Msg "正在下载 Python" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/python-amd64.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Python 中" } else { Print-Msg "Python 安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Python Print-Msg "正在解压 Python" Expand-Archive -Path "$Env:CACHE_HOME/python-amd64.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/python-amd64.zip" -Force -Recurse Print-Msg "Python 安装成功" } # 下载并解压 Git function Install-Git { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/PortableGit.zip", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/PortableGit.zip" ) $cache_path = "$Env:CACHE_HOME/git_tmp" $path = "$InstallPath/git" $i = 0 # 下载 Git ForEach ($url in $urls) { Print-Msg "正在下载 Git" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/PortableGit.zip" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Git 中" } else { Print-Msg "Git 安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } # 解压 Git Print-Msg "正在解压 Git" Expand-Archive -Path "$Env:CACHE_HOME/PortableGit.zip" -DestinationPath "$cache_path" -Force # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Remove-Item -Path "$Env:CACHE_HOME/PortableGit.zip" -Force -Recurse Print-Msg "Git 安装成功" } # 下载 Aria2 function Install-Aria2 { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe", "https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe" ) $i = 0 ForEach ($url in $urls) { Print-Msg "正在下载 Aria2" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/aria2c.exe" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载 Aria2 中" } else { Print-Msg "Aria2 安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } Move-Item -Path "$Env:CACHE_HOME/aria2c.exe" -Destination "$InstallPath/git/bin/aria2c.exe" -Force Print-Msg "Aria2 下载成功" } # 下载 uv function Install-uv { Print-Msg "正在下载 uv" python -m pip install uv if ($?) { Print-Msg "uv 下载成功" } else { Print-Msg "uv 下载失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # Github 镜像测试 function Set-Github-Mirror { $Env:GIT_CONFIG_GLOBAL = "$InstallPath/.gitconfig" # 设置 Git 配置文件路径 if (Test-Path "$InstallPath/.gitconfig") { Remove-Item -Path "$InstallPath/.gitconfig" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory "*" git config --global core.longpaths true if ((Test-Path "$PSScriptRoot/disable_gh_mirror.txt") -or ($DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg "检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源" return } # 使用自定义 Github 镜像源 if ((Test-Path "$PSScriptRoot/gh_mirror.txt") -or ($UseCustomGithubMirror)) { if ($UseCustomGithubMirror) { $github_mirror = $UseCustomGithubMirror } else { $github_mirror = Get-Content "$PSScriptRoot/gh_mirror.txt" } git config --global url."$github_mirror".insteadOf "https://github.com" Print-Msg "检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源" return } # 自动检测可用镜像源并使用 $status = 0 ForEach($i in $GITHUB_MIRROR_LIST) { Print-Msg "测试 Github 镜像源: $i" if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } git clone "$i/licyk/empty" "$Env:CACHE_HOME/github-mirror-test" --quiet if ($?) { Print-Msg "该 Github 镜像源可用" $github_mirror = $i $status = 1 break } else { Print-Msg "镜像源不可用, 更换镜像源进行测试" } } if (Test-Path "$Env:CACHE_HOME/github-mirror-test") { Remove-Item -Path "$Env:CACHE_HOME/github-mirror-test" -Force -Recurse } if ($status -eq 0) { Print-Msg "无可用 Github 镜像源, 取消使用 Github 镜像源" } else { Print-Msg "设置 Github 镜像源" git config --global url."$github_mirror".insteadOf "https://github.com" } } # Git 仓库下载 function Git-Clone { param ( [String]$url, [String]$path ) $name = [System.IO.Path]::GetFileNameWithoutExtension("$url") $folder_name = [System.IO.Path]::GetFileName("$path") Print-Msg "检测 $name 是否已安装" $status = 0 if (!(Test-Path "$path")) { $status = 1 } else { $items = Get-ChildItem "$path" if ($items.Count -eq 0) { $status = 1 } } if ($status -eq 1) { Print-Msg "正在下载 $name" $cache_path = "$Env:CACHE_HOME/${folder_name}_tmp" # 清理缓存路径 if (Test-Path "$cache_path") { Remove-Item -Path "$cache_path" -Force -Recurse } git clone --recurse-submodules $url "$cache_path" if ($?) { # 检测是否下载成功 # 清理空文件夹 if (Test-Path "$path") { $random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path "$path" -Destination "$Env:CACHE_HOME/$random_string" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path "$([System.IO.Path]::GetDirectoryName($path))" -Force > $null Move-Item -Path "$cache_path" -Destination "$path" -Force Print-Msg "$name 安装成功" } else { Print-Msg "$name 安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "$name 已安装" } } # 设置 PyTorch 镜像源 function Get-PyTorch-Mirror ($pytorch_package) { # 获取 PyTorch 的版本 $torch_part = @($pytorch_package -split ' ' | Where-Object { $_ -like "torch==*" })[0] if ($PyTorchMirrorType) { Print-Msg "使用指定的 PyTorch 镜像源类型: $PyTorchMirrorType" $mirror_type = $PyTorchMirrorType } elseif ($torch_part) { # 获取 PyTorch 镜像源类型 if ($torch_part.split("+") -eq $torch_part) { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def version_increment(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] += 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == 10: ver_parts[i] = 0 ver_parts[i - 1] += 1 return '.'.join(map(str, ver_parts)) def version_decrement(version: str) -> str: version = ''.join(re.findall(r'\d|\.', version)) ver_parts = list(map(int, version.split('.'))) ver_parts[-1] -= 1 for i in range(len(ver_parts) - 1, 0, -1): if ver_parts[i] == -1: ver_parts[i] = 9 ver_parts[i - 1] -= 1 while len(ver_parts) > 1 and ver_parts[0] == 0: ver_parts.pop(0) return '.'.join(map(str, ver_parts)) def has_version(version: str) -> bool: return version != version.replace('~=', '').replace('===', '').replace('!=', '').replace('<=', '').replace('>=', '').replace('<', '').replace('>', '').replace('==', '') def get_package_name(package: str) -> str: return package.split('~=')[0].split('===')[0].split('!=')[0].split('<=')[0].split('>=')[0].split('<')[0].split('>')[0].split('==')[0] def get_package_version(package: str) -> str: return package.split('~=').pop().split('===').pop().split('!=').pop().split('<=').pop().split('>=').pop().split('<').pop().split('>').pop().split('==').pop() def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def get_pytorch_mirror_type( torch_version: str, use_xpu: bool = False, use_rocm: bool = False, ) -> str: # cu118: 2.0.0 ~ 2.4.0 # cu121: 2.1.1 ~ 2.4.0 # cu124: 2.4.0 ~ 2.6.0 # cu126: 2.6.0 ~ 2.7.1 # cu128: 2.7.0 ~ 2.7.1 # cu129: 2.8.0 # cu130: 2.9.0 ~ torch_ver = get_package_version(torch_version) cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() has_gpus = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]) has_xpu = any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]) if compare_versions(torch_ver, '2.0.0') < 0: # torch < 2.0.0: default cu11x if has_gpus: return 'cu11x' if compare_versions(torch_ver, '2.0.0') >= 0 and compare_versions(torch_ver, '2.3.1') < 0: # 2.0.0 <= torch < 2.3.1: default cu118 if has_gpus: return 'cu118' if compare_versions(torch_ver, '2.3.0') >= 0 and compare_versions(torch_ver, '2.4.1') < 0: # 2.3.0 <= torch < 2.4.1: default cu121 if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu121' if compare_versions(torch_ver, '2.4.0') >= 0 and compare_versions(torch_ver, '2.6.0') < 0: # 2.4.0 <= torch < 2.6.0: default cu124 if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu121') >= 0: return 'cu121' if compare_versions(str(int(cuda_support_ver * 10)), 'cu118') >= 0: return 'cu118' if has_gpus: return 'cu124' if compare_versions(torch_ver, '2.6.0') >= 0 and compare_versions(torch_ver, '2.7.0') < 0: # 2.6.0 <= torch < 2.7.0: default cu126 if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu124') >= 0: return 'cu124' if compare_versions(cuda_comp_cap, '10.0') > 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu126' if compare_versions(torch_ver, '2.7.0') >= 0 and compare_versions(torch_ver, '2.8.0') < 0: # 2.7.0 <= torch < 2.8.0: default cu128 if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu128' if compare_versions(torch_ver, '2.8.0') >= 0 and compare_versions(torch_ver, '2.9.0') < 0: # torch ~= 2.8.0: default cu129 if compare_versions(str(int(cuda_support_ver * 10)), 'cu129') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu129' if compare_versions(torch_ver, '2.9.0') >= 0: # torch >= 2.9.0: default cu130 if compare_versions(str(int(cuda_support_ver * 10)), 'cu130') < 0: if compare_versions(str(int(cuda_support_ver * 10)), 'cu128') >= 0: return 'cu128' if compare_versions(str(int(cuda_support_ver * 10)), 'cu126') >= 0: return 'cu126' if use_xpu and has_xpu: return 'xpu' if has_gpus: return 'cu130' return 'cpu' if __name__ == '__main__': print(get_pytorch_mirror_type('$torch_part', use_xpu=True)) ".Trim() $mirror_type = $(python -c "$content") } else { $mirror_type = $torch_part.Split("+")[-1] } Print-Msg "PyTorch 镜像源类型: $mirror_type" } else { Print-Msg "未获取到 PyTorch 版本, 无法确定镜像源类型, 可能导致 PyTorch 安装失败" $mirror_type = "null" } # 设置对应的镜像源 switch ($mirror_type) { cpu { Print-Msg "设置 PyTorch 镜像源类型为 cpu" $pytorch_mirror_type = "cpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CPU } $mirror_extra_index_url = "" $mirror_find_links = "" } xpu { Print-Msg "设置 PyTorch 镜像源类型为 xpu" $pytorch_mirror_type = "xpu" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { $PIP_EXTRA_INDEX_MIRROR_XPU } $mirror_extra_index_url = "" $mirror_find_links = "" } cu11x { Print-Msg "设置 PyTorch 镜像源类型为 cu11x" $pytorch_mirror_type = "cu11x" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } cu118 { Print-Msg "设置 PyTorch 镜像源类型为 cu118" $pytorch_mirror_type = "cu118" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU118 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu121 { Print-Msg "设置 PyTorch 镜像源类型为 cu121" $pytorch_mirror_type = "cu121" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU121 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu124 { Print-Msg "设置 PyTorch 镜像源类型为 cu124" $pytorch_mirror_type = "cu124" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU124 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu126 { Print-Msg "设置 PyTorch 镜像源类型为 cu126" $pytorch_mirror_type = "cu126" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU126 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu128 { Print-Msg "设置 PyTorch 镜像源类型为 cu128" $pytorch_mirror_type = "cu128" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU128 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu129 { Print-Msg "设置 PyTorch 镜像源类型为 cu129" $pytorch_mirror_type = "cu129" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU129 } $mirror_extra_index_url = "" $mirror_find_links = "" } cu130 { Print-Msg "设置 PyTorch 镜像源类型为 cu130" $pytorch_mirror_type = "cu130" $mirror_index_url = if ($USE_PIP_MIRROR) { $PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { $PIP_EXTRA_INDEX_MIRROR_CU130 } $mirror_extra_index_url = "" $mirror_find_links = "" } Default { Print-Msg "未知的 PyTorch 镜像源类型: $mirror_type, 使用默认 PyTorch 镜像源" $pytorch_mirror_type = "null" $mirror_index_url = $Env:PIP_INDEX_URL $mirror_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $mirror_find_links = $Env:PIP_FIND_LINKS } } return $mirror_index_url, $mirror_extra_index_url, $mirror_find_links, $pytorch_mirror_type } # 为 PyTorch 获取合适的 CUDA 版本类型 function Get-Appropriate-CUDA-Version-Type { $content = " import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def select_avaliable_type() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() if compare_versions(cuda_support_ver, '13.0') >= 0: return 'cu130' elif compare_versions(cuda_support_ver, '12.9') >= 0: return 'cu129' elif compare_versions(cuda_support_ver, '12.8') >= 0: return 'cu128' elif compare_versions(cuda_support_ver, '12.6') >= 0: return 'cu126' elif compare_versions(cuda_support_ver, '12.4') >= 0: return 'cu124' elif compare_versions(cuda_support_ver, '12.1') >= 0: return 'cu121' elif compare_versions(cuda_support_ver, '11.8') >= 0: return 'cu118' elif compare_versions(cuda_comp_cap, '10.0') > 0: return 'cu128' # RTX 50xx elif compare_versions(cuda_comp_cap, '0.0') > 0: return 'cu118' # 其他 Nvidia 显卡 else: gpus = get_gpu_list() if any([ x for x in gpus if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): return 'xpu' if any([ x for x in gpus if 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): return 'cu118' return 'cpu' if __name__ == '__main__': print(select_avaliable_type()) ".Trim() return $(python -c "$content") } # 获取合适的 PyTorch / xFormers 版本 function Get-PyTorch-And-xFormers-Package { Print-Msg "设置 PyTorch 和 xFormers 版本" if ($PyTorchPackage) { # 使用自定义的 PyTorch / xFormers 版本 if ($xFormersPackage){ return $PyTorchPackage, $xFormersPackage } else { return $PyTorchPackage, $null } } if ($PyTorchMirrorType) { Print-Msg "根据 $PyTorchMirrorType 类型的 PyTorch 镜像源配置 PyTorch 组合" $appropriate_cuda_version = $PyTorchMirrorType } else { $appropriate_cuda_version = Get-Appropriate-CUDA-Version-Type } switch ($appropriate_cuda_version) { cu130 { $pytorch_package = "torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130" $xformers_package = "xformers==0.0.33" break } cu129 { $pytorch_package = "torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129" $xformers_package = "xformers==0.0.32.post2" break } cu128 { $pytorch_package = "torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128" $xformers_package = "xformers==0.0.33" break } cu126 { $pytorch_package = "torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126" $xformers_package = "xformers==0.0.33" break } cu124 { $pytorch_package = "torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124" $xformers_package = "xformers==0.0.29.post3" break } cu121 { $pytorch_package = "torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121" $xformers_package = "xformers===0.0.27" break } cu118 { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } xpu { $pytorch_package = "torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu" $xformers_package = $null break } cpu { $pytorch_package = "torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu" $xformers_package = $null break } Default { $pytorch_package = "torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118" $xformers_package = "xformers==0.0.27+cu118" break } } return $pytorch_package, $xformers_package } # 安装 PyTorch function Install-PyTorch { $pytorch_package, $xformers_package = Get-PyTorch-And-xFormers-Package $mirror_pip_index_url, $mirror_pip_extra_index_url, $mirror_pip_find_links, $pytorch_mirror_type = Get-PyTorch-Mirror $pytorch_package # 备份镜像源配置 $tmp_pip_index_url = $Env:PIP_INDEX_URL $tmp_uv_default_index = $Env:UV_DEFAULT_INDEX $tmp_pip_extra_index_url = $Env:PIP_EXTRA_INDEX_URL $tmp_uv_index = $Env:UV_INDEX $tmp_pip_find_links = $Env:PIP_FIND_LINKS $tmp_uv_find_links = $Env:UV_FIND_LINKS # 设置新的镜像源 $Env:PIP_INDEX_URL = $mirror_pip_index_url $Env:UV_DEFAULT_INDEX = $mirror_pip_index_url $Env:PIP_EXTRA_INDEX_URL = $mirror_pip_extra_index_url $Env:UV_INDEX = $mirror_pip_extra_index_url $Env:PIP_FIND_LINKS = $mirror_pip_find_links $Env:UV_FIND_LINKS = $mirror_pip_find_links Print-Msg "将要安装的 PyTorch: $pytorch_package" Print-Msg "将要安装的 xFormers: $xformers_package" Print-Msg "检测是否需要安装 PyTorch" python -m pip show torch --quiet 2> $null if (!($?)) { Print-Msg "安装 PyTorch 中" if ($USE_UV) { uv pip install $pytorch_package.ToString().Split() if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $pytorch_package.ToString().Split() } } else { python -m pip install $pytorch_package.ToString().Split() } if ($?) { Print-Msg "PyTorch 安装成功" } else { Print-Msg "PyTorch 安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } else { Print-Msg "PyTorch 已安装, 无需再次安装" } Print-Msg "检测是否需要安装 xFormers" python -m pip show xformers --quiet 2> $null if (!($?)) { if ($xformers_package) { Print-Msg "安装 xFormers 中" if ($USE_UV) { uv pip install $xformers_package.ToString().Split() --no-deps if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $xformers_package.ToString().Split() --no-deps } } else { python -m pip install $xformers_package.ToString().Split() --no-deps } if ($?) { Print-Msg "xFormers 安装成功" } else { Print-Msg "xFormers 安装失败, 终止 ComfyUI 安装进程, 可尝试重新运行 ComfyUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg "xFormers 已安装, 无需再次安装" } # 还原镜像源配置 $Env:PIP_INDEX_URL = $tmp_pip_index_url $Env:UV_DEFAULT_INDEX = $tmp_uv_default_index $Env:PIP_EXTRA_INDEX_URL = $tmp_pip_extra_index_url $Env:UV_INDEX = $tmp_uv_index $Env:PIP_FIND_LINKS = $tmp_pip_find_links $Env:UV_FIND_LINKS = $tmp_uv_find_links } # 安装 CLIP function Install-CLIP { $url = "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/clip_python_package.zip" Print-Msg "检测是否需要安装 CLIP 软件包" python -m pip show clip --quiet 2> $null if ($?) { Print-Msg "CLIP 软件包已安装" return } else { Print-Msg "安装 CLIP 软件包中" } if ($USE_UV) { uv pip install $url if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install $url } } else { python -m pip install $url } if ($?) { Print-Msg "CLIP 软件包安装成功" } else { Print-Msg "CLIP 软件包安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } } # 安装 Stable Diffusion WebUI 依赖 function Install-Stable-Diffusion-WebUI-Dependence { # 记录脚本所在路径 $current_path = $(Get-Location).ToString() Set-Location "$InstallPath/$Env:CORE_PREFIX" $dep_path = "$InstallPath/$Env:CORE_PREFIX/requirements_versions.txt" # SD Next if (!(Test-Path "$dep_path")) { $dep_path = "$InstallPath/$Env:CORE_PREFIX/requirements.txt" } Print-Msg "安装 Stable Diffusion WebUI 依赖中" if ($USE_UV) { uv pip install -r "$dep_path" if (!($?)) { Print-Msg "检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装" python -m pip install -r "$dep_path" } } else { python -m pip install -r "$dep_path" } if ($?) { Print-Msg "Stable Diffusion WebUI 依赖安装成功" } else { Print-Msg "Stable Diffusion WebUI 依赖安装失败, 终止 Stable Diffusion WebUI 安装进程, 可尝试重新运行 SD WebUI Installer 重试失败的安装" Set-Location "$current_path" if (!($BuildMode)) { Read-Host | Out-Null } exit 1 } Set-Location "$current_path" } # 模型下载器 function Model-Downloader ($download_list) { $sum = $download_list.Count for ($i = 0; $i -lt $download_list.Count; $i++) { $content = $download_list[$i] $url = $content[0] $path = $content[1] $file = $content[2] $model_full_path = Join-Path -Path $path -ChildPath $file if (Test-Path $model_full_path) { Print-Msg "[$($i + 1)/$sum] $file 模型已存在于 $path 中" } else { Print-Msg "[$($i + 1)/$sum] 下载 $file 模型到 $path 中" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M $url -d "$path" -o "$file" if ($?) { Print-Msg "[$($i + 1)/$sum] $file 下载成功" } else { Print-Msg "[$($i + 1)/$sum] $file 下载失败" } } } } # 配置安装的核心组件列表 function Get-Stable-Diffusion-WebUI-Component-List ($branch) { $sd_webui_repositories = New-Object System.Collections.ArrayList $repositories_list = New-Object System.Collections.ArrayList $sd_webui_repositories_path = "$InstallPath/$Env:CORE_PREFIX/repositories" $sd_webui_repositories.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/salesforce/BLIP", "$sd_webui_repositories_path/BLIP" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/Stability-AI/stablediffusion", "$sd_webui_repositories_path/stable-diffusion-stability-ai" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/Stability-AI/generative-models", "$sd_webui_repositories_path/generative-models" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/crowsonkb/k-diffusion", "$sd_webui_repositories_path/k-diffusion" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets", "$sd_webui_repositories_path/stable-diffusion-webui-assets" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui_forge"), "https://github.com/lllyasviel/huggingface_guess", "$sd_webui_repositories_path/huggingface_guess" )) | Out-Null $sd_webui_repositories.Add(@( @("sd_webui_forge"), "https://github.com/lllyasviel/google_blockly_prototypes", "$sd_webui_repositories_path/google_blockly_prototypes" )) | Out-Null for ($i = 0; $i -lt $sd_webui_repositories.Count; $i++) { $branch_type, $repo_url, $path = $sd_webui_repositories[$i] if ($branch -in $branch_type) { $repositories_list.Add(@($repo_url, $path)) | Out-Null } } return $repositories_list } # 配置安装的扩展列表 function Get-Stable-Diffusion-WebUI-Extension ($branch) { $sd_webui_extension = New-Object System.Collections.ArrayList $extension_list = New-Object System.Collections.ArrayList $sd_webui_extension_path = "$InstallPath/$Env:CORE_PREFIX/extensions" $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Coyote-A/ultimate-upscale-for-automatic1111", "$sd_webui_extension_path/ultimate-upscale-for-automatic1111" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/DominikDoom/a1111-sd-webui-tagcomplete", "$sd_webui_extension_path/a1111-sd-webui-tagcomplete" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Bing-su/adetailer", "$sd_webui_extension_path/adetailer" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/zanllp/sd-webui-infinite-image-browsing", "$sd_webui_extension_path/sd-webui-infinite-image-browsing" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/huchenlei/sd-webui-openpose-editor", "$sd_webui_extension_path/sd-webui-openpose-editor" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Physton/sd-webui-prompt-all-in-one", "$sd_webui_extension_path/sd-webui-prompt-all-in-one" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu"), "https://github.com/licyk/sd-webui-wd14-tagger", "$sd_webui_extension_path/sd-webui-wd14-tagger" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/hanamizuki-ai/stable-diffusion-webui-localization-zh_Hans", "$sd_webui_extension_path/stable-diffusion-webui-localization-zh_Hans" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Haoming02/sd-webui-mosaic-outpaint", "$sd_webui_extension_path/sd-webui-mosaic-outpaint" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Haoming02/sd-webui-resource-monitor", "$sd_webui_extension_path/sd-webui-resource-monitor" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/licyk/sd-webui-tcd-sampler", "$sd_webui_extension_path/sd-webui-tcd-sampler" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu"), "https://github.com/licyk/advanced_euler_sampler_extension", "$sd_webui_extension_path/advanced_euler_sampler_extension" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_amdgpu"), "https://github.com/hako-mikan/sd-webui-regional-prompter", "$sd_webui_extension_path/sd-webui-regional-prompter" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/Akegarasu/sd-webui-model-converter", "$sd_webui_extension_path/sd-webui-model-converter" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_amdgpu"), "https://github.com/Mikubill/sd-webui-controlnet", "$sd_webui_extension_path/sd-webui-controlnet" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_amdgpu"), "https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111", "$sd_webui_extension_path/multidiffusion-upscaler-for-automatic1111" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_amdgpu", "sdnext"), "https://github.com/mcmonkeyprojects/sd-dynamic-thresholding", "$sd_webui_extension_path/sd-dynamic-thresholding" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_amdgpu", "sdnext"), "https://github.com/hako-mikan/sd-webui-lora-block-weight", "$sd_webui_extension_path/sd-webui-lora-block-weight" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu"), "https://github.com/arenasys/stable-diffusion-webui-model-toolkit", "$sd_webui_extension_path/stable-diffusion-webui-model-toolkit" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/licyk/a1111-sd-webui-haku-img", "$sd_webui_extension_path/a1111-sd-webui-haku-img" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_reforge", "sd_webui_amdgpu"), "https://github.com/hako-mikan/sd-webui-supermerger", "$sd_webui_extension_path/sd-webui-supermerger" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_reforge", "sd_webui_amdgpu", "sdnext"), "https://github.com/continue-revolution/sd-webui-segment-anything", "$sd_webui_extension_path/sd-webui-segment-anything" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui_forge"), "https://github.com/licyk/sd_forge_hypertile_svd_z123", "$sd_webui_extension_path/sd_forge_hypertile_svd_z123" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui_forge"), "https://github.com/lllyasviel/sd-forge-layerdiffuse", "$sd_webui_extension_path/sd-forge-layerdiffuse" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/licyk/sd-webui-licyk-style-image", "$sd_webui_extension_path/sd-webui-licyk-style-image" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/w-e-w/sdwebui-close-confirmation-dialogue", "$sd_webui_extension_path/sdwebui-close-confirmation-dialogue" )) | Out-Null $sd_webui_extension.Add(@( @("sd_webui", "sd_webui_forge", "sd_webui_reforge", "sd_webui_forge_classic", "sd_webui_amdgpu", "sdnext"), "https://github.com/viyiviyi/stable-diffusion-webui-zoomimage", "$sd_webui_extension_path/stable-diffusion-webui-zoomimage" )) | Out-Null for ($i = 0; $i -lt $sd_webui_extension.Count; $i++) { $branch_type, $repo_url, $path = $sd_webui_extension[$i] if ($branch -in $branch_type) { $extension_list.Add(@($repo_url, $path)) | Out-Null } } return $extension_list } # 安装 function Check-Install { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null Print-Msg "检测是否安装 Python" if ((Test-Path "$InstallPath/python/python.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { Print-Msg "Python 已安装" } else { Print-Msg "Python 未安装" Install-Python } # 切换 uv 指定的 Python if (Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe") { $Env:UV_PYTHON = "$InstallPath/$Env:CORE_PREFIX/python/python.exe" } Print-Msg "检测是否安装 Git" if ((Test-Path "$InstallPath/git/bin/git.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { Print-Msg "Git 已安装" } else { Print-Msg "Git 未安装" Install-Git } Print-Msg "检测是否安装 Aria2" if ((Test-Path "$InstallPath/git/bin/aria2c.exe") -or (Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/aria2c.exe")) { Print-Msg "Aria2 已安装" } else { Print-Msg "Aria2 未安装" Install-Aria2 } Print-Msg "检测是否安装 uv" python -m pip show uv --quiet 2> $null if ($?) { Print-Msg "uv 已安装" } else { Print-Msg "uv 未安装" Install-uv } Check-uv-Version Set-Github-Mirror if ((Test-Path "$PSScriptRoot/install_sd_webui.txt") -or ($InstallBranch -eq "sd_webui")) { $branch_type = "sd_webui" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge.txt") -or ($InstallBranch -eq "sd_webui_forge")) { $branch_type = "sd_webui_forge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_reforge.txt") -or ($InstallBranch -eq "sd_webui_reforge")) { $branch_type = "sd_webui_reforge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge_classic.txt") -or ($InstallBranch -eq "sd_webui_forge_classic")) { $branch_type = "sd_webui_forge_classic" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_amdgpu.txt") -or ($InstallBranch -eq "sd_webui_amdgpu")) { $branch_type = "sd_webui_amdgpu" } elseif ((Test-Path "$PSScriptRoot/install_sd_next.txt") -or ($InstallBranch -eq "sdnext")) { $branch_type = "sdnext" } else { $branch_type = "sd_webui" } $sd_webui_component = Get-Stable-Diffusion-WebUI-Component-List $branch_type $sd_webui_extension = Get-Stable-Diffusion-WebUI-Extension $branch_type # SD WebUI 核心 Git-Clone "$SD_WEBUI_REPO" "$InstallPath/$Env:CORE_PREFIX" # SD WebUI 组件 for ($i = 0; $i -lt $sd_webui_component.Count; $i++) { $repo_url, $path = $sd_webui_component[$i] Git-Clone "$repo_url" "$path" } # SD WebUI 扩展 if ($NoPreDownloadExtension) { Print-Msg "检测到 -NoPreDownloadExtension 命令行参数, 跳过安装 Stable Diffusion WebUI 扩展" } else { for ($i = 0; $i -lt $sd_webui_extension.Count; $i++) { $repo_url, $path = $sd_webui_extension[$i] Git-Clone "$repo_url" "$path" } } Install-PyTorch Install-CLIP Install-Stable-Diffusion-WebUI-Dependence if (!(Test-Path "$InstallPath/launch_args.txt")) { Print-Msg "设置默认 Stable Diffusion WebUI 启动参数" if ((Test-Path "$PSScriptRoot/install_sd_webui.txt") -or ($InstallBranch -eq "sd_webui")) { $content = "--theme dark --autolaunch --xformers --api --skip-load-model-at-start --skip-python-version-check --skip-version-check --no-download-sd-model" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge.txt") -or ($InstallBranch -eq "sd_webui_forge")) { $content = "--theme dark --autolaunch --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_reforge.txt") -or ($InstallBranch -eq "sd_webui_reforge")) { $content = "--theme dark --autolaunch --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge_classic.txt") -or ($InstallBranch -eq "sd_webui_forge_classic")) { $content = "--theme dark --autolaunch --xformers --api --skip-python-version-check --skip-version-check" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_amdgpu.txt") -or ($InstallBranch -eq "sd_webui_amdgpu")) { $content = "--theme dark --autolaunch --api --skip-torch-cuda-test --backend directml --skip-python-version-check --skip-version-check --no-download-sd-model" } elseif ((Test-Path "$PSScriptRoot/install_sd_next.txt") -or ($InstallBranch -eq "sdnext")) { $content = "--autolaunch --use-cuda --use-xformers" } else { $content = "--theme dark --autolaunch --xformers --api --skip-load-model-at-start --skip-python-version-check --skip-version-check --no-download-sd-model" } Set-Content -Encoding UTF8 -Path "$InstallPath/launch_args.txt" -Value $content } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/config.json")) { Print-Msg "设置默认 Stable Diffusion WebUI 设置" $json_content = @{ "quicksettings_list" = @( "sd_model_checkpoint", "sd_vae", "CLIP_stop_at_last_layers" ) "save_to_dirs" = $false "grid_save_to_dirs" = $false "export_for_4chan" = $false "CLIP_stop_at_last_layers" = 2 "localization" = "zh-Hans (Stable)" "show_progress_every_n_steps" = 1 "js_live_preview_in_modal_lightbox" = $true "upscaler_for_img2img" = "Lanczos" "emphasis" = "No norm" "samples_filename_pattern" = "[datetime<%Y%m%d_%H%M%S>]_[model_name]_[sampler]" "extra_options_img2img" = @( "upscaler_for_img2img", "img2img_color_correction", "img2img_fix_steps", "img2img_extra_noise" ) "extra_options_txt2img" = @( "img2img_extra_noise" ) "img2img_color_correction" = $true } $json_content = $json_content | ConvertTo-Json -Depth 4 # 创建一个不带 BOM 的 UTF-8 编码器 $utf8_encoding = New-Object System.Text.UTF8Encoding($false) # 使用 StreamWriter 来写入文件 $stream_writer = [System.IO.StreamWriter]::new("$InstallPath/$Env:CORE_PREFIX/config.json", $false, $utf8_encoding) $stream_writer.Write($json_content) $stream_writer.Close() } if ($NoPreDownloadModel) { Print-Msg "检测到 -NoPreDownloadModel 命令行参数, 跳过下载模型" } else { Print-Msg "预下载模型中" $model_list = New-Object System.Collections.ArrayList $checkpoint_path = "$InstallPath/$Env:CORE_PREFIX/models/Stable-diffusion" $vae_approx_path = "$InstallPath/$Env:CORE_PREFIX/models/VAE-approx" $model_list.Add(@("https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/model.pt", "$vae_approx_path", "model.pt")) | Out-Null $model_list.Add(@("https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sdxl.pt", "$vae_approx_path", "vaeapprox-sdxl.pt")) | Out-Null $model_list.Add(@("https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sd3.pt", "$vae_approx_path", "vaeapprox-sd3.pt")) | Out-Null $url = "https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors" $name = Split-Path -Path $url -Leaf if ((!(Get-ChildItem -Path $checkpoint_path -Include "*.safetensors", "*.pth", "*.ckpt" -Recurse)) -or (Test-Path "$checkpoint_path/${name}.aria2")) { $model_list.Add(@("$url", "$checkpoint_path", "$name")) | Out-Null } Model-Downloader $model_list } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } # 启动脚本 function Write-Launch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableUV, [string]`$LaunchArg, [switch]`$EnableShortcut, [switch]`$DisableCUDAMalloc, [switch]`$DisableEnvCheck, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-DisableUV] [-LaunchArg <Stable Diffusion WebUI 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableUV 禁用 SD WebUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -LaunchArg <Stable Diffusion WebUI 启动参数> 设置 Stable Diffusion WebUI 自定义启动参数, 如启用 --autolaunch 和 --xformers, 则使用 -LaunchArg ```"--autolaunch --xformers```" 进行启用 -EnableShortcut 创建 Stable Diffusion WebUI 启动快捷方式 -DisableCUDAMalloc 禁用 SD WebUI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck 禁用 SD WebUI Installer 检查 Stable Diffusion WebUI 运行环境中存在的问题, 禁用后可能会导致 Stable Diffusion WebUI 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 修复 PyTorch 的 libomp 问题 function Fix-PyTorch { `$content = `" import importlib.util import shutil import os import ctypes import logging try: torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: lib_folder = os.path.join(folder, 'lib') test_file = os.path.join(lib_folder, 'fbgemm.dll') dest = os.path.join(lib_folder, 'libomp140.x86_64.dll') if os.path.exists(dest): break with open(test_file, 'rb') as f: contents = f.read() if b'libomp140.x86_64.dll' not in contents: break try: mydll = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as e: logging.warning('检测到 PyTorch 版本存在 libomp 问题, 进行修复') shutil.copyfile(os.path.join(lib_folder, 'libiomp5md.dll'), dest) except Exception as _: pass `".Trim() Print-Msg `"检测 PyTorch 的 libomp 问题中`" python -c `"`$content`" Print-Msg `"PyTorch 检查完成`" } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # Stable Diffusion WebUI 启动参数 function Get-Stable-Diffusion-WebUI-Launch-Args { `$arguments = New-Object System.Collections.ArrayList if ((Test-Path `"`$PSScriptRoot/launch_args.txt`") -or (`$LaunchArg)) { if (`$LaunchArg) { `$launch_args = `$LaunchArg } else { `$launch_args = Get-Content `"`$PSScriptRoot/launch_args.txt`" } if (`$launch_args.Trim().Split().Length -le 1) { `$arguments = `$launch_args.Trim().Split() } else { `$arguments = [regex]::Matches(`$launch_args, '(`"[^`"]*`"|''[^'']*''|\S+)') | ForEach-Object { `$_.Value -replace '^[`"'']|[`"'']`$', '' } } Print-Msg `"检测到本地存在 launch_args.txt 启动参数配置文件 / -LaunchArg 命令行参数, 已读取该启动参数配置文件并应用启动参数`" Print-Msg `"使用的启动参数: `$arguments`" } return `$arguments } # 设置 Stable Diffusion WebUI 的快捷启动方式 function Create-Stable-Diffusion-WebUI-Shortcut { # 设置快捷方式名称 if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"AUTOMATIC1111/stable-diffusion-webui`") -or (`$branch -eq `"AUTOMATIC1111/stable-diffusion-webui.git`")) { `$filename = `"SD-WebUI`" } elseif ((`$branch -eq `"lllyasviel/stable-diffusion-webui-forge`") -or (`$branch -eq `"lllyasviel/stable-diffusion-webui-forge.git`")) { `$filename = `"SD-WebUI-Forge`" } elseif ((`$branch -eq `"Panchovix/stable-diffusion-webui-reForge`") -or (`$branch -eq `"Panchovix/stable-diffusion-webui-reForge.git`")) { `$filename = `"SD-WebUI-reForge`" } elseif ((`$branch -eq `"Haoming02/sd-webui-forge-classic`") -or (`$branch -eq `"Haoming02/sd-webui-forge-classic.git`")) { `$filename = `"SD-WebUI-Forge-Classic`" } elseif ((`$branch -eq `"lshqqytiger/stable-diffusion-webui-amdgpu`") -or (`$branch -eq `"lshqqytiger/stable-diffusion-webui-amdgpu.git`")) { `$filename = `"SD-WebUI-AMDGPU`" } elseif ((`$branch -eq `"vladmandic/automatic`") -or (`$branch -eq `"vladmandic/automatic.git`") -or (`$branch -eq `"vladmandic/sdnext`") -or (`$branch -eq `"vladmandic/sdnext.git`")) { `$filename = `"SD-Next`" } else { `$filename = `"SD-WebUI`" } } else { `$filename = `"SD-WebUI`" } `$url = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/gradio_icon.ico`" `$shortcut_icon = `"`$PSScriptRoot/gradio_icon.ico`" if ((!(Test-Path `"`$PSScriptRoot/enable_shortcut.txt`")) -and (!(`$EnableShortcut))) { return } Print-Msg `"检测到 enable_shortcut.txt 配置文件 / -EnableShortcut 命令行参数, 开始检查 Stable Diffusion WebUI 快捷启动方式中`" if (!(Test-Path `"`$shortcut_icon`")) { Print-Msg `"获取 Stable Diffusion WebUI 图标中`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/gradio_icon.ico`" if (!(`$?)) { Print-Msg `"获取 Stable Diffusion WebUI 图标失败, 无法创建 Stable Diffusion WebUI 快捷启动方式`" return } } Print-Msg `"更新 Stable Diffusion WebUI 快捷启动方式`" `$shell = New-Object -ComObject WScript.Shell `$desktop = [System.Environment]::GetFolderPath(`"Desktop`") `$shortcut_path = `"`$desktop\`$filename.lnk`" `$shortcut = `$shell.CreateShortcut(`$shortcut_path) `$shortcut.TargetPath = `"`$PSHome\powershell.exe`" `$launch_script_path = `$(Get-Item `"`$PSScriptRoot/launch.ps1`").FullName `$shortcut.Arguments = `"-ExecutionPolicy Bypass -File ```"`$launch_script_path```"`" `$shortcut.IconLocation = `$shortcut_icon # 保存到桌面 `$shortcut.Save() `$start_menu_path = `"`$Env:APPDATA/Microsoft/Windows/Start Menu/Programs`" `$taskbar_path = `"`$Env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar`" # 保存到开始菜单 Copy-Item -Path `"`$shortcut_path`" -Destination `"`$start_menu_path`" -Force # 固定到任务栏 # Copy-Item -Path `"`$shortcut_path`" -Destination `"`$taskbar_path`" -Force # `$shell = New-Object -ComObject Shell.Application # `$shell.Namespace([System.IO.Path]::GetFullPath(`$taskbar_path)).ParseName((Get-Item `$shortcut_path).Name).InvokeVerb('taskbarpin') } # 设置 CUDA 内存分配器 function Set-PyTorch-CUDA-Memory-Alloc { if ((!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) -and (!(`$DisableCUDAMalloc))) { Print-Msg `"检测是否可设置 CUDA 内存分配器`" } else { Print-Msg `"检测到 disable_set_pytorch_cuda_memory_alloc.txt 配置文件 / -DisableCUDAMalloc 命令行参数, 已禁用自动设置 CUDA 内存分配器`" return } `$content = `" import os import importlib.util import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ('StateFlags', ctypes.c_ulong), ('DeviceID', ctypes.c_char * 128), ('DeviceKey', ctypes.c_char * 128) ] # Load user32.dll user32 = ctypes.windll.user32 # Call EnumDisplayDevicesA def enum_display_devices(): device_info = DISPLAY_DEVICEA() device_info.cb = ctypes.sizeof(device_info) device_index = 0 gpu_names = set() while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0): device_index += 1 gpu_names.add(device_info.DeviceString.decode('utf-8')) return gpu_names return enum_display_devices() else: gpu_names = set() out = subprocess.check_output(['nvidia-smi', '-L']) for l in out.split(b'\n'): if len(l) > 0: gpu_names.add(l.decode('utf-8').split(' (UUID')[0]) return gpu_names blacklist = {'GeForce GTX TITAN X', 'GeForce GTX 980', 'GeForce GTX 970', 'GeForce GTX 960', 'GeForce GTX 950', 'GeForce 945M', 'GeForce 940M', 'GeForce 930M', 'GeForce 920M', 'GeForce 910M', 'GeForce GTX 750', 'GeForce GTX 745', 'Quadro K620', 'Quadro K1200', 'Quadro K2200', 'Quadro M500', 'Quadro M520', 'Quadro M600', 'Quadro M620', 'Quadro M1000', 'Quadro M1200', 'Quadro M2000', 'Quadro M2200', 'Quadro M3000', 'Quadro M4000', 'Quadro M5000', 'Quadro M5500', 'Quadro M6000', 'GeForce MX110', 'GeForce MX130', 'GeForce 830M', 'GeForce 840M', 'GeForce GTX 850M', 'GeForce GTX 860M', 'GeForce GTX 1650', 'GeForce GTX 1630', 'Tesla M4', 'Tesla M6', 'Tesla M10', 'Tesla M40', 'Tesla M60' } def cuda_malloc_supported(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: for b in blacklist: if b in x: return False return True def is_nvidia_device(): try: names = get_gpu_names() except: names = set() for x in names: if 'NVIDIA' in x: return True return False def get_pytorch_cuda_alloc_conf(is_cuda = True): if is_nvidia_device(): if cuda_malloc_supported(): if is_cuda: return 'cuda_malloc' else: return 'pytorch_malloc' else: return 'pytorch_malloc' else: return None def main(): try: version = '' torch_spec = importlib.util.find_spec('torch') for folder in torch_spec.submodule_search_locations: ver_file = os.path.join(folder, 'version.py') if os.path.isfile(ver_file): spec = importlib.util.spec_from_file_location('torch_version_import', ver_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) version = module.__version__ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up if '+cu' in version: #only on cuda torch print(get_pytorch_cuda_alloc_conf()) else: print(get_pytorch_cuda_alloc_conf(False)) else: print(None) except Exception as _: print(None) if __name__ == '__main__': main() `".Trim() `$status = `$(python -c `"`$content`") switch (`$status) { cuda_malloc { Print-Msg `"设置 CUDA 内存分配器为 CUDA 内置异步分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"backend:cudaMallocAsync`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"backend:cudaMallocAsync`" } pytorch_malloc { Print-Msg `"设置 CUDA 内存分配器为 PyTorch 原生分配器`" `$Env:PYTORCH_CUDA_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" # PyTorch 将弃用该参数 `$Env:PYTORCH_ALLOC_CONF = `"garbage_collection_threshold:0.9,max_split_size_mb:512`" } Default { Print-Msg `"显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器`" } } } # 检查 Stable Diffusion WebUI 依赖完整性 function Check-Stable-Diffusion-WebUI-Requirements { `$content = `" import inspect import platform import re import os import sys import copy import logging import argparse import importlib.metadata from pathlib import Path from typing import Any, Callable, NamedTuple def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数输入参数输入```"```"```" parser = argparse.ArgumentParser(description=```"运行环境检查```") def _normalized_filepath(filepath): return Path(filepath).absolute().as_posix() parser.add_argument( ```"--requirement-path```", type=_normalized_filepath, default=None, help=```"依赖文件路径```", ) parser.add_argument(```"--debug-mode```", action=```"store_true```", help=```"显示调试信息```") return parser.parse_args() COMMAND_ARGS = get_args() class LoggingColoredFormatter(logging.Formatter): ```"```"```"Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 ```"```"```" COLORS = { ```"DEBUG```": ```"\033[0;36m```", # CYAN ```"INFO```": ```"\033[0;32m```", # GREEN ```"WARNING```": ```"\033[0;33m```", # YELLOW ```"ERROR```": ```"\033[0;31m```", # RED ```"CRITICAL```": ```"\033[0;37;41m```", # WHITE ON RED ```"RESET```": ```"\033[0m```", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: ```"```"```"Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True ```"```"```" super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS[```"RESET```"]) colored_record.levelname = f```"{seq}{levelname}{self.COLORS['RESET']}```" return super().format(colored_record) def get_logger( name: str | None = None, level: int | None = logging.INFO, color: bool | None = True ) -> logging.Logger: ```"```"```"获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 ```"```"```" stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r```"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s```", r```"%Y-%m-%d %H:%M:%S```", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug(```"Logger 初始化完成```") return _logger logger = get_logger( name=```"Requirement Checker```", level=logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO, ) class PyWhlVersionComponent(NamedTuple): ```"```"```"Python 版本号组件 参考: https://peps.python.org/pep-0440 Attributes: epoch (int): 版本纪元号, 用于处理不兼容的重大更改, 默认为 0 release (list[int]): 发布版本号段, 主版本号的数字部分, 如 [1, 2, 3] pre_l (str | None): 预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等 pre_n (int | None): 预发布版本编号, 与预发布标签配合使用 post_n1 (int | None): 后发布版本编号, 格式如 1.0-1 中的数字 post_l (str | None): 后发布标签, 如 'post', 'rev', 'r' 等 post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字 dev_l (str | None): 开发版本标签, 通常为 'dev' dev_n (int | None): 开发版本编号, 如 dev1 中的数字 local (str | None): 本地版本标识符, 加号后面的部分 is_wildcard (bool): 标记是否包含通配符, 用于版本范围匹配 ```"```"```" epoch: int ```"```"```"版本纪元号, 用于处理不兼容的重大更改, 默认为 0```"```"```" release: list[int] ```"```"```"发布版本号段, 主版本号的数字部分, 如 [1, 2, 3]```"```"```" pre_l: str | None ```"```"```"预发布标签, 包括 'a', 'b', 'rc', 'alpha' 等```"```"```" pre_n: int | None ```"```"```"预发布版本编号, 与预发布标签配合使用```"```"```" post_n1: int | None ```"```"```"后发布版本编号, 格式如 1.0-1 中的数字```"```"```" post_l: str | None ```"```"```"后发布标签, 如 'post', 'rev', 'r' 等```"```"```" post_n2: int | None ```"```"```"post_n2 (int | None): 后发布版本编号, 格式如 1.0-post1 中的数字```"```"```" dev_l: str | None ```"```"```"开发版本标签, 通常为 'dev'```"```"```" dev_n: int | None ```"```"```"开发版本编号, 如 dev1 中的数字```"```"```" local: str | None ```"```"```"本地版本标识符, 加号后面的部分```"```"```" is_wildcard: bool ```"```"```"标记是否包含通配符, 用于版本范围匹配```"```"```" class PyWhlVersionComparison: ```"```"```"Python 版本号比较工具 使用: ````````````python # 常规版本匹配 PyWhlVersionComparison(```"2.0.0```") < PyWhlVersionComparison(```"2.3.0+cu118```") # True PyWhlVersionComparison(```"2.0```") > PyWhlVersionComparison(```"0.9```") # True PyWhlVersionComparison(```"1.3```") <= PyWhlVersionComparison(```"1.2.2```") # False # 通配符版本匹配, 需要在不包含通配符的版本对象中使用 ~ 符号 PyWhlVersionComparison(```"1.0*```") == ~PyWhlVersionComparison(```"1.0a1```") # True PyWhlVersionComparison(```"0.9*```") == ~PyWhlVersionComparison(```"1.0```") # False ```````````` Attributes: VERSION_PATTERN (str): 提去 Wheel 版本号的正则表达式 WHL_VERSION_PARSE_REGEX (re.Pattern): 编译后的用于解析 Wheel 版本号的工具 version (str): 版本号字符串 ```"```"```" def __init__(self, version: str) -> None: ```"```"```"初始化 Python 版本号比较工具 Args: version (str): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_lt_v2(self.version, other.version) def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_gt_v2(self.version, other.version) def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_le_v2(self.version, other.version) def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_ge_v2(self.version, other.version) def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return self.is_v1_eq_v2(self.version, other.version) def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, PyWhlVersionComparison): return NotImplemented return not self.is_v1_eq_v2(self.version, other.version) def __invert__(self) -> ```"PyWhlVersionMatcher```": ```"```"```"使用 ~ 操作符实现兼容性版本匹配 (~= 的语义) Returns: PyWhlVersionMatcher: 兼容性版本匹配器 ```"```"```" return PyWhlVersionMatcher(self.version) # 提取版本标识符组件的正则表达式 # ref: # https://peps.python.org/pep-0440 # https://packaging.python.org/en/latest/specifications/version-specifiers VERSION_PATTERN = r```"```"```" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version ```"```"```" # 编译正则表达式 WHL_VERSION_PARSE_REGEX = re.compile( r```"^\s*```" + VERSION_PATTERN + r```"\s*$```", re.VERBOSE | re.IGNORECASE, ) def parse_version(self, version_str: str) -> PyWhlVersionComponent: ```"```"```"解释 Python 软件包版本号 Args: version_str (str): Python 软件包版本号 Returns: PyWhlVersionComponent: 版本组件的命名元组 Raises: ValueError: 如果 Python 版本号不符合 PEP440 规范 ```"```"```" # 检测并剥离通配符 wildcard = version_str.endswith(```".*```") or version_str.endswith(```"*```") clean_str = version_str.rstrip(```"*```").rstrip(```".```") if wildcard else version_str match = self.WHL_VERSION_PARSE_REGEX.match(clean_str) if not match: logger.debug(```"未知的版本号字符串: %s```", version_str) raise ValueError(f```"未知的版本号字符串: {version_str}```") components = match.groupdict() # 处理 release 段 (允许空字符串) release_str = components[```"release```"] or ```"0```" release_segments = [int(seg) for seg in release_str.split(```".```")] # 构建命名元组 return PyWhlVersionComponent( epoch=int(components[```"epoch```"] or 0), release=release_segments, pre_l=components[```"pre_l```"], pre_n=int(components[```"pre_n```"]) if components[```"pre_n```"] else None, post_n1=int(components[```"post_n1```"]) if components[```"post_n1```"] else None, post_l=components[```"post_l```"], post_n2=int(components[```"post_n2```"]) if components[```"post_n2```"] else None, dev_l=components[```"dev_l```"], dev_n=int(components[```"dev_n```"]) if components[```"dev_n```"] else None, local=components[```"local```"], is_wildcard=wildcard, ) def compare_version_objects( self, v1: PyWhlVersionComponent, v2: PyWhlVersionComponent ) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: v1 (PyWhlVersionComponent): 第 1 个 Python 版本号标识符组件 v2 (PyWhlVersionComponent): 第 2 个 Python 版本号标识符组件 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" # 比较 epoch if v1.epoch != v2.epoch: return v1.epoch - v2.epoch # 对其 release 长度, 缺失部分补 0 if len(v1.release) != len(v2.release): for _ in range(abs(len(v1.release) - len(v2.release))): if len(v1.release) < len(v2.release): v1.release.append(0) else: v2.release.append(0) # 比较 release for n1, n2 in zip(v1.release, v2.release): if n1 != n2: return n1 - n2 # 如果 release 长度不同, 较短的版本号视为较小 ? # 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15] # 计算结果就会变成 len([0, 15, 0]) > len([0, 15]) # 但 0.15.0 和 0.15 实际上是一样的版本 # if len(v1.release) != len(v2.release): # return len(v1.release) - len(v2.release) # 比较 pre-release if v1.pre_l and not v2.pre_l: return -1 # pre-release 小于正常版本 elif not v1.pre_l and v2.pre_l: return 1 elif v1.pre_l and v2.pre_l: pre_order = { ```"a```": 0, ```"b```": 1, ```"c```": 2, ```"rc```": 3, ```"alpha```": 0, ```"beta```": 1, ```"pre```": 0, ```"preview```": 0, } if pre_order[v1.pre_l] != pre_order[v2.pre_l]: return pre_order[v1.pre_l] - pre_order[v2.pre_l] elif v1.pre_n is not None and v2.pre_n is not None: return v1.pre_n - v2.pre_n elif v1.pre_n is None and v2.pre_n is not None: return -1 elif v1.pre_n is not None and v2.pre_n is None: return 1 # 比较 post-release if v1.post_n1 is not None: post_n1 = v1.post_n1 elif v1.post_l: post_n1 = int(v1.post_n2) if v1.post_n2 else 0 else: post_n1 = 0 if v2.post_n1 is not None: post_n2 = v2.post_n1 elif v2.post_l: post_n2 = int(v2.post_n2) if v2.post_n2 else 0 else: post_n2 = 0 if post_n1 != post_n2: return post_n1 - post_n2 # 比较 dev-release if v1.dev_l and not v2.dev_l: return -1 # dev-release 小于 post-release 或正常版本 elif not v1.dev_l and v2.dev_l: return 1 elif v1.dev_l and v2.dev_l: if v1.dev_n is not None and v2.dev_n is not None: return v1.dev_n - v2.dev_n elif v1.dev_n is None and v2.dev_n is not None: return -1 elif v1.dev_n is not None and v2.dev_n is None: return 1 # 比较 local version if v1.local and not v2.local: return -1 # local version 小于 dev-release 或正常版本 elif not v1.local and v2.local: return 1 elif v1.local and v2.local: local1 = v1.local.split(```".```") local2 = v2.local.split(```".```") # 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0 if len(local1) != len(local2): for _ in range(abs(len(local1) - len(local2))): if len(local1) < len(local2): local1.append(0) else: local2.append(0) for l1, l2 in zip(local1, local2): if l1.isdigit() and l2.isdigit(): l1, l2 = int(l1), int(l2) if l1 != l2: return (l1 > l2) - (l1 < l2) return len(local1) - len(local2) return 0 # 版本相同 def compare_versions(self, version1: str, version2: str) -> int: ```"```"```"比较两个版本字符串 Python 软件包版本号 Args: version1 (str): 版本号 1 version2 (str): 版本号 2 Returns: int: 如果版本号 1 大于 版本号 2, 则返回````1````, 小于则返回````-1````, 如果相等则返回````0```` ```"```"```" v1 = self.parse_version(version1) v2 = self.parse_version(version2) return self.compare_version_objects(v1, v2) def compatible_version_matcher(self, spec_version: str) -> Callable[[str], bool]: ```"```"```"PEP 440 兼容性版本匹配 (~= 操作符) Returns: (Callable[[str], bool]): 一个接受 version_str (````str````) 参数的判断函数 ```"```"```" # 解析规范版本 spec = self.parse_version(spec_version) # 获取有效 release 段 (去除末尾的零) clean_release = [] for num in spec.release: if num != 0 or (clean_release and clean_release[-1] != 0): clean_release.append(num) # 确定最低版本和前缀匹配规则 if len(clean_release) == 0: logger.debug(```"解析到错误的兼容性发行版本号```") raise ValueError(```"解析到错误的兼容性发行版本号```") # 生成前缀匹配模板 (忽略后缀) prefix_length = len(clean_release) - 1 if prefix_length == 0: # 处理类似 ~= 2 的情况 (实际 PEP 禁止, 但这里做容错) prefix_pattern = [spec.release[0]] min_version = self.parse_version(f```"{spec.release[0]}```") else: prefix_pattern = list(spec.release[:prefix_length]) min_version = spec def _is_compatible(version_str: str) -> bool: target = self.parse_version(version_str) # 主版本前缀检查 target_prefix = target.release[: len(prefix_pattern)] if target_prefix != prefix_pattern: return False # 最低版本检查 (自动忽略 pre/post/dev 后缀) return self.compare_version_objects(target, min_version) >= 0 return _is_compatible def version_match(self, spec: str, version: str) -> bool: ```"```"```"PEP 440 版本前缀匹配 Args: spec (str): 版本匹配表达式 (e.g. '1.1.*') version (str): 需要检测的实际版本号 (e.g. '1.1a1') Returns: bool: 是否匹配 ```"```"```" # 分离通配符和本地版本 spec_parts = spec.split(```"+```", 1) spec_main = spec_parts[0].rstrip(```".*```") # 移除通配符 has_wildcard = spec.endswith(```".*```") and ```"+```" not in spec # 解析规范版本 (不带通配符) try: spec_ver = self.parse_version(spec_main) except ValueError: return False # 解析目标版本 (忽略本地版本) target_ver = self.parse_version(version.split(```"+```", 1)[0]) # 前缀匹配规则 if has_wildcard: # 生成补零后的 release 段 spec_release = spec_ver.release.copy() while len(spec_release) < len(target_ver.release): spec_release.append(0) # 比较前 N 个 release 段 (N 为规范版本长度) return ( target_ver.release[: len(spec_ver.release)] == spec_ver.release and target_ver.epoch == spec_ver.epoch ) else: # 严格匹配时使用原比较函数 return self.compare_versions(spec_main, version) == 0 def is_v1_ge_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于或等于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> True 0.9, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) >= 0 def is_v1_gt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于 v2 例如: ```````````` 1.1, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号大于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) > 0 def is_v1_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否等于 v2 例如: ```````````` 1.0, 1.0 -> True 0.9, 1.0 -> False 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: ````bool````: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) == 0 def is_v1_lt_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) < 0 def is_v1_le_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否小于或等于 v2 例如: ```````````` 0.9, 1.0 -> True 1.0, 1.0 -> True 1.1, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号小于或等于 v2 版本号则返回````True```` ```"```"```" return self.compare_versions(v1, v2) <= 0 def is_v1_c_eq_v2(self, v1: str, v2: str) -> bool: ```"```"```"查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配) 例如: ```````````` 1.0*, 1.0a1 -> True 0.9*, 1.0 -> False ```````````` Args: v1 (str): 第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定 v2 (str): 第 2 个 Python 软件包版本号 Returns: bool: 如果 v1 版本号等于 v2 版本号则返回````True```` ```"```"```" func = self.compatible_version_matcher(v1) return func(v2) class PyWhlVersionMatcher: ```"```"```"Python 兼容性版本匹配器, 用于实现 ~= 操作符的语义 Attributes: spec_version (str): 版本号 comparison (PyWhlVersionComparison): Python 版本号比较工具 _matcher_func (Callable[[str], bool]): 兼容性版本匹配函数 ```"```"```" def __init__(self, spec_version: str) -> None: ```"```"```"初始化 Python 兼容性版本匹配器 Args: spec_version (str): 版本号 ```"```"```" self.spec_version = spec_version self.comparison = PyWhlVersionComparison(spec_version) self._matcher_func = self.comparison.compatible_version_matcher(spec_version) def __eq__(self, other: object) -> bool: ```"```"```"实现 ~version == other_version 的语义 Args: other (object): 用于比较的对象 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if isinstance(other, str): return self._matcher_func(other) elif isinstance(other, PyWhlVersionComparison): return self._matcher_func(other.version) elif isinstance(other, PyWhlVersionMatcher): # 允许 ~v1 == ~v2 的比较 (比较规范版本) return self.spec_version == other.spec_version return NotImplemented def __repr__(self) -> str: return f```"~{self.spec_version}```" class ParsedPyWhlRequirement(NamedTuple): ```"```"```"解析后的依赖声明信息 参考: https://peps.python.org/pep-0508 ```"```"```" name: str ```"```"```"软件包名称```"```"```" extras: list[str] ```"```"```"extras 列表,例如 ['fred', 'bar']```"```"```" specifier: list[tuple[str, str]] | str ```"```"```"版本约束列表或 URL 地址 如果是版本依赖,则为版本约束列表,例如 [('>=', '1.0'), ('<', '2.0')] 如果是 URL 依赖,则为 URL 字符串,例如 'http://example.com/package.tar.gz' ```"```"```" marker: Any ```"```"```"环境标记表达式,用于条件依赖```"```"```" class Parser: ```"```"```"语法解析器 Attributes: text (str): 待解析的字符串 pos (int): 字符起始位置 len (int): 字符串长度 ```"```"```" def __init__(self, text: str) -> None: ```"```"```"初始化解析器 Args: text (str): 要解析的文本 ```"```"```" self.text = text self.pos = 0 self.len = len(text) def peek(self) -> str: ```"```"```"查看当前位置的字符但不移动指针 Returns: str: 当前位置的字符,如果到达末尾则返回空字符串 ```"```"```" if self.pos < self.len: return self.text[self.pos] return ```"```" def consume(self, expected: str | None = None) -> str: ```"```"```"消耗当前字符并移动指针 Args: expected (str | None): 期望的字符,如果提供但不匹配会抛出异常 Returns: str: 实际消耗的字符 Raises: ValueError: 当字符不匹配或到达文本末尾时 ```"```"```" if self.pos >= self.len: raise ValueError(f```"不期望的输入内容结尾, 期望: {expected}```") char = self.text[self.pos] if expected and char != expected: raise ValueError(f```"期望 '{expected}', 得到 '{char}' 在位置 {self.pos}```") self.pos += 1 return char def skip_whitespace(self): ```"```"```"跳过空白字符(空格和制表符)```"```"```" while self.pos < self.len and self.text[self.pos] in ```" \t```": self.pos += 1 def match(self, pattern: str) -> str | None: ```"```"```"尝试匹配指定模式, 成功则移动指针 Args: pattern (str): 要匹配的模式字符串 Returns: (str | None): 匹配成功的字符串, 否则为 None ```"```"```" # 跳过空格再匹配 original_pos = self.pos self.skip_whitespace() if self.text.startswith(pattern, self.pos): result = self.text[self.pos : self.pos + len(pattern)] self.pos += len(pattern) return result # 如果没有匹配,恢复位置 self.pos = original_pos return None def read_while(self, condition) -> str: ```"```"```"读取满足条件的字符序列 Args: condition: 判断字符是否满足条件的函数 Returns: str: 满足条件的字符序列 ```"```"```" start = self.pos while self.pos < self.len and condition(self.text[self.pos]): self.pos += 1 return self.text[start : self.pos] def eof(self) -> bool: ```"```"```"检查是否到达文本末尾 Returns: bool: 如果到达末尾返回 True, 否则返回 False ```"```"```" return self.pos >= self.len class RequirementParser(Parser): ```"```"```"Python 软件包解析工具 Attributes: bindings (dict[str, str] | None): 解析语法 ```"```"```" def __init__(self, text: str, bindings: dict[str, str] | None = None): ```"```"```"初始化依赖声明解析器 Args: text (str): 覫解析的依赖声明文本 bindings (dict[str, str] | None): 环境变量绑定字典 ```"```"```" super().__init__(text) self.bindings = bindings or {} def parse(self) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明,返回 (name, extras, version_specs / url, marker) Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" self.skip_whitespace() # 首先解析名称 name = self.parse_identifier() self.skip_whitespace() # 解析 extras extras = [] if self.peek() == ```"[```": extras = self.parse_extras() self.skip_whitespace() # 检查是 URL 依赖还是版本依赖 if self.peek() == ```"@```": # URL依赖 self.consume(```"@```") self.skip_whitespace() url = self.parse_url() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, url, marker) else: # 版本依赖 versions = [] # 检查是否有版本约束 (不是以分号开头) if not self.eof() and self.peek() not in (```";```", ```",```"): versions = self.parse_versionspec() self.skip_whitespace() # 解析可选的 marker marker = None if self.match(```";```"): marker = self.parse_marker() return ParsedPyWhlRequirement(name, extras, versions, marker) def parse_identifier(self) -> str: ```"```"```"解析标识符 Returns: str: 解析得到的标识符 ```"```"```" def is_identifier_char(c): return c.isalnum() or c in ```"-_.```" result = self.read_while(is_identifier_char) if not result: raise ValueError(```"应为预期标识符```") return result def parse_extras(self) -> list[str]: ```"```"```"解析 extras 列表 Returns: list[str]: extras 列表 ```"```"```" self.consume(```"[```") self.skip_whitespace() extras = [] if self.peek() != ```"]```": extras.append(self.parse_identifier()) self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() extras.append(self.parse_identifier()) self.skip_whitespace() self.consume(```"]```") return extras def parse_versionspec(self) -> list[tuple[str, str]]: ```"```"```"解析版本约束 Returns: list[tuple[str, str]]: 版本约束列表 ```"```"```" if self.match(```"(```"): versions = self.parse_version_many() self.consume(```")```") return versions else: return self.parse_version_many() def parse_version_many(self) -> list[tuple[str, str]]: ```"```"```"解析多个版本约束 Returns: list[tuple[str, str]]: 多个版本约束组成的列表 ```"```"```" versions = [self.parse_version_one()] self.skip_whitespace() while self.match(```",```"): self.skip_whitespace() versions.append(self.parse_version_one()) self.skip_whitespace() return versions def parse_version_one(self) -> tuple[str, str]: ```"```"```"解析单个版本约束 Returns: tuple[str, str]: (操作符, 版本号) 元组 ```"```"```" op = self.parse_version_cmp() self.skip_whitespace() version = self.parse_version() return (op, version) def parse_version_cmp(self) -> str: ```"```"```"解析版本比较操作符 Returns: str: 版本比较操作符 Raises: ValueError: 当找不到有效的版本比较操作符时 ```"```"```" operators = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in operators: if self.match(op): return op raise ValueError(f```"预期在位置 {self.pos} 处出现版本比较符```") def parse_version(self) -> str: ```"```"```"解析版本号 Returns: str: 版本号字符串 Raises: ValueError: 当找不到有效版本号时 ```"```"```" def is_version_char(c): return c.isalnum() or c in ```"-_.*+!```" version = self.read_while(is_version_char) if not version: raise ValueError(```"期望为版本字符串```") return version def parse_url(self) -> str: ```"```"```"解析 URL (简化版本) Returns: str: URL 字符串 Raises: ValueError: 当找不到有效 URL 时 ```"```"```" # 读取直到遇到空白或分号 start = self.pos while self.pos < self.len and self.text[self.pos] not in ```" \t;```": self.pos += 1 url = self.text[start : self.pos] if not url: raise ValueError(```"@ 后的预期 URL```") return url def parse_marker(self) -> Any: ```"```"```"解析 marker 表达式 Returns: Any: 解析后的 marker 表达式 ```"```"```" self.skip_whitespace() return self.parse_marker_or() def parse_marker_or(self) -> Any: ```"```"```"解析 OR 表达式 Returns: Any: 解析后的 OR 表达式 ```"```"```" left = self.parse_marker_and() self.skip_whitespace() if self.match(```"or```"): self.skip_whitespace() right = self.parse_marker_or() return (```"or```", left, right) return left def parse_marker_and(self) -> Any: ```"```"```"解析 AND 表达式 Returns: Any: 解析后的 AND 表达式 ```"```"```" left = self.parse_marker_expr() self.skip_whitespace() if self.match(```"and```"): self.skip_whitespace() right = self.parse_marker_and() return (```"and```", left, right) return left def parse_marker_expr(self) -> Any: ```"```"```"解析基础 marker 表达式 Returns: Any: 解析后的基础表达式 ```"```"```" self.skip_whitespace() if self.peek() == ```"(```": self.consume(```"(```") expr = self.parse_marker() self.consume(```")```") return expr left = self.parse_marker_var() self.skip_whitespace() op = self.parse_marker_op() self.skip_whitespace() right = self.parse_marker_var() return (op, left, right) def parse_marker_var(self) -> str: ```"```"```"解析 marker 变量 Returns: str: 解析得到的变量值 ```"```"```" self.skip_whitespace() # 检查是否是环境变量 env_vars = [ ```"python_version```", ```"python_full_version```", ```"os_name```", ```"sys_platform```", ```"platform_release```", ```"platform_system```", ```"platform_version```", ```"platform_machine```", ```"platform_python_implementation```", ```"implementation_name```", ```"implementation_version```", ```"extra```", ] for var in env_vars: if self.match(var): # 返回绑定的值,如果不存在则返回变量名 return self.bindings.get(var, var) # 否则解析为字符串 return self.parse_python_str() def parse_marker_op(self) -> str: ```"```"```"解析 marker 操作符 Returns: str: marker 操作符 Raises: ValueError: 当找不到有效操作符时 ```"```"```" # 版本比较操作符 version_ops = [```"<=```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```", ```"<```", ```">```"] for op in version_ops: if self.match(op): return op # in 操作符 if self.match(```"in```"): return ```"in```" # not in 操作符 if self.match(```"not```"): self.skip_whitespace() if self.match(```"in```"): return ```"not in```" raise ValueError(```"预期在 'not' 之后出现 'in'```") raise ValueError(f```"在位置 {self.pos} 处应出现标记运算符```") def parse_python_str(self) -> str: ```"```"```"解析 Python 字符串 Returns: str: 解析得到的字符串 ```"```"```" self.skip_whitespace() if self.peek() == '```"': return self.parse_quoted_string('```"') elif self.peek() == ```"'```": return self.parse_quoted_string(```"'```") else: # 如果没有引号,读取标识符 return self.parse_identifier() def parse_quoted_string(self, quote: str) -> str: ```"```"```"解析引号字符串 Args: quote (str): 引号字符 Returns: str: 解析得到的字符串 Raises: ValueError: 当字符串未正确闭合时 ```"```"```" self.consume(quote) result = [] while self.pos < self.len and self.text[self.pos] != quote: if self.text[self.pos] == ```"\\```": # 处理转义 self.pos += 1 if self.pos < self.len: result.append(self.text[self.pos]) self.pos += 1 else: result.append(self.text[self.pos]) self.pos += 1 if self.pos >= self.len: raise ValueError(f```"未闭合的字符串字面量,预期为 '{quote}'```") self.consume(quote) return ```"```".join(result) def format_full_version(info: str) -> str: ```"```"```"格式化完整的版本信息 Args: info (str): 版本信息 Returns: str: 格式化后的版本字符串 ```"```"```" version = f```"{info.major}.{info.minor}.{info.micro}```" kind = info.releaselevel if kind != ```"final```": version += kind[0] + str(info.serial) return version def get_parse_bindings() -> dict[str, str]: ```"```"```"获取用于解析 Python 软件包名的语法 Returns: (dict[str, str]): 解析 Python 软件包名的语法字典 ```"```"```" # 创建环境变量绑定 if hasattr(sys, ```"implementation```"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = ```"0```" implementation_name = ```"```" bindings = { ```"implementation_name```": implementation_name, ```"implementation_version```": implementation_version, ```"os_name```": os.name, ```"platform_machine```": platform.machine(), ```"platform_python_implementation```": platform.python_implementation(), ```"platform_release```": platform.release(), ```"platform_system```": platform.system(), ```"platform_version```": platform.version(), ```"python_full_version```": platform.python_version(), ```"python_version```": ```".```".join(platform.python_version_tuple()[:2]), ```"sys_platform```": sys.platform, } return bindings def version_string_is_canonical(version: str) -> bool: ```"```"```"判断版本号标识符是否符合标准 Args: version (str): 版本号字符串 Returns: bool: 如果版本号标识符符合 PEP 440 标准, 则返回````True```` ```"```"```" return ( re.match( r```"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$```", version, ) is not None ) def is_package_has_version(package: str) -> bool: ```"```"```"检查 Python 软件包是否指定版本号 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包存在版本声明, 如````torch==2.3.0````, 则返回````True```` ```"```"```" return package != ( package.replace(```"===```", ```"```") .replace(```"~=```", ```"```") .replace(```"!=```", ```"```") .replace(```"<=```", ```"```") .replace(```">=```", ```"```") .replace(```"<```", ```"```") .replace(```">```", ```"```") .replace(```"==```", ```"```") ) def get_package_name(package: str) -> str: ```"```"```"获取 Python 软件包的包名, 去除末尾的版本声明 Args: package (str): Python 软件包名 Returns: str: 返回去除版本声明后的 Python 软件包名 ```"```"```" return ( package.split(```"===```")[0] .split(```"~=```")[0] .split(```"!=```")[0] .split(```"<=```")[0] .split(```">=```")[0] .split(```"<```")[0] .split(```">```")[0] .split(```"==```")[0] .strip() ) def get_package_version(package: str) -> str: ```"```"```"获取 Python 软件包的包版本号 Args: package (str): Python 软件包名 返回值: str: 返回 Python 软件包的包版本号 ```"```"```" return ( package.split(```"===```") .pop() .split(```"~=```") .pop() .split(```"!=```") .pop() .split(```"<=```") .pop() .split(```">=```") .pop() .split(```"<```") .pop() .split(```">```") .pop() .split(```"==```") .pop() .strip() ) WHEEL_PATTERN = r```"```"```" ^ # 字符串开始 (?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段) - # 分隔符 (?: # 版本号和可选构建号组合 (?P<version>[^-]+) # 版本号 (至少一个非连字符段) (?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头) ) - # 分隔符 (?P<python>[^-]+) # Python 版本标签 - # 分隔符 (?P<abi>[^-]+) # ABI 标签 - # 分隔符 (?P<platform>[^-]+) # 平台标签 \.whl$ # 固定后缀 ```"```"```" ```"```"```"解析 Python Wheel 名的的正则表达式```"```"```" REPLACE_PACKAGE_NAME_DICT = { ```"sam2```": ```"SAM-2```", } ```"```"```"Python 软件包名替换表```"```"```" def parse_wheel_filename(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 distribution 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: distribution 名称, 例如 pydantic Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"distribution```") def parse_wheel_version(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 version 名称 Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: version 名称, 例如 1.10.15 Raises: ValueError: 如果文件名不符合 PEP491 规范 ```"```"```" match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE) if not match: logger.debug(```"未知的 Wheel 文件名: %s```", filename) raise ValueError(f```"未知的 Wheel 文件名: {filename}```") return match.group(```"version```") def parse_wheel_to_package_name(filename: str) -> str: ```"```"```"解析 Python wheel 文件名并返回 <distribution>==<version> Args: filename (str): wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl Returns: str: <distribution>==<version> 名称, 例如 pydantic==1.10.15 ```"```"```" distribution = parse_wheel_filename(filename) version = parse_wheel_version(filename) return f```"{distribution}=={version}```" def remove_optional_dependence_from_package(filename: str) -> str: ```"```"```"移除 Python 软件包声明中可选依赖 Args: filename (str): Python 软件包名 Returns: str: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2 ```"```"```" return re.sub(r```"\[.*?\]```", ```"```", filename) def get_correct_package_name(name: str) -> str: ```"```"```"将原 Python 软件包名替换成正确的 Python 软件包名 Args: name (str): 原 Python 软件包名 Returns: str: 替换成正确的软件包名, 如果原有包名正确则返回原包名 ```"```"```" return REPLACE_PACKAGE_NAME_DICT.get(name, name) def parse_requirement( text: str, bindings: dict[str, str], ) -> ParsedPyWhlRequirement: ```"```"```"解析依赖声明的主函数 Args: text (str): 依赖声明文本 bindings (dict[str, str]): 解析 Python 软件包名的语法字典 Returns: ParsedPyWhlRequirement: 解析结果元组 ```"```"```" parser = RequirementParser(text, bindings) return parser.parse() def evaluate_marker(marker: Any) -> bool: ```"```"```"评估 marker 表达式, 判断当前环境是否符合要求 Args: marker (Any): marker 表达式 Returns: bool: 评估结果 ```"```"```" if marker is None: return True if isinstance(marker, tuple): op = marker[0] if op in (```"and```", ```"or```"): left = evaluate_marker(marker[1]) right = evaluate_marker(marker[2]) if op == ```"and```": return left and right else: # 'or' return left or right else: # 处理比较操作 left = marker[1] right = marker[2] if op in [```"<```", ```"<=```", ```">```", ```">=```", ```"==```", ```"!=```", ```"~=```", ```"===```"]: try: left_ver = PyWhlVersionComparison(str(left).lower()) right_ver = PyWhlVersionComparison(str(right).lower()) if op == ```"<```": return left_ver < right_ver elif op == ```"<=```": return left_ver <= right_ver elif op == ```">```": return left_ver > right_ver elif op == ```">=```": return left_ver >= right_ver elif op == ```"==```": return left_ver == right_ver elif op == ```"!=```": return left_ver != right_ver elif op == ```"~=```": return left_ver >= ~right_ver elif op == ```"===```": # 任意相等, 直接比较字符串 return str(left).lower() == str(right).lower() except Exception: # 如果版本比较失败, 回退到字符串比较 left_str = str(left).lower() right_str = str(right).lower() if op == ```"<```": return left_str < right_str elif op == ```"<=```": return left_str <= right_str elif op == ```">```": return left_str > right_str elif op == ```">=```": return left_str >= right_str elif op == ```"==```": return left_str == right_str elif op == ```"!=```": return left_str != right_str elif op == ```"~=```": # 简化处理 return left_str >= right_str elif op == ```"===```": return left_str == right_str # 处理 in 和 not in 操作 elif op == ```"in```": # 将右边按逗号分割, 检查左边是否在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() in values elif op == ```"not in```": # 将右边按逗号分割, 检查左边是否不在其中 values = [v.strip() for v in str(right).lower().split(```",```")] return str(left).lower() not in values return False def parse_requirement_to_list(text: str) -> list[str]: ```"```"```"解析依赖声明并返回依赖列表 Args: text (str): 依赖声明 Returns: list[str]: 解析后的依赖声明表 ```"```"```" try: bindings = get_parse_bindings() name, _, version_specs, marker = parse_requirement(text, bindings) except Exception as e: logger.debug(```"解析失败: %s```", e) return [] # 检查marker条件 if not evaluate_marker(marker): return [] # 构建依赖列表 dependencies = [] # 如果是 URL 依赖 if isinstance(version_specs, str): # URL 依赖只返回包名 dependencies.append(name) else: # 版本依赖 if version_specs: # 有版本约束, 为每个约束创建一个依赖项 for op, version in version_specs: dependencies.append(f```"{name}{op}{version}```") else: # 没有版本约束, 只返回包名 dependencies.append(name) return dependencies def parse_requirement_list(requirements: list[str]) -> list[str]: ```"```"```"将 Python 软件包声明列表解析成标准 Python 软件包名列表 例如有以下的 Python 软件包声明列表: ````````````python requirements = [ 'torch==2.3.0', 'diffusers[torch]==0.10.2', 'NUMPY', '-e .', '--index-url https://pypi.python.org/simple', '--extra-index-url https://download.pytorch.org/whl/cu124', '--find-links https://download.pytorch.org/whl/torch_stable.html', '-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds', 'git+https://github.com/WASasquatch/img2texture.git', 'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl', 'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer', 'protobuf<5,>=4.25.3', ] ```````````` 上述例子中的软件包名声明列表将解析成: ````````````python requirements = [ 'torch==2.3.0', 'diffusers==0.10.2', 'numpy', 'mgds', 'img2texture', 'pydantic==1.10.15', 'prodigy-plus-schedule-free==1.9.1', 'protobuf<5', 'protobuf>=4.25.3', ] ```````````` Args: requirements (list[str]): Python 软件包名声明列表 Returns: list[str]: 将 Python 软件包名声明列表解析成标准声明列表 ```"```"```" def _extract_repo_name(url_string: str) -> str | None: ```"```"```"从包含 Git 仓库 URL 的字符串中提取仓库名称 Args: url_string (str): 包含 Git 仓库 URL 的字符串 Returns: (str | None): 提取到的仓库名称, 如果未找到则返回 None ```"```"```" # 模式1: 匹配 git+https:// 或 git+ssh:// 开头的 URL # 模式2: 匹配直接以 git+ 开头的 URL patterns = [ # 匹配 git+protocol://host/path/to/repo.git 格式 r```"git\+[a-z]+://[^/]+/(?:[^/]+/)*([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+https://host/owner/repo.git 格式 r```"git\+https://[^/]+/[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 匹配 git+ssh://git@host:owner/repo.git 格式 r```"git\+ssh://git@[^:]+:[^/]+/([^/@]+?)(?:\.git)?(?:@|$)```", # 通用模式: 匹配最后一个斜杠后的内容, 直到遇到 @ 或 .git 或字符串结束 r```"/([^/@]+?)(?:\.git)?(?:@|$)```", ] for pattern in patterns: match = re.search(pattern, url_string) if match: return match.group(1) return None package_list: list[str] = [] canonical_package_list: list[str] = [] for requirement in requirements: # 清理注释内容 # prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1 requirement = re.sub(r```"\s*#.*$```", ```"```", requirement).strip() logger.debug(```"原始 Python 软件包名: %s```", requirement) if ( requirement is None or requirement == ```"```" or requirement.startswith(```"#```") or ```"# skip_verify```" in requirement or requirement.startswith(```"--index-url```") or requirement.startswith(```"--extra-index-url```") or requirement.startswith(```"--find-links```") or requirement.startswith(```"-e .```") or requirement.startswith(```"-r ```") ): continue # -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds # git+https://github.com/WASasquatch/img2texture.git -> img2texture # git+https://github.com/deepghs/waifuc -> waifuc # -e git+https://github.com/Nerogar/mgds.git@2c67a5a -> mgds # git+ssh://git@github.com:licyk/sd-webui-all-in-one@dev -> sd-webui-all-in-one # git+https://gitlab.com/user/my-project.git@main -> my-project # git+ssh://git@bitbucket.org:team/repo-name.git@develop -> repo-name # https://github.com/another/repo.git -> repo # git@github.com:user/repository.git -> repository if ( requirement.startswith(```"-e git+http```") or requirement.startswith(```"git+http```") or requirement.startswith(```"-e git+ssh://```") or requirement.startswith(```"git+ssh://```") ): egg_match = re.search(r```"egg=([^#&]+)```", requirement) if egg_match: package_list.append(egg_match.group(1).split(```"-```")[0]) continue repo_name_match = _extract_repo_name(requirement) if repo_name_match is not None: package_list.append(repo_name_match) continue package_name = os.path.basename(requirement) package_name = ( package_name.split(```".git```")[0] if package_name.endswith(```".git```") else package_name ) package_list.append(package_name) continue # https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15 if requirement.startswith(```"https://```") or requirement.startswith(```"http://```"): package_name = parse_wheel_to_package_name(os.path.basename(requirement)) package_list.append(package_name) continue # 常规 Python 软件包声明 # 解析版本列表 possble_requirement = parse_requirement_to_list(requirement) if len(possble_requirement) == 0: continue elif len(possble_requirement) == 1: requirement = possble_requirement[0] else: requirements_list = parse_requirement_list(possble_requirement) package_list += requirements_list continue multi_requirements = requirement.split(```",```") if len(multi_requirements) > 1: package_name = get_package_name(multi_requirements[0].strip()) for package_name_with_version_marked in multi_requirements: version_symbol = str.replace( package_name_with_version_marked, package_name, ```"```", 1 ) format_package_name = remove_optional_dependence_from_package( f```"{package_name}{version_symbol}```".strip() ) package_list.append(format_package_name) else: format_package_name = remove_optional_dependence_from_package( multi_requirements[0].strip() ) package_list.append(format_package_name) # 处理包名大小写并统一成小写 for p in package_list: p = p.lower().strip() logger.debug(```"预处理后的 Python 软件包名: %s```", p) if not is_package_has_version(p): logger.debug(```"%s 无版本声明```", p) new_p = get_correct_package_name(p) logger.debug(```"包名处理: %s -> %s```", p, new_p) canonical_package_list.append(new_p) continue if version_string_is_canonical(get_package_version(p)): canonical_package_list.append(p) else: logger.debug(```"%s 软件包名的版本不符合标准```", p) return canonical_package_list def read_packages_from_requirements_file(file_path: str | Path) -> list[str]: ```"```"```"从 requirements.txt 文件中读取 Python 软件包版本声明列表 Args: file_path (str | Path): requirements.txt 文件路径 Returns: list[str]: 从 requirements.txt 文件中读取的 Python 软件包声明列表 ```"```"```" try: with open(file_path, ```"r```", encoding=```"utf-8```") as f: return f.readlines() except Exception as e: logger.debug(```"打开 %s 时出现错误: %s\n请检查文件是否出现损坏```", file_path, e) return [] def get_package_version_from_library(package_name: str) -> str | None: ```"```"```"获取已安装的 Python 软件包版本号 Args: package_name (str): Python 软件包名 Returns: (str | None): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回````None```` ```"```"```" try: ver = importlib.metadata.version(package_name) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.lower()) except Exception as _: ver = None if ver is None: try: ver = importlib.metadata.version(package_name.replace(```"_```", ```"-```")) except Exception as _: ver = None return ver def is_package_installed(package: str) -> bool: ```"```"```"判断 Python 软件包是否已安装在环境中 Args: package (str): Python 软件包名 Returns: bool: 如果 Python 软件包未安装或者未安装正确的版本, 则返回````False```` ```"```"```" # 分割 Python 软件包名和版本号 if ```"===```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"===```")] elif ```"~=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"~=```")] elif ```"!=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"!=```")] elif ```"<=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<=```")] elif ```">=```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">=```")] elif ```"<```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"<```")] elif ```">```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```">```")] elif ```"==```" in package: pkg_name, pkg_version = [x.strip() for x in package.split(```"==```")] else: pkg_name, pkg_version = package.strip(), None env_pkg_version = get_package_version_from_library(pkg_name) logger.debug( ```"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s```", pkg_name, env_pkg_version, pkg_version, ) if env_pkg_version is None: return False if pkg_version is not None: # ok = env_pkg_version === / == pkg_version if ```"===```" in package or ```"==```" in package: logger.debug(```"包含条件: === / ==```") logger.debug(```"%s == %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version ~= pkg_version if ```"~=```" in package: logger.debug(```"包含条件: ~=```") logger.debug(```"%s ~= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) == ~PyWhlVersionComparison( pkg_version ): logger.debug(```"%s == %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version != pkg_version if ```"!=```" in package: logger.debug(```"包含条件: !=```") logger.debug(```"%s != %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) != PyWhlVersionComparison( pkg_version ): logger.debug(```"%s != %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version <= pkg_version if ```"<=```" in package: logger.debug(```"包含条件: <=```") logger.debug(```"%s <= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) <= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s <= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version >= pkg_version if ```">=```" in package: logger.debug(```"包含条件: >=```") logger.debug(```"%s >= %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) >= PyWhlVersionComparison( pkg_version ): logger.debug(```"%s >= %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version < pkg_version if ```"<```" in package: logger.debug(```"包含条件: <```") logger.debug(```"%s < %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) < PyWhlVersionComparison( pkg_version ): logger.debug(```"%s < %s 条件成立```", env_pkg_version, pkg_version) return True # ok = env_pkg_version > pkg_version if ```">```" in package: logger.debug(```"包含条件: >```") logger.debug(```"%s > %s ?```", env_pkg_version, pkg_version) if PyWhlVersionComparison(env_pkg_version) > PyWhlVersionComparison( pkg_version ): logger.debug(```"%s > %s 条件成立```", env_pkg_version, pkg_version) return True logger.debug(```"%s 需要安装```", package) return False return True def validate_requirements(requirement_path: str | Path) -> bool: ```"```"```"检测环境依赖是否完整 Args: requirement_path (str | Path): 依赖文件路径 Returns: bool: 如果有缺失依赖则返回````False```` ```"```"```" origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) for package in requires: if not is_package_installed(package): return False return True def main() -> None: requirement_path = COMMAND_ARGS.requirement_path if not os.path.isfile(requirement_path): logger.error(```"依赖文件未找到, 无法检查运行环境```") sys.exit(1) logger.debug(```"检测运行环境中```") print(validate_requirements(requirement_path)) logger.debug(```"环境检查完成```") if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 Stable Diffusion WebUI 内核依赖完整性中`" if (!(Test-Path `"`$Env:CACHE_HOME`")) { New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" > `$null } Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/check_stable_diffusion_webui_requirement.py`" -Value `$content `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements_versions.txt`" if (!(Test-Path `"`$dep_path`")) { `$dep_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/requirements.txt`" } if (!(Test-Path `"`$dep_path`")) { Print-Msg `"未检测到 Stable Diffusion WebUI 依赖文件, 跳过依赖完整性检查`" return } `$status = `$(python `"`$Env:CACHE_HOME/check_stable_diffusion_webui_requirement.py`" --requirement-path `"`$dep_path`") if (`$status -eq `"False`") { Print-Msg `"检测到 Stable Diffusion WebUI 内核有依赖缺失, 安装 Stable Diffusion WebUI 依赖中`" if (`$USE_UV) { uv pip install -r `"`$dep_path`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install -r `"`$dep_path`" } } else { python -m pip install -r `"`$dep_path`" } if (`$?) { Print-Msg `"Stable Diffusion WebUI 依赖安装成功`" } else { Print-Msg `"Stable Diffusion WebUI 依赖安装失败, 这将会导致 Stable Diffusion WebUI 缺失依赖无法正常运行`" } } else { Print-Msg `"Stable Diffusion WebUI 无缺失依赖`" } } # 检查插件是否被禁用 function Check-Extension-Is-Disabled (`$name) { `$sd_webui_config = `"`$PSScriptRoot/`$Env:CORE_PREFIX/config.json`" try { `$json_content = Get-Content -Path `$sd_webui_config -Raw | ConvertFrom-Json } catch { return `$false } if (`$json_content.PSObject.Properties[`"disable_all_extensions`"]) { if (`$json_content.disable_all_extensions -ne `"none`") { return `$true } else { if (`$json_content.disabled_extensions -contains `$name) { return `$true } else { return `$false } } } } # 检查 Stable Diffusion WebUI 环境中组件依赖 function Check-Stable-Diffusion-WebUI-Env-Requirements { `$current_python_path = `$Env:PYTHONPATH `$Env:PYTHONPATH = `"`$([System.IO.Path]::GetFullPath(`"`$PSScriptRoot/`$Env:CORE_PREFIX`"))`$([System.IO.Path]::PathSeparator)`$Env:PYTHONPATH`" Print-Msg `"检查 Stable Diffusion WebUI 扩展依赖中`" `$extension_list = Get-ChildItem -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/extensions`" | Select-Object -ExpandProperty FullName `$current_live_config = `$Env:WEBUI_LAUNCH_LIVE_OUTPUT `$Env:WEBUI_LAUNCH_LIVE_OUTPUT = 1 if (`$LaunchArg) { `$launch_args = `$LaunchArg } elseif (Test-Path `"`$PSScriptRoot/launch_args.txt`") { `$launch_args = Get-Content `"`$PSScriptRoot/launch_args.txt`" } else { `$launch_args = `"`" } `$sum = 0 ForEach (`$extension_path in `$extension_list) { if (Test-Path `"`$extension_path/install.py`") { `$sum += 1 } } `$count = 0 if ((`$launch_args -match `"--disable-extra-extensions`") -or (`$launch_args -match `"--disable-all-extensions`")) { `$extension_list = @() } ForEach (`$extension_path in `$extension_list) { if (!(Test-Path `"`$extension_path/install.py`")) { continue } `$count += 1 `$name = `$([System.IO.Path]::GetFileName(`$extension_path)) `$status = Check-Extension-Is-Disabled `$name if (`$status) { Print-Msg `"[`$count/`$sum] `$name 扩展已禁用, 不执行该扩展的依赖安装脚本`" } else { Print-Msg `"[`$count/`$sum] 执行 `$name 扩展的依赖安装脚本中`" python `"`$extension_path/install.py`" if (`$?) { Print-Msg `"[`$count/`$sum] 执行 `$name 扩展的依赖安装脚本成功`" } else { Print-Msg `"[`$count/`$sum] 执行 `$name 扩展的依赖安装脚本失败, 这可能会导致 `$name 扩展部分功能无法正常使用`" } } } Print-Msg `"Stable Diffusion WebUI 扩展依赖检查完成`" Print-Msg `"检查 Stable Diffusion WebUI 内置扩展依赖中`" `$extension_list = Get-ChildItem -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/extensions-builtin`" | Select-Object -ExpandProperty FullName `$sum = 0 ForEach (`$extension_path in `$extension_list) { if (Test-Path `"`$extension_path/install.py`") { `$sum += 1 } } `$count = 0 if (`$launch_args -match `"--disable-all-extensions`") { `$extension_list = @() } ForEach (`$extension_path in `$extension_list) { if (!(Test-Path `"`$extension_path/install.py`")) { continue } `$count += 1 `$name = `$([System.IO.Path]::GetFileName(`$extension_path)) `$status = Check-Extension-Is-Disabled `$name if (`$status) { Print-Msg `"[`$count/`$sum] `$name 内置扩展已禁用, 不执行该内置扩展的依赖安装脚本`" } else { Print-Msg `"[`$count/`$sum] 执行 `$name 内置扩展的依赖安装脚本中`" python `"`$extension_path/install.py`" if (`$?) { Print-Msg `"[`$count/`$sum] 执行 `$name 内置扩展的依赖安装脚本成功`" } else { Print-Msg `"[`$count/`$sum] 执行 `$name 内置扩展的依赖安装脚本失败, 这可能会导致 `$name 内置扩展部分功能无法正常使用`" } } } Print-Msg `"Stable Diffusion WebUI 内置扩展依赖检查完成`" `$Env:PYTHONPATH = `$current_python_path `$Env:WEBUI_LAUNCH_LIVE_OUTPUT = `$current_live_config } # 检查 onnxruntime-gpu 版本问题 function Check-Onnxruntime-GPU { `$content = `" import re import sys import argparse from enum import Enum from pathlib import Path import importlib.metadata def get_args() -> argparse.Namespace: ```"```"```"获取命令行参数 :return argparse.Namespace: 命令行参数命名空间 ```"```"```" parser = argparse.ArgumentParser() parser.add_argument( ```"--ignore-ort-install```", action=```"store_true```", help=```"忽略 onnxruntime-gpu 未安装的状态, 强制进行检查```", ) return parser.parse_args() class CommonVersionComparison: ```"```"```"常规版本号比较工具 使用: ````````````python CommonVersionComparison(```"1.0```") != CommonVersionComparison(```"1.0```") # False CommonVersionComparison(```"1.0.1```") > CommonVersionComparison(```"1.0```") # True CommonVersionComparison(```"1.0a```") < CommonVersionComparison(```"1.0```") # True ```````````` Attributes: version (str | int | float): 版本号字符串 ```"```"```" def __init__(self, version: str | int | float) -> None: ```"```"```"常规版本号比较工具初始化 Args: version (str | int | float): 版本号字符串 ```"```"```" self.version = version def __lt__(self, other: object) -> bool: ```"```"```"实现 < 符号的版本比较 Returns: bool: 如果此版本小于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) < 0 def __gt__(self, other: object) -> bool: ```"```"```"实现 > 符号的版本比较 Returns: bool: 如果此版本大于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) > 0 def __le__(self, other: object) -> bool: ```"```"```"实现 <= 符号的版本比较 Returns: bool: 如果此版本小于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) <= 0 def __ge__(self, other: object) -> bool: ```"```"```"实现 >= 符号的版本比较 Returns: bool: 如果此版本大于等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) >= 0 def __eq__(self, other: object) -> bool: ```"```"```"实现 == 符号的版本比较 Returns: bool: 如果此版本等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) == 0 def __ne__(self, other: object) -> bool: ```"```"```"实现 != 符号的版本比较 Returns: bool: 如果此版本不等于另一个版本 ```"```"```" if not isinstance(other, CommonVersionComparison): return NotImplemented return self.compare_versions(self.version, other.version) != 0 def compare_versions( self, version1: str | int | float, version2: str | int | float ) -> int: ```"```"```"对比两个版本号大小 Args: version1 (str | int | float): 第一个版本号 version2 (str | int | float): 第二个版本号 Returns: int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样 ```"```"```" version1 = str(version1) version2 = str(version2) # 移除构建元数据(+之后的部分) v1_main = version1.split(```"+```", maxsplit=1)[0] v2_main = version2.split(```"+```", maxsplit=1)[0] # 分离主版本号和预发布版本(支持多种分隔符) def _split_version(v): # 先尝试用 -, _, . 分割预发布版本 # 匹配主版本号部分和预发布部分 match = re.match(r```"^([0-9]+(?:\.[0-9]+)*)([-_.].*)?$```", v) if match: release = match.group(1) pre = match.group(2)[1:] if match.group(2) else ```"```" # 去掉分隔符 return release, pre return v, ```"```" v1_release, v1_pre = _split_version(v1_main) v2_release, v2_pre = _split_version(v2_main) # 将版本号拆分成数字列表 try: nums1 = [int(x) for x in v1_release.split(```".```") if x] nums2 = [int(x) for x in v2_release.split(```".```") if x] except Exception as _: return 0 # 补齐版本号长度 max_len = max(len(nums1), len(nums2)) nums1 += [0] * (max_len - len(nums1)) nums2 += [0] * (max_len - len(nums2)) # 比较版本号 for i in range(max_len): if nums1[i] > nums2[i]: return 1 elif nums1[i] < nums2[i]: return -1 # 如果主版本号相同, 比较预发布版本 if v1_pre and not v2_pre: return -1 # 预发布版本 < 正式版本 elif not v1_pre and v2_pre: return 1 # 正式版本 > 预发布版本 elif v1_pre and v2_pre: if v1_pre > v2_pre: return 1 elif v1_pre < v2_pre: return -1 else: return 0 else: return 0 # 版本号相同 class OrtType(str, Enum): ```"```"```"onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu ```"```"```" CU130 = ```"cu130```" CU121CUDNN8 = ```"cu121cudnn8```" CU121CUDNN9 = ```"cu121cudnn9```" CU118 = ```"cu118```" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: ```"```"```"获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 ```"```"```" package = ```"onnxruntime-gpu```" version_file = ```"onnxruntime/capi/version_info.py```" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][ 0 ] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: ```"```"```"获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 ```"```"```" ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, ```"r```", encoding=```"utf8```") as f: for line in f: if ```"cuda_version```" in line: cuda_ver = get_value_from_variable(line, ```"cuda_version```") if ```"cudnn_version```" in line: cudnn_ver = get_value_from_variable(line, ```"cudnn_version```") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: ```"```"```"从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 ```"```"```" pattern = rf'{var_name}\s*=\s*```"([^```"]+)```"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: ```"```"```"获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 ```"```"```" try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: ```"```"```"判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 ```"```"```" # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: if not ignore_ort_install: try: _ = importlib.metadata.version(```"onnxruntime-gpu```") except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU121CUDNN9 return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"13.0```" ): return OrtType.CU130 else: return None elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison(```"13.0```") ): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison( ort_support_cudnn_ver ) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison( ort_support_cudnn_ver ) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison( ```"12.0```" ): return None else: return OrtType.CU118 else: if ignore_ort_install: return None if sys.platform != ```"win32```": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 try: _ = importlib.metadata.version(```"onnxruntime-gpu```") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison(```"13.0```"): # CUDA >= 13.x return OrtType.CU130 elif ( CommonVersionComparison(```"12.0```") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison(```"13.0```") ): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison(```"8```"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def main() -> None: ```"```"```"主函数```"```"```" arg = get_args() # print(need_install_ort_ver(not arg.ignore_ort_install)) print(need_install_ort_ver()) if __name__ == ```"__main__```": main() `".Trim() Print-Msg `"检查 onnxruntime-gpu 版本问题中`" Set-Content -Encoding UTF8 -Path `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`" -Value `$content `$status = `$(python `"`$Env:CACHE_HOME/onnxruntime_gpu_check.py`") # TODO: 暂时屏蔽 CUDA 13.0 的处理 if (`$status -eq `"cu130`") { `$status = `"None`" } `$need_reinstall_ort = `$false `$need_switch_mirror = `$false switch (`$status) { # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 cu118 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.18.1`" } cu121cudnn9 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.19.0,<1.23.2`" } cu121cudnn8 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu==1.17.1`" `$need_switch_mirror = `$true } cu130 { `$need_reinstall_ort = `$true `$ort_version = `"onnxruntime-gpu>=1.23.2`" } Default { `$need_reinstall_ort = `$false } } if (`$need_reinstall_ort) { Print-Msg `"检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作`" if (`$need_switch_mirror) { `$tmp_pip_index_url = `$Env:PIP_INDEX_URL `$tmp_pip_extra_index_url = `$Env:PIP_EXTRA_INDEX_URL `$tmp_uv_index_url = `$Env:UV_DEFAULT_INDEX `$tmp_UV_extra_index_url = `$Env:UV_INDEX `$Env:PIP_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:PIP_EXTRA_INDEX_URL = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" `$Env:UV_DEFAULT_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`" `$Env:UV_INDEX = `"https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple`" } Print-Msg `"卸载原有的 onnxruntime-gpu 中`" python -m pip uninstall onnxruntime-gpu -y Print-Msg `"重新安装 onnxruntime-gpu 中`" if (`$USE_UV) { uv pip install `$ort_version if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$ort_version } } else { python -m pip install `$ort_version } if (`$?) { Print-Msg `"onnxruntime-gpu 重新安装成功`" } else { Print-Msg `"onnxruntime-gpu 重新安装失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速`" } if (`$need_switch_mirror) { `$Env:PIP_INDEX_URL = `$tmp_pip_index_url `$Env:PIP_EXTRA_INDEX_URL = `$tmp_pip_extra_index_url `$Env:UV_DEFAULT_INDEX = `$tmp_uv_index_url `$Env:UV_INDEX = `$tmp_UV_extra_index_url } } else { Print-Msg `"onnxruntime-gpu 无版本问题`" } } # 检查 Numpy 版本 function Check-Numpy-Version { `$content = `" import importlib.metadata from importlib.metadata import version try: ver = int(version('numpy').split('.')[0]) except: ver = -1 if ver > 1: print(True) else: print(False) `".Trim() Print-Msg `"检查 Numpy 版本中`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"检测到 Numpy 版本大于 1, 这可能导致部分组件出现异常, 尝试重装中`" if (`$USE_UV) { uv pip install `"numpy==1.26.4`" if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `"numpy==1.26.4`" } } else { python -m pip install `"numpy==1.26.4`" } if (`$?) { Print-Msg `"Numpy 重新安装成功`" } else { Print-Msg `"Numpy 重新安装失败, 这可能导致部分功能异常`" } } else { Print-Msg `"Numpy 无版本问题`" } } # 检测 Microsoft Visual C++ Redistributable function Check-MS-VCPP-Redistributable { Print-Msg `"检测 Microsoft Visual C++ Redistributable 是否缺失`" if ([string]::IsNullOrEmpty(`$Env:SYSTEMROOT)) { `$vc_runtime_dll_path = `"C:/Windows/System32/vcruntime140_1.dll`" } else { `$vc_runtime_dll_path = `"`$Env:SYSTEMROOT/System32/vcruntime140_1.dll`" } if (Test-Path `"`$vc_runtime_dll_path`") { Print-Msg `"Microsoft Visual C++ Redistributable 未缺失`" } else { Print-Msg `"检测到 Microsoft Visual C++ Redistributable 缺失, 这可能导致 PyTorch 无法正常识别 GPU 导致报错`" Print-Msg `"Microsoft Visual C++ Redistributable 下载: https://aka.ms/vs/17/release/vc_redist.x64.exe`" Print-Msg `"请下载并安装 Microsoft Visual C++ Redistributable 后重新启动`" Start-Sleep -Seconds 2 } } # 检查 Stable Diffusion WebUI 运行环境 function Check-Stable-Diffusion-WebUI-Env { if ((Test-Path `"`$PSScriptRoot/disable_check_env.txt`") -or (`$DisableEnvCheck)) { Print-Msg `"检测到 disable_check_env.txt 配置文件 / -DisableEnvCheck 命令行参数, 已禁用 Stable Diffusion WebUI 运行环境检测, 这可能会导致 Stable Diffusion WebUI 运行环境中存在的问题无法被发现并解决`" return } else { Print-Msg `"检查 Stable Diffusion WebUI 运行环境中`" } Check-Stable-Diffusion-WebUI-Requirements Check-Stable-Diffusion-WebUI-Env-Requirements Fix-PyTorch Check-Onnxruntime-GPU Check-Numpy-Version Check-MS-VCPP-Redistributable Print-Msg `"Stable Diffusion WebUI 运行环境检查完成`" } # 设置 SD WebUI 扩展列表镜像源 function Set-Stable-Diffusion-WebUI-Extension-List-Mirror { # 扩展列表地址: https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Stable Diffusion WebUI 扩展列表镜像源`" return } if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { # 使用自定义 Github 镜像源 if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源`" Print-Msg `"测试 `$github_mirror 是否可用`" `$github_mirror = `$github_mirror -creplace `"github.com`", `"raw.githubusercontent.com`" `$mirror_test_url = `"`${github_mirror}/licyk/empty/main/README.md`" try { Invoke-WebRequest -Uri `$mirror_test_url | Out-Null Print-Msg `"该镜像源可用, 设置 Stable Diffusion WebUI 扩展列表镜像源`" `$Env:WEBUI_EXTENSIONS_INDEX = `"`${github_mirror}/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json`" } catch { Print-Msg `"该镜像源不可用, 取消设置 Stable Diffusion WebUI 扩展列表镜像源`" } return } `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" `$github_mirror = `$i -creplace `"github.com`", `"raw.githubusercontent.com`" `$mirror_test_url = `"`${github_mirror}/licyk/empty/main/README.md`" try { Invoke-WebRequest -Uri `$mirror_test_url | Out-Null Print-Msg `"该镜像源可用, 设置 Stable Diffusion WebUI 扩展列表镜像源`" `$Env:WEBUI_EXTENSIONS_INDEX = `"`${github_mirror}/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json`" `$status = 1 break } catch { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消设置 Stable Diffusion WebUI 扩展列表镜像源`" } } # 设置 ControlNet 扩展依赖镜像源 function Set-ControlNet-Extension-Requirement-Mirror { if (`$USE_PIP_MIRROR) { Print-Msg `"检测到使用 PyPI 镜像源, 为 ControlNet 扩展依赖的安装设置 PyPI 镜像源`" } else { Print-Msg `"检测到使用 PyPI 官方源, 使用 ControlNet 扩展默认的 PyPI 镜像源`" return } `$Env:INSIGHTFACE_WHEEL = `"insightface`" `$Env:HANDREFINER_WHEEL = `"handrefinerportable`" `$Env:DEPTH_ANYTHING_WHEEL = `"depth_anything`" `$Env:DEPTH_ANYTHING_V2_WHEEL = `"depth_anything_v2`" `$Env:DSINE_WHEEL = `"dsine`" `$Env:CLIP_PACKAGE = `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/clip_python_package.zip`" `$Env:PIP_FIND_LINKS = `"`$Env:PIP_FIND_LINKS https://licyk.github.io/t/pypi/index.html`" `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR, https://licyk.github.io/t/pypi/index.html`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } Set-Github-Mirror Set-HuggingFace-Mirror Set-uv PyPI-Mirror-Status Set-Stable-Diffusion-WebUI-Extension-List-Mirror Set-ControlNet-Extension-Requirement-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" Read-Host | Out-Null return } `$launch_args = Get-Stable-Diffusion-WebUI-Launch-Args # 记录上次的路径 `$current_path = `$(Get-Location).ToString() Set-Location `"`$PSScriptRoot/`$Env:CORE_PREFIX`" Create-Stable-Diffusion-WebUI-Shortcut Check-Stable-Diffusion-WebUI-Env Set-PyTorch-CUDA-Memory-Alloc if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过启动 Stable Diffusion WebUI`" } else { Print-Msg `"启动 Stable Diffusion WebUI 中`" python launch.py `$launch_args `$req = `$? if (`$req) { Print-Msg `"Stable Diffusion WebUI 正常退出`" } else { Print-Msg `"Stable Diffusion WebUI 出现异常, 已退出`" } Read-Host | Out-Null } Set-Location `"`$current_path`" } ################### Main ".Trim() if (Test-Path "$InstallPath/launch.ps1") { Print-Msg "更新 launch.ps1 中" } else { Print-Msg "生成 launch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch.ps1" -Value $content } # 更新脚本 function Write-Update-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" Read-Host | Out-Null return } Print-Msg `"拉取 Stable Diffusion WebUI 更新内容中`" Fix-Git-Point-Off-Set `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$core_origin_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" fetch --recurse-submodules --all if (`$?) { Print-Msg `"应用 Stable Diffusion WebUI 更新中`" `$commit_hash = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" reset --hard `"`$remote_branch`" --recurse-submodules `$core_latest_ver = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$core_origin_ver -eq `$core_latest_ver) { Print-Msg `"Stable Diffusion WebUI 已为最新版, 当前版本:`$core_origin_ver`" } else { Print-Msg `"Stable Diffusion WebUI 更新成功, 版本:`$core_origin_ver -> `$core_latest_ver`" } } else { Print-Msg `"拉取 Stable Diffusion WebUI 更新内容失败`" Print-Msg `"更新 Stable Diffusion WebUI 失败, 请检查控制台日志。可尝试重新运行 SD WebUI Installer 更新脚本进行重试`" } Print-Msg `"退出 Stable Diffusion WebUI 更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update.ps1") { Print-Msg "更新 update.ps1 中" } else { Print-Msg "生成 update.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update.ps1" -Value $content } # 更新插件脚本 function Write-Update-Extension-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 修复 Git 分支游离 function Fix-Git-Point-Off-Set { param( `$path ) if (Test-Path `"`$path/.git`") { git -C `"`$path`" symbolic-ref HEAD > `$null 2> `$null if (!(`$?)) { Print-Msg `"检测到出现分支游离, 进行修复中`" git -C `"`$path`" remote prune origin # 删除无用分支 git -C `"`$path`" submodule init # 初始化git子模块 `$branch = `$(git -C `"`$path`" branch -a | Select-String -Pattern `"/HEAD`").ToString().Split(`"/`")[3] # 查询远程HEAD所指分支 git -C `"`$path`" checkout `$branch # 切换到主分支 git -C `"`$path`" reset --recurse-submodules --hard origin/`$branch # 回退到远程分支的版本 } } } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 列出更新结果 function List-Update-Status (`$update_status) { `$success = 0 `$failed = 0 `$sum = 0 Print-Msg `"当前 Stable Diffusion WebUI 扩展更新结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"扩展名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"更新结果`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$update_status.Count; `$i++) { `$content = `$update_status[`$i] `$name = `$content[0] `$ver = `$content[1] `$status = `$content[2] `$sum += 1 if (`$status) { `$success += 1 } else { `$failed += 1 } Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`${name}: `" -ForegroundColor White -NoNewline if (`$status) { Write-Host `"`$ver `" -ForegroundColor Cyan } else { Write-Host `"`$ver `" -ForegroundColor Red } } Write-Host Write-Host `"[●: `$sum | ✓: `$success | ×: `$failed]`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } Set-Github-Mirror if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" Read-Host | Out-Null return } `$extension_list = Get-ChildItem -Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/extensions`" | Select-Object -ExpandProperty FullName `$sum = 0 `$count = 0 ForEach (`$extension in `$extension_list) { if (Test-Path `"`$extension/.git`") { `$sum += 1 } } Print-Msg `"更新 Stable Diffusion WebUI 扩展中`" `$update_status = New-Object System.Collections.ArrayList ForEach (`$extension in `$extension_list) { if (!(Test-Path `"`$extension/.git`")) { continue } `$count += 1 `$extension_name = `$(`$(Get-Item `$extension).Name) Print-Msg `"[`$count/`$sum] 更新 `$extension_name 扩展中`" Fix-Git-Point-Off-Set `"`$extension`" `$origin_ver = `$(git -C `"`$extension`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") `$branch = `$(git -C `"`$extension`" symbolic-ref --quiet HEAD 2> `$null).split(`"/`")[2] git -C `"`$extension`" show-ref --verify --quiet `"refs/remotes/origin/`$(git -C `"`$extension`" branch --show-current)`" if (`$?) { `$remote_branch = `"origin/`$branch`" } else { `$author=`$(git -C `"`$extension`" config --get `"branch.`${branch}.remote`") if (`$author) { `$remote_branch = `$(git -C `"`$extension`" rev-parse --abbrev-ref `"`${branch}@{upstream}`") } else { `$remote_branch = `$branch } } git -C `"`$extension`" fetch --recurse-submodules --all if (`$?) { `$commit_hash = `$(git -C `"`$extension`" log `"`$remote_branch`" --max-count 1 --format=`"%h`") git -C `"`$extension`" reset --hard `"`$remote_branch`" --recurse-submodules `$latest_ver = `$(git -C `"`$extension`" show -s --format=`"%h %cd`" --date=format:`"%Y-%m-%d %H:%M:%S`") if (`$origin_ver -eq `$latest_ver) { Print-Msg `"[`$count/`$sum] `$extension_name 扩展已为最新版`" `$update_status.Add(@(`$extension_name, `"已为最新版`", `$true)) | Out-Null } else { Print-Msg `"[`$count/`$sum] `$extension_name 扩展更新成功, 版本:`$origin_ver -> `$latest_ver`" `$update_status.Add(@(`$extension_name, `"更新成功, 版本:`$origin_ver -> `$latest_ver`", `$true)) | Out-Null } } else { Print-Msg `"[`$count/`$sum] `$extension_name 扩展更新失败`" `$update_status.Add(@(`$extension_name, `"更新失败`", `$false)) | Out-Null } } List-Update-Status `$update_status Print-Msg `"退出 Stable Diffusion WebUI 扩展更新脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/update_extension.ps1") { Print-Msg "更新 update_extension.ps1 中" } else { Print-Msg "生成 update_extension.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/update_extension.ps1" -Value $content } # 分支切换脚本 function Write-Switch-Branch-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWitchBranch, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchBranch <Stable Diffusion WebUI 分支编号>] [-DisablePyPIMirror] [-DisableUpdate] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -BuildWitchBranch <Stable Diffusion WebUI 分支编号> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 switch_branch.ps1 脚本, 根据 Stable Diffusion WebUI 分支编号切换到对应的 Stable Diffusion WebUI 分支 Stable Diffusion WebUI 分支编号可运行 switch_branch.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `"`$i/licyk/empty`" `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 获取 SD WebUI 分支 function Get-Stable-Diffusion-WebUI-Branch { `$remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" symbolic-ref --quiet HEAD 2> `$null) if (`$ref -eq `$null) { `$ref = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" show -s --format=`"%h`") } return `"`$(`$remote.Split(`"/`")[-2])/`$(`$remote.Split(`"/`")[-1]) `$([System.IO.Path]::GetFileName(`$ref))`" } # 切换 SD WebUI 分支 function Switch-Stable-Diffusion-WebUI-Branch (`$remote, `$branch, `$use_submod) { `$sd_webui_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX`" `$preview_url = `$(git -C `"`$sd_webui_path`" remote get-url origin) Set-Github-Mirror # 设置 Github 镜像源 Print-Msg `"Stable Diffusion WebUI 远程源替换: `$preview_url -> `$remote`" git -C `"`$sd_webui_path`" remote set-url origin `"`$remote`" # 替换远程源 # 处理 Git 子模块 if (`$use_submod) { Print-Msg `"更新 Stable Diffusion WebUI 的 Git 子模块信息`" git -C `"`$sd_webui_path`" submodule update --init --recursive } else { Print-Msg `"禁用 Stable Diffusion WebUI 的 Git 子模块`" git -C `"`$sd_webui_path`" submodule deinit --all -f } Print-Msg `"拉取 Stable Diffusion WebUI 远程源更新`" git -C `"`$sd_webui_path`" fetch # 拉取远程源内容 if (`$?) { if (`$use_submod) { Print-Msg `"清理原有的 Git 子模块`" git -C `"`$sd_webui_path`" submodule deinit --all -f } Print-Msg `"切换 Stable Diffusion WebUI 分支至 `$branch`" # 本地分支不存在时创建一个分支 git -C `"`$sd_webui_path`" show-ref --verify --quiet `"refs/heads/`${branch}`" if (!(`$?)) { git -C `"`$sd_webui_path`" branch `"`${branch}`" } git -C `"`$sd_webui_path`" checkout `"`${branch}`" --force # 切换分支 Print-Msg `"应用 Stable Diffusion WebUI 远程源的更新`" if (`$use_submod) { Print-Msg `"更新 Stable Diffusion WebUI 的 Git 子模块信息`" git -C `"`$sd_webui_path`" reset --hard `"origin/`$branch`" git -C `"`$sd_webui_path`" submodule deinit --all -f git -C `"`$sd_webui_path`" submodule update --init --recursive } if (`$use_submod) { git -C `"`$sd_webui_path`" reset --recurse-submodules --hard `"origin/`$branch`" # 切换到最新的提交内容上 } else { git -C `"`$sd_webui_path`" reset --hard `"origin/`$branch`" # 切换到最新的提交内容上 } Print-Msg `"切换 Stable Diffusion WebUI 分支完成`" `$global:status = `$true } else { Print-Msg `"拉取 Stable Diffusion WebUI 远程源更新失败, 取消分支切换`" Print-Msg `"尝试回退 Stable Diffusion WebUI 的更改`" git -C `"`$sd_webui_path`" remote set-url origin `"`$preview_url`" if (`$use_submod) { git -C `"`$sd_webui_path`" submodule deinit --all -f } else { git -C `"`$sd_webui_path`" submodule update --init --recursive } Print-Msg `"回退 Stable Diffusion WebUI 分支更改完成`" Print-Msg `"切换 Stable Diffusion WebUI 分支更改失败`" `$global:status = `$false } } # 重置 repositories 中的组件 function Reset-Repositories { `$repositories_path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/repositories`" if (!(Test-Path `"`$repositories_path`")) { return } Print-Msg `"重置 Stable Diffusion WebUI 组件状态中`" `$repositories_list = Get-ChildItem -Path `"`$repositories_path`" | Select-Object -ExpandProperty FullName ForEach (`$rep_path in `$repositories_list) { if (Test-Path `"`$rep_path/.git`") { git -C `"`$rep_path`" reset --hard --recurse-submodules } } Print-Msg `"重置 Stable Diffusion WebUI 组件状态完成`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" Read-Host | Out-Null return } `$content = `" ----------------------------------------------------- - 1、AUTOMATIC1111 - Stable-Diffusion-WebUI 主分支 - 2、AUTOMATIC1111 - Stable-Diffusion-WebUI 测试分支 - 3、lllyasviel - Stable-Diffusion-WebUI-Forge 分支 - 4、Panchovix - Stable-Diffusion-WebUI-reForge 主分支 - 5、Panchovix - Stable-Diffusion-WebUI-reForge 测试分支 - 6、Haoming02 - Stable-Diffusion-WebUI-Forge-Classic 分支 - 7、Haoming02 - Stable-Diffusion-WebUI-Forge-Neo 分支 - 8、lshqqytiger - Stable-Diffusion-WebUI-AMDGPU 分支 - 9、vladmandic - SD.NEXT 主分支 - 10、vladmandic - SD.NEXT 测试分支 ----------------------------------------------------- `".Trim() `$to_exit = 0 while (`$True) { Print-Msg `"Stable Diffusion WebUI 分支列表`" `$go_to = 0 Write-Host `$content Print-Msg `"当前 Stable Diffusion WebUI 分支: `$(Get-Stable-Diffusion-WebUI-Branch)`" Print-Msg `"请选择 Stable Diffusion WebUI 分支`" Print-Msg `"提示: 输入数字后回车, 或者输入 exit 退出 Stable Diffusion WebUI 分支切换脚本`" if (`$BuildMode) { `$go_to = 1 `$arg = `$BuildWitchBranch } else { `$arg = (Read-Host `"=========================================>`").Trim() } switch (`$arg) { 1 { `$remote = `"https://github.com/AUTOMATIC1111/stable-diffusion-webui`" `$branch = `"master`" `$branch_name = `"AUTOMATIC1111 - Stable-Diffusion-WebUI 主分支`" `$use_submod = `$false `$go_to = 1 } 2 { `$remote = `"https://github.com/AUTOMATIC1111/stable-diffusion-webui`" `$branch = `"dev`" `$branch_name = `"AUTOMATIC1111 - Stable-Diffusion-WebUI 测试分支`" `$use_submod = `$false `$go_to = 1 } 3 { `$remote = `"https://github.com/lllyasviel/stable-diffusion-webui-forge`" `$branch = `"main`" `$branch_name = `"lllyasviel - Stable-Diffusion-WebUI-Forge 分支`" `$use_submod = `$false `$go_to = 1 } 4 { `$remote = `"https://github.com/Panchovix/stable-diffusion-webui-reForge`" `$branch = `"main`" `$branch_name = `"Panchovix - Stable-Diffusion-WebUI-reForge 主分支`" `$use_submod = `$false `$go_to = 1 } 5 { `$remote = `"https://github.com/Panchovix/stable-diffusion-webui-reForge`" `$branch = `"dev_upstream`" `$branch_name = `"Panchovix - Stable-Diffusion-WebUI-reForge 测试分支`" `$use_submod = `$false `$go_to = 1 } 6 { `$remote = `"https://github.com/Haoming02/sd-webui-forge-classic`" `$branch = `"classic`" `$branch_name = `"Haoming02 - Stable-Diffusion-WebUI-Forge-Classic 分支`" `$use_submod = `$false `$go_to = 1 } 7 { `$remote = `"https://github.com/Haoming02/sd-webui-forge-classic`" `$branch = `"neo`" `$branch_name = `"Haoming02 - Stable-Diffusion-WebUI-Forge-Neo 分支`" `$use_submod = `$false `$go_to = 1 } 8 { `$remote = `"https://github.com/lshqqytiger/stable-diffusion-webui-amdgpu`" `$branch = `"master`" `$branch_name = `"lshqqytiger - Stable-Diffusion-WebUI-AMDGPU 分支`" `$use_submod = `$false `$go_to = 1 } 9 { `$remote = `"https://github.com/vladmandic/sdnext`" `$branch = `"master`" `$branch_name = `"vladmandic - SD.NEXT 主分支`" `$use_submod = `$true `$go_to = 1 } 10 { `$remote = `"https://github.com/vladmandic/sdnext`" `$branch = `"dev`" `$branch_name = `"vladmandic - SD.NEXT 测试分支`" `$use_submod = `$true `$go_to = 1 } exit { Print-Msg `"退出 Stable Diffusion WebUI 分支切换脚本`" `$to_exit = 1 `$go_to = 1 } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否切换 Stable Diffusion WebUI 分支到 `$branch_name ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$operate = `"yes`" } else { `$operate = (Read-Host `"=========================================>`").Trim() } if (`$operate -eq `"yes`" -or `$operate -eq `"y`" -or `$operate -eq `"YES`" -or `$operate -eq `"Y`") { Print-Msg `"开始切换 Stable Diffusion WebUI 分支`" Switch-Stable-Diffusion-WebUI-Branch `$remote `$branch `$use_submod Reset-Repositories if (`$status) { Print-Msg `"切换 Stable Diffusion WebUI 分支成功`" } else { Print-Msg `"切换 Stable Diffusion WebUI 分支失败, 可尝试重新运行 Stable Diffusion WebUI 分支切换脚本`" } } else { Print-Msg `"取消切换 Stable Diffusion WebUI 分支`" } Print-Msg `"退出 Stable Diffusion WebUI 分支切换脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/switch_branch.ps1") { Print-Msg "更新 switch_branch.ps1 中" } else { Print-Msg "生成 switch_branch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/switch_branch.ps1" -Value $content } # 获取安装脚本 function Write-Launch-Stable-Diffusion-WebUI-Install-Script { $content = " param ( [string]`$InstallPath, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisablePyPIMirror, [switch]`$DisableUV, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [string]`$InstallBranch, [Parameter(ValueFromRemainingArguments=`$true)]`$ExtraArgs ) `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION if (-not `$InstallPath) { `$InstallPath = `$PSScriptRoot } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 下载 SD WebUI Installer function Download-Stable-Diffusion-WebUI-Installer { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$PSScriptRoot/cache`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"正在下载最新的 SD WebUI Installer 脚本`" Invoke-WebRequest -Uri `$url -OutFile `"`$PSScriptRoot/cache/stable_diffusion_webui_installer.ps1`" if (`$?) { Print-Msg `"下载 SD WebUI Installer 脚本成功`" break } else { Print-Msg `"下载 SD WebUI Installer 脚本失败`" `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 SD WebUI Installer 脚本`" } else { Print-Msg `"下载 SD WebUI Installer 脚本失败, 可尝试重新运行 SD WebUI Installer 下载脚本`" return `$false } } } return `$true } # 获取本地配置文件参数 function Get-Local-Setting { `$arg = @{} if ((Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`") -or (`$DisablePyPIMirror)) { `$arg.Add(`"-DisablePyPIMirror`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { `$arg.Add(`"-DisableProxy`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$arg.Add(`"-UseCustomProxy`", `$proxy_value) } } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { `$arg.Add(`"-DisableUV`", `$true) } if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { `$arg.Add(`"-DisableGithubMirror`", `$true) } else { if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } `$arg.Add(`"-UseCustomGithubMirror`", `$github_mirror) } } if ((Get-Command git -ErrorAction SilentlyContinue) -and (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/.git`")) { `$git_remote = `$(git -C `"`$PSScriptRoot/`$Env:CORE_PREFIX`" remote get-url origin) `$array = `$git_remote -split `"/`" `$branch = `"`$(`$array[-2])/`$(`$array[-1])`" if ((`$branch -eq `"AUTOMATIC1111/stable-diffusion-webui`") -or (`$branch -eq `"AUTOMATIC1111/stable-diffusion-webui.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui`") } elseif ((`$branch -eq `"lllyasviel/stable-diffusion-webui-forge`") -or (`$branch -eq `"lllyasviel/stable-diffusion-webui-forge.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_forge`") } elseif ((`$branch -eq `"Panchovix/stable-diffusion-webui-reForge`") -or (`$branch -eq `"Panchovix/stable-diffusion-webui-reForge.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_reforge`") } elseif ((`$branch -eq `"Haoming02/sd-webui-forge-classic`") -or (`$branch -eq `"Haoming02/sd-webui-forge-classic.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_forge_classic`") } elseif ((`$branch -eq `"lshqqytiger/stable-diffusion-webui-amdgpu`") -or (`$branch -eq `"lshqqytiger/stable-diffusion-webui-amdgpu.git`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_amdgpu`") } elseif ((`$branch -eq `"vladmandic/automatic`") -or (`$branch -eq `"vladmandic/automatic.git`") -or (`$branch -eq `"vladmandic/sdnext`") -or (`$branch -eq `"vladmandic/sdnext.git`")) { `$arg.Add(`"-InstallBranch`", `"sdnext`") } } elseif ((Test-Path `"`$PSScriptRoot/install_sd_webui.txt`") -or (`$InstallBranch -eq `"sd_webui`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui`") } elseif ((Test-Path `"`$PSScriptRoot/install_sd_webui_forge.txt`") -or (`$InstallBranch -eq `"sd_webui_forge`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_forge`") } elseif ((Test-Path `"`$PSScriptRoot/install_sd_webui_reforge.txt`") -or (`$InstallBranch -eq `"sd_webui_reforge`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_reforge`") } elseif ((Test-Path `"`$PSScriptRoot/install_sd_webui_forge_classic.txt`") -or (`$InstallBranch -eq `"sd_webui_forge_classic`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_forge_classic`") } elseif ((Test-Path `"`$PSScriptRoot/install_sd_webui_amdgpu.txt`") -or (`$InstallBranch -eq `"sd_webui_amdgpu`")) { `$arg.Add(`"-InstallBranch`", `"sd_webui_amdgpu`") } elseif ((Test-Path `"`$PSScriptRoot/install_sd_next.txt`") -or (`$InstallBranch -eq `"sdnext`")) { `$arg.Add(`"-InstallBranch`", `"sdnext`") } `$arg.Add(`"-InstallPath`", `$InstallPath) return `$arg } # 处理额外命令行参数 function Get-ExtraArgs { `$extra_args = New-Object System.Collections.ArrayList ForEach (`$a in `$ExtraArgs) { `$extra_args.Add(`$a) | Out-Null } `$params = `$extra_args.ForEach{ if (`$_ -match '\s|`"') { `"'{0}'`" -f (`$_ -replace `"'`", `"''`") } else { `$_ } } -join ' ' return `$params } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Set-Proxy `$status = Download-Stable-Diffusion-WebUI-Installer if (`$status) { Print-Msg `"运行 SD WebUI Installer 中`" `$arg = Get-Local-Setting `$extra_args = Get-ExtraArgs try { Invoke-Expression `"& ```"`$PSScriptRoot/cache/stable_diffusion_webui_installer.ps1```" `$extra_args @arg`" } catch { Print-Msg `"运行 SD WebUI Installer 时出现了错误: `$_`" Read-Host | Out-Null } } else { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/launch_stable_diffusion_webui_installer.ps1") { Print-Msg "更新 launch_stable_diffusion_webui_installer.ps1 中" } else { Print-Msg "生成 launch_stable_diffusion_webui_installer.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/launch_stable_diffusion_webui_installer.ps1" -Value $content } # 重装 PyTorch 脚本 function Write-PyTorch-ReInstall-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [int]`$BuildWithTorch, [switch]`$BuildWithTorchReinstall, [switch]`$DisablePyPIMirror, [switch]`$DisableUpdate, [switch]`$DisableUV, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-DisablePyPIMirror] [-DisableUpdate] [-DisableUV] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD WebUI Installer 构建模式, 并且添加 -BuildWithTorch) 在 SD WebUI Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableUV 禁用 SD WebUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 uv 是否需要更新 function Check-uv-Version { `$content = `" import re from importlib.metadata import version def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def is_uv_need_update() -> bool: try: uv_ver = version('uv') except: return True if compare_versions(uv_ver, uv_minimum_ver) < 0: return True else: return False uv_minimum_ver = '`$UV_MINIMUM_VER' print(is_uv_need_update()) `".Trim() Print-Msg `"检测 uv 是否需要更新`" `$status = `$(python -c `"`$content`") if (`$status -eq `"True`") { Print-Msg `"更新 uv 中`" python -m pip install -U `"uv>=`$UV_MINIMUM_VER`" if (`$?) { Print-Msg `"uv 更新成功`" } else { Print-Msg `"uv 更新失败, 可能会造成 uv 部分功能异常`" } } else { Print-Msg `"uv 无需更新`" } } # 设置 uv 的使用状态 function Set-uv { # 切换 uv 指定的 Python if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`" } if ((Test-Path `"`$PSScriptRoot/disable_uv.txt`") -or (`$DisableUV)) { Print-Msg `"检测到 disable_uv.txt 配置文件 / -DisableUV 命令行参数, 已禁用 uv, 使用 Pip 作为 Python 包管理器`" `$Global:USE_UV = `$false } else { Print-Msg `"默认启用 uv 作为 Python 包管理器, 加快 Python 软件包的安装速度`" Print-Msg `"当 uv 安装 Python 软件包失败时, 将自动切换成 Pip 重试 Python 软件包的安装`" `$Global:USE_UV = `$true Check-uv-Version } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取 xFormers 版本 function Get-xFormers-Version { `$content = `" from importlib.metadata import version try: ver = version('xformers') except: ver = None print(ver) `".Trim() `$status = `$(python -c `"`$content`") return `$status } # 获取驱动支持的最高 CUDA 版本 function Get-Drive-Support-CUDA-Version { Print-Msg `"获取显卡驱动支持的最高 CUDA 版本`" if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) { `$cuda_ver = `$(nvidia-smi -q | Select-String -Pattern 'CUDA Version\s*:\s*([\d.]+)').Matches.Groups[1].Value } else { `$cuda_ver = `"未知`" } return `$cuda_ver } # 显示 PyTorch 和 xFormers 版本 function Get-PyTorch-And-xFormers-Version { `$content = `" from importlib.metadata import version try: print(version('torch')) except: print(None) `".Trim() `$torch_ver = `$(python -c `"`$content`") `$content = `" from importlib.metadata import version try: print(version('xformers')) except: print(None) `".Trim() `$xformers_ver = `$(python -c `"`$content`") if (`$torch_ver -eq `"None`") { `$torch_ver = `"未安装`" } if (`$xformers_ver -eq `"None`") { `$xformers_ver = `"未安装`" } return `$torch_ver, `$xformers_ver } # 获取 HashTable 的值 function Get-HashValue { param( [hashtable]`$Hashtable, [string]`$Key, [object]`$Default = `$null ) if (`$Hashtable.ContainsKey(`$Key)) { return `$Hashtable[`$Key] } else { return `$Default } } # 获取可用的 PyTorch 类型 function Get-Avaliable-PyTorch-Type { `$content = `" import re import json import subprocess def get_cuda_comp_cap() -> float: # Returns float of CUDA Compute Capability using nvidia-smi # Returns 0.0 on error # CUDA Compute Capability # ref https://developer.nvidia.com/cuda-gpus # ref https://en.wikipedia.org/wiki/CUDA # Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0 try: return max(map(float, subprocess.check_output(['nvidia-smi', '--query-gpu=compute_cap', '--format=noheader,csv'], text=True).splitlines())) except Exception as _: return 0.0 def get_cuda_version() -> float: try: # 获取 nvidia-smi 输出 output = subprocess.check_output(['nvidia-smi', '-q'], text=True) match = re.search(r'CUDA Version\s+:\s+(\d+\.\d+)', output) if match: return float(match.group(1)) return 0.0 except: return 0.0 def get_gpu_list() -> list[dict[str, str]]: try: cmd = [ 'powershell', '-Command', 'Get-CimInstance Win32_VideoController | Select-Object Name, AdapterCompatibility, AdapterRAM, DriverVersion | ConvertTo-Json' ] result = subprocess.run(cmd, capture_output=True, text=True, check=True) gpus = json.loads(result.stdout) if isinstance(gpus, dict): gpus = [gpus] gpu_info = [] for gpu in gpus: gpu_info.append({ 'Name': gpu.get('Name', None), 'AdapterCompatibility': gpu.get('AdapterCompatibility', None), 'AdapterRAM': gpu.get('AdapterRAM', None), 'DriverVersion': gpu.get('DriverVersion', None), }) return gpu_info except Exception as _: return [] def compare_versions(version1: str, version2: str) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 CUDA_TYPE = [ 'cu113', 'cu117', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu129', 'cu130', ] def get_avaliable_device() -> str: cuda_comp_cap = get_cuda_comp_cap() cuda_support_ver = get_cuda_version() gpu_list = get_gpu_list() device_list = ['cpu'] if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') and ( x.get('Name', '').startswith('Intel(R) Arc') or x.get('Name', '').startswith('Intel(R) Core Ultra') ) ]): device_list.append('xpu') if any([ x for x in gpu_list if 'Intel' in x.get('AdapterCompatibility', '') or 'NVIDIA' in x.get('AdapterCompatibility', '') or 'Advanced Micro Devices' in x.get('AdapterCompatibility', '') ]): device_list.append('directml') if compare_versions(cuda_comp_cap, '10.0') > 0: for ver in CUDA_TYPE: if compare_versions(ver, str(int(12.8 * 10))) >= 0: device_list.append(ver) else: for ver in CUDA_TYPE: if compare_versions(ver, str(int(cuda_support_ver * 10))) <= 0: device_list.append(ver) return ','.join(list(set(device_list))) if __name__ == '__main__': print(get_avaliable_device()) `".Trim() Print-Msg `"获取可用的 PyTorch 类型`" `$res = `$(python -c `"`$content`") return `$res -split ',' | ForEach-Object { `$_.Trim() } } # 获取 PyTorch 列表 function Get-PyTorch-List { `$pytorch_list = New-Object System.Collections.ArrayList `$supported_type = Get-Avaliable-PyTorch-Type # >>>>>>>>>> Start `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.12.1+cpu torchvision==0.13.1+cpu torchaudio==1.12.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.12.1 (CUDA 11.3) + xFormers 0.0.14`" `"type`" = `"cu113`" `"supported`" = `"cu113`" -in `$supported_type `"torch`" = `"torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==1.12.1+cu113`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==1.13.1+cpu torchvision==0.14.1+cpu torchaudio==0.13.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 torch-directml==0.1.13.1.dev230413`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 1.13.1 (CUDA 11.7) + xFormers 0.0.16`" `"type`" = `"cu117`" `"supported`" = `"cu117`" -in `$supported_type `"torch`" = `"torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==1.13.1+cu117`" `"xformers`" = `"xformers==0.0.18`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.0 torch-directml==0.2.0.dev230426`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.0.0a0+gite9ebda2 torchvision==0.15.2a0+fa99a53 intel_extension_for_pytorch==2.0.110+gitc6ea20b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.0 (CUDA 11.8) + xFormers 0.0.18`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.0+cu118`" `"xformers`" = `"xformers==0.0.14`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.0.1+cpu torchvision==0.15.2+cpu torchaudio==2.0.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.0.1 (CUDA 11.8) + xFormers 0.0.22`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.1+cu118`" `"xformers`" = `"xformers==0.0.22`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.0+cpu torchvision==0.16.0+cpu torchaudio==2.1.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi torchaudio==2.1.0a0+cxx11.abi intel_extension_for_pytorch==2.1.10+xpu`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.0 (Intel Core Ultra)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.1.0a0+git7bcf7da torchvision==0.16.0+fbb4cc5 torchaudio==2.1.0+6ea1133 intel_extension_for_pytorch==2.1.20+git4849f3b`" `"find_links`" = `"https://licyk.github.io/t/pypi/index.html`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.1+cpu torchvision==0.16.1+cpu torchaudio==2.1.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 11.8) + xFormers 0.0.23`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu118 torchvision==0.16.1+cu118 torchaudio==2.1.1+cu118`" `"xformers`" = `"xformers==0.0.23+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.1 (CUDA 12.1) + xFormers 0.0.23`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.1+cu121 torchvision==0.16.1+cu121 torchaudio==2.1.1+cu121`" `"xformers`" = `"xformers===0.0.23`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.1.2+cpu torchvision==0.16.2+cpu torchaudio==2.1.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 11.8) + xFormers 0.0.23.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118`" `"xformers`" = `"xformers==0.0.23.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.1.2 (CUDA 12.1) + xFormers 0.0.23.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.1.2+cu121 torchvision==0.16.2+cu121 torchaudio==2.1.2+cu121`" `"xformers`" = `"xformers===0.0.23.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 11.8) + xFormers 0.0.24`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu118 torchvision==0.17.0+cu118 torchaudio==2.2.0+cu118`" `"xformers`" = `"xformers==0.0.24+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.0 (CUDA 12.1) + xFormers 0.0.24`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.0+cu121 torchvision==0.17.0+cu121 torchaudio==2.2.0+cu121`" `"xformers`" = `"xformers===0.0.24`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.1+cpu torchvision==0.17.1+cpu torchaudio==2.2.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 11.8) + xFormers 0.0.25`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu118 torchvision==0.17.1+cu118 torchaudio==2.2.1+cu118`" `"xformers`" = `"xformers==0.0.25+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 torch-directml==0.2.1.dev240521`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.1 (CUDA 12.1) + xFormers 0.0.25`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121`" `"xformers`" = `"xformers===0.0.25`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.2.2+cpu torchvision==0.17.2+cpu torchaudio==2.2.2+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 11.8) + xFormers 0.0.25.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu118 torchvision==0.17.2+cu118 torchaudio==2.2.2+cu118`" `"xformers`" = `"xformers==0.0.25.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.2.2 (CUDA 12.1) + xFormers 0.0.25.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.2.2+cu121 torchvision==0.17.2+cu121 torchaudio==2.2.2+cu121`" `"xformers`" = `"xformers===0.0.25.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.0+cpu torchvision==0.18.0+cpu torchaudio==2.3.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 11.8) + xFormers 0.0.26.post1`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" `"xformers`" = `"xformers==0.0.26.post1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.0 (CUDA 12.1) + xFormers 0.0.26.post1`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121`" `"xformers`" = `"xformers===0.0.26.post1`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.3.1+cpu torchvision==0.18.1+cpu torchaudio==2.3.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (DirectML)`" `"type`" = `"directml`" `"supported`" = `"directml`" -in `$supported_type `"torch`" = `"torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 torch-directml==0.2.3.dev240715`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 11.8) + xFormers 0.0.27`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118`" `"xformers`" = `"xformers==0.0.27+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.3.1 (CUDA 12.1) + xFormers 0.0.27`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.3.1+cu121 torchvision==0.18.1+cu121 torchaudio==2.3.1+cu121`" `"xformers`" = `"xformers===0.0.27`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.0+cpu torchvision==0.19.0+cpu torchaudio==2.4.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 11.8) + xFormers 0.0.27.post2`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu118 torchvision==0.19.0+cu118 torchaudio==2.4.0+cu118`" `"xformers`" = `"xformers==0.0.27.post2+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.0 (CUDA 12.1) + xFormers 0.0.27.post2`" `"type`" = `"cu121`" `"supported`" = `"cu121`" -in `$supported_type `"torch`" = `"torch==2.4.0+cu121 torchvision==0.19.0+cu121 torchaudio==2.4.0+cu121`" `"xformers`" = `"xformers==0.0.27.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU121 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.4.1+cpu torchvision==0.19.1+cpu torchaudio==2.4.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.4.1 (CUDA 12.4) + xFormers 0.0.28.post1`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.4.1+cu124 torchvision==0.19.1+cu124 torchaudio==2.4.1+cu124`" `"xformers`" = `"xformers==0.0.28.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.0+cpu torchvision==0.20.0+cpu torchaudio==2.5.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.0 (CUDA 12.4) + xFormers 0.0.28.post2`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.0+cu124 torchvision==0.20.0+cu124 torchaudio==2.5.0+cu124`" `"xformers`" = `"xformers==0.0.28.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.5.1+cpu torchvision==0.20.1+cpu torchaudio==2.5.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.5.1 (CUDA 12.4) + xFormers 0.0.28.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124`" `"xformers`" = `"xformers==0.0.28.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+cpu torchvision==0.21.0+cpu torchaudio==2.6.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.6.0+xpu torchvision==0.21.0+xpu torchaudio==2.6.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.4) + xFormers 0.0.29.post3`" `"type`" = `"cu124`" `"supported`" = `"cu124`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu124 torchvision==0.21.0+cu124 torchaudio==2.6.0+cu124`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU124 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.6.0 (CUDA 12.6) + xFormers 0.0.29.post3`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.6.0+cu126 torchvision==0.21.0+cu126 torchaudio==2.6.0+cu126`" `"xformers`" = `"xformers==0.0.29.post3`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+cpu torchvision==0.22.0+cpu torchaudio==2.7.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.0+xpu torchvision==0.22.0+xpu torchaudio==2.7.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu118 torchvision==0.22.0+cu118 torchaudio==2.7.0+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.6) + xFormers 0.0.30`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu126 torchvision==0.22.0+cu126 torchaudio==2.7.0+cu126`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.0 (CUDA 12.8) + xFormers 0.0.30`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.0+cu128 torchvision==0.22.0+cu128 torchaudio==2.7.0+cu128`" `"xformers`" = `"xformers==0.0.30`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+cpu torchvision==0.22.1+cpu torchaudio==2.7.1+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.7.1+xpu torchvision==0.22.1+xpu torchaudio==2.7.1+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 11.8)`" `"type`" = `"cu118`" `"supported`" = `"cu118`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu118 torchvision==0.22.1+cu118 torchaudio==2.7.1+cu118`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU118 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.6) + xFormers 0.0.31.post1`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu126 torchvision==0.22.1+cu126 torchaudio==2.7.1+cu126`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.7.1 (CUDA 12.8) + xFormers 0.0.31.post1`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.7.1+cu128 torchvision==0.22.1+cu128 torchaudio==2.7.1+cu128`" `"xformers`" = `"xformers==0.0.31.post1`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+cpu torchvision==0.23.0+cpu torchaudio==2.8.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.8.0+xpu torchvision==0.23.0+xpu torchaudio==2.8.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu128 torchvision==0.23.0+cu128 torchaudio==2.8.0+cu128`" `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.8.0 (CUDA 12.9)`" `"type`" = `"cu129`" `"supported`" = `"cu129`" -in `$supported_type `"torch`" = `"torch==2.8.0+cu129 torchvision==0.23.0+cu129 torchaudio==2.8.0+cu129`" # `"xformers`" = `"xformers==0.0.32.post2`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU129 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CPU)`" `"type`" = `"cpu`" `"supported`" = `"cpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+cpu torchvision==0.24.0+cpu torchaudio==2.9.0+cpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (Intel Arc)`" `"type`" = `"xpu`" `"supported`" = `"xpu`" -in `$supported_type `"torch`" = `"torch==2.9.0+xpu torchvision==0.24.0+xpu torchaudio==2.9.0+xpu`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_XPU } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.6)`" `"type`" = `"cu126`" `"supported`" = `"cu126`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu126 torchvision==0.24.0+cu126 torchaudio==2.9.0+cu126`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU126 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 12.8)`" `"type`" = `"cu128`" `"supported`" = `"cu128`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu128 torchvision==0.24.0+cu128 torchaudio==2.9.0+cu128`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU128 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null `$pytorch_list.Add(@{ `"name`" = `"Torch 2.9.0 (CUDA 13.0)`" `"type`" = `"cu130`" `"supported`" = `"cu130`" -in `$supported_type `"torch`" = `"torch==2.9.0+cu130 torchvision==0.24.0+cu130 torchaudio==2.9.0+cu130`" `"xformers`" = `"xformers==0.0.33`" `"index_mirror`" = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU } else { `$PIP_EXTRA_INDEX_MIRROR_CU130 } `"extra_index_mirror`" = `"`" `"find_links`" = `"`" }) | Out-Null # <<<<<<<<<< End return `$pytorch_list } # 列出 PyTorch 列表 function List-PyTorch (`$pytorch_list) { Print-Msg `"PyTorch 版本列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"版本序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"PyTorch 版本`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"支持当前设备情况`" -ForegroundColor Blue for (`$i = 0; `$i -lt `$pytorch_list.Count; `$i++) { `$pytorch_hashtables = `$pytorch_list[`$i] `$count += 1 `$name = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"name`" `$supported = Get-HashValue -Hashtable `$pytorch_hashtables -Key `"supported`" Write-Host `"- `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline if (`$supported) { Write-Host `"(支持✓)`" -ForegroundColor Green } else { Write-Host `"(不支持×)`" -ForegroundColor Red } } Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } Set-uv PyPI-Mirror-Status `$pytorch_list = Get-PyTorch-List `$go_to = 0 `$to_exit = 0 `$torch_ver = `"`" `$xformers_ver = `"`" `$cuda_support_ver = Get-Drive-Support-CUDA-Version `$current_torch_ver, `$current_xformers_ver = Get-PyTorch-And-xFormers-Version `$after_list_model_option = `"`" while (`$True) { switch (`$after_list_model_option) { display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" List-PyTorch `$pytorch_list Print-Msg `"当前 PyTorch 版本: `$current_torch_ver`" Print-Msg `"当前 xFormers 版本: `$current_xformers_ver`" Print-Msg `"当前显卡驱动支持的最高 CUDA 版本: `$cuda_support_ver`" Print-Msg `"请选择 PyTorch 版本`" Print-Msg `"提示:`" Print-Msg `"1. PyTorch 版本通常来说选择最新版的即可`" Print-Msg `"2. 驱动支持的最高 CUDA 版本需要大于或等于要安装的 PyTorch 中所带的 CUDA 版本, 若驱动支持的最高 CUDA 版本低于要安装的 PyTorch 中所带的 CUDA 版本, 可尝试更新显卡驱动, 或者选择 CUDA 版本更低的 PyTorch`" Print-Msg `"3. 输入数字后回车, 或者输入 exit 退出 PyTorch 重装脚本`" if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建已启用, 指定安装的 PyTorch 序号: `$BuildWithTorch`" `$arg = `$BuildWithTorch `$go_to = 1 } else { `$arg = (Read-Host `"=========================================>`").Trim() } switch (`$arg) { exit { Print-Msg `"退出 PyTorch 重装脚本`" `$to_exit = 1 `$go_to = 1 } Default { try { # 检测输入是否符合列表 `$i = [int]`$arg if (!((`$i -ge 1) -and (`$i -le `$pytorch_list.Count))) { `$after_list_model_option = `"display_input_error`" break } `$pytorch_info = `$pytorch_list[(`$i - 1)] `$combination_name = Get-HashValue -Hashtable `$pytorch_info -Key `"name`" `$torch_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"torch`" `$xformers_ver = Get-HashValue -Hashtable `$pytorch_info -Key `"xformers`" `$index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"index_mirror`" `$extra_index_mirror = Get-HashValue -Hashtable `$pytorch_info -Key `"extra_index_mirror`" `$find_links = Get-HashValue -Hashtable `$pytorch_info -Key `"find_links`" if (`$null -ne `$index_mirror) { `$Env:PIP_INDEX_URL = `$index_mirror `$Env:UV_DEFAULT_INDEX = `$index_mirror } if (`$null -ne `$extra_index_mirror) { `$Env:PIP_EXTRA_INDEX_URL = `$extra_index_mirror `$Env:UV_INDEX = `$extra_index_mirror } if (`$null -ne `$find_links) { `$Env:PIP_FIND_LINKS = `$find_links `$Env:UV_FIND_LINKS = `$find_links } } catch { `$after_list_model_option = `"display_input_error`" break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Read-Host | Out-Null exit 0 } Print-Msg `"是否选择仅强制重装 ? (通常情况下不需要)`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { if (`$BuildWithTorchReinstall) { `$use_force_reinstall = `"yes`" } else { `$use_force_reinstall = `"no`" } } else { `$use_force_reinstall = (Read-Host `"=========================================>`").Trim() } if (`$use_force_reinstall -eq `"yes`" -or `$use_force_reinstall -eq `"y`" -or `$use_force_reinstall -eq `"YES`" -or `$use_force_reinstall -eq `"Y`") { `$force_reinstall_arg = `"--force-reinstall`" `$force_reinstall_status = `"启用`" } else { `$force_reinstall_arg = New-Object System.Collections.ArrayList `$force_reinstall_status = `"禁用`" } Print-Msg `"当前的选择: `$combination_name`" Print-Msg `"PyTorch: `$torch_ver`" Print-Msg `"xFormers: `$xformers_ver`" Print-Msg `"仅强制重装: `$force_reinstall_status`" Print-Msg `"是否确认安装?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$install_torch = `"yes`" } else { `$install_torch = (Read-Host `"=========================================>`").Trim() } if (`$install_torch -eq `"yes`" -or `$install_torch -eq `"y`" -or `$install_torch -eq `"YES`" -or `$install_torch -eq `"Y`") { Print-Msg `"重装 PyTorch 中`" if (`$USE_UV) { uv pip install `$torch_ver.ToString().Split() `$force_reinstall_arg if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } } else { python -m pip install `$torch_ver.ToString().Split() `$force_reinstall_arg --no-warn-conflicts } if (`$?) { Print-Msg `"安装 PyTorch 成功`" } else { Print-Msg `"安装 PyTorch 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } if (`$null -ne `$xformers_ver) { Print-Msg `"重装 xFormers 中`" if (`$USE_UV) { `$current_xf_ver = Get-xFormers-Version if (`$xformers_ver.Split(`"=`")[-1] -ne `$current_xf_ver) { Print-Msg `"卸载原有 xFormers 中`" python -m pip uninstall xformers -y } uv pip install `$xformers_ver `$force_reinstall_arg --no-deps if (!(`$?)) { Print-Msg `"检测到 uv 安装 Python 软件包失败, 尝试回滚至 Pip 重试 Python 软件包安装`" python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } } else { python -m pip install `$xformers_ver `$force_reinstall_arg --no-deps --no-warn-conflicts } if (`$?) { Print-Msg `"安装 xFormers 成功`" } else { Print-Msg `"安装 xFormers 失败, 终止 PyTorch 重装进程`" if (!(`$BuildMode)) { Read-Host | Out-Null } exit 1 } } } else { Print-Msg `"取消重装 PyTorch`" } Print-Msg `"退出 PyTorch 重装脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/reinstall_pytorch.ps1") { Print-Msg "更新 reinstall_pytorch.ps1 中" } else { Print-Msg "生成 reinstall_pytorch.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/reinstall_pytorch.ps1" -Value $content } # 模型下载脚本 function Write-Download-Model-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$BuildMode, [string]`$BuildWitchModel, [switch]`$DisablePyPIMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableUpdate, [switch]`$DisableAutoApplyUpdate ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-BuildMode] [-BuildWitchModel <模型编号列表>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUpdate] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -BuildMode 启用 SD WebUI Installer 构建模式 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableUpdate 禁用 SD WebUI Installer 更新检查 -DisableAutoApplyUpdate 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # SD WebUI Installer 更新检测 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if ((Test-Path `"`$PSScriptRoot/disable_update.txt`") -or (`$DisableUpdate)) { Print-Msg `"检测到 disable_update.txt 更新配置文件 / -DisableUpdate 命令行参数, 已禁用 SD WebUI Installer 的自动检查更新功能`" return } # 获取更新时间间隔 try { `$last_update_time = Get-Content `"`$PSScriptRoot/update_time.txt`" 2> `$null `$last_update_time = Get-Date `$last_update_time -Format `"yyyy-MM-dd HH:mm:ss`" } catch { `$last_update_time = Get-Date 0 -Format `"yyyy-MM-dd HH:mm:ss`" } finally { `$update_time = Get-Date -Format `"yyyy-MM-dd HH:mm:ss`" `$time_span = New-TimeSpan -Start `$last_update_time -End `$update_time } if (`$time_span.TotalSeconds -gt `$UPDATE_TIME_SPAN) { Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 } else { return } ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -le `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 已是最新版本`" return } if ((`$DisableAutoApplyUpdate) -or (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`")) { Print-Msg `"检测到 SD WebUI Installer 有新版本可用, 是否进行更新 (yes/no) ?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" `$arg = (Read-Host `"========================================>`").Trim() if (!(`$arg -eq `"yes`" -or `$arg -eq `"y`" -or `$arg -eq `"YES`" -or `$arg -eq `"Y`")) { Print-Msg `"跳过 SD WebUI Installer 更新`" return } } else { Print-Msg `"检测到 SD WebUI Installer 有新版本可用`" } Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } # 检查 Aria2 版本并更新 function Check-Aria2-Version { `$content = `" import re import subprocess def get_aria2_ver() -> str: try: aria2_output = subprocess.check_output(['aria2c', '--version'], text=True).splitlines() except: return None for text in aria2_output: version_match = re.search(r'aria2 version (\d+\.\d+\.\d+)', text) if version_match: return version_match.group(1) return None def compare_versions(version1, version2) -> int: version1 = str(version1) version2 = str(version2) try: nums1 = re.sub(r'[a-zA-Z]+', '', version1).replace('-', '.').replace('+', '.').split('.') nums2 = re.sub(r'[a-zA-Z]+', '', version2).replace('-', '.').replace('+', '.').split('.') except: return 0 for i in range(max(len(nums1), len(nums2))): num1 = int(nums1[i]) if i < len(nums1) else 0 num2 = int(nums2[i]) if i < len(nums2) else 0 if num1 == num2: continue elif num1 > num2: return 1 else: return -1 return 0 def aria2_need_update(aria2_min_ver: str) -> bool: aria2_ver = get_aria2_ver() if aria2_ver: if compare_versions(aria2_ver, aria2_min_ver) < 0: return True else: return False else: return True print(aria2_need_update('`$ARIA2_MINIMUM_VER')) `".Trim() Print-Msg `"检查 Aria2 是否需要更新`" `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$status = `$(python -c `"`$content`") `$i = 0 if (`$status -eq `"True`") { Print-Msg `"更新 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null } else { Print-Msg `"Aria2 无需更新`" return } ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"Aria2 下载失败, 无法更新 Aria2, 可能会导致模型下载出现问题`" return } } } if ((Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`" -Force } elseif ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/git/bin/git.exe`")) { Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } else { New-Item -ItemType Directory -Path `"`$PSScriptRoot/git/bin`" -Force > `$null Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$PSScriptRoot/git/bin/aria2c.exe`" -Force } Print-Msg `"Aria2 更新完成`" } # 模型列表 function Get-Model-List { `$model_list = New-Object System.Collections.ArrayList # >>>>>>>>>> Start # SD 1.5 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/v1-5-pruned-emaonly.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/animefull-final-pruned.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/nai1-artist_all_in_one_merge.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/Counterfeit-V3.0_fp16.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cetusMix_Whalefall2.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/ex2K_sse2.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/kohakuV5_rev2.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinamix_meinaV11.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/oukaStar_10.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/rabbit_v6.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/sweetSugarSyndrome_rev15.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/AnythingV5Ink_ink.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/meinapastel_v6Pastel.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/qteamixQ_omegaFp16.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors`", `"SD 1.5`", `"Stable-diffusion`")) | Out-Null # SD 2.1 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/v2-1_768-ema-pruned.safetensors`", `"SD 2.1`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-1-4-anime_e2.ckpt`", `"SD 2.1`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sd_2.1/wd-mofu-fp16.safetensors`", `"SD 2.1`", `"Stable-diffusion`")) | Out-Null # SDXL `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-lora/resolve/master/sdxl/sd_xl_offset_example-lora_1.0.safetensors`", `"SDXL`", `"Lora`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/cosxl_edit.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0-base.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-3.1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-opt.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animagine-xl-4.0-zero.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/holodayo-xl-2.1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kivotos-xl-2.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/clandestine-xl-1.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/UrangDiffusion-1.1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/RaeDiffusion-XL-v2.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sd_xl_anime_V52.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-delta-rev1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/kohaku-xl-zeta.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/starryXLV52_v52.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v20.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/heartOfAppleXL_v30.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v10.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/sanaexlAnimeV10_v11.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v1.1.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/Illustrious-XL-v2.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/miaomiaoHarem_v15a.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/waiNSFWIllustrious_v80.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tIllunai3_v4.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/pdForAnime_v20.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/omegaPonyXLAnime_v20.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animeIllustDiffusion_v061.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifuDiffusion_v10.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/artiwaifu-diffusion-v2.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/AnythingXL_xl.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/abyssorangeXLElse_v10.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/animaPencilXL_v200.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/bluePencilXL_v401.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/nekorayxl_v06W3.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-model/resolve/master/sdxl_1.0/CounterfeitXL-V1.0.safetensors`", `"SDXL`", `"Stable-diffusion`")) | Out-Null # SD 3 `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3_medium_incl_clips_t5xxlfp8.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_fp8_scaled.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_large_turbo.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/emi3.safetensors`", `"SD 3`", `"Stable-diffusion`")) | Out-Null # SD 3 Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_g.safetensors`", `"SD 3 Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/clip_l.safetensors`", `"SD 3 Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp16.safetensors`", `"SD 3 Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"SD 3 Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-3-model/resolve/master/text_encoders/t5xxl_fp8_e4m3fn_scaled.safetensors`", `"SD 3 Text Encoder`", `"text_encoder`")) | Out-Null # FLUX `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-fp8.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux_dev_fp8_scaled_diffusion_model.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4-v2.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-bnb-nf4.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q2_K.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q3_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_1.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q4_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_1.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q5_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q6_K.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-Q8_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-F16.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-fp8.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q2_K.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q3_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_1.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q4_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_1.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q5_K_S.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q6_K.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-Q8_0.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-schnell-F16.gguf`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/ashen0209-flux1-dev2pro.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/jimmycarter-LibreFLUX.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/nyanko7-flux-dev-de-distill.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/shuttle-3-diffusion.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev_fp8_scaled.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-krea-dev.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-dev-kontext_fp8_scaled.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/flux1-kontext-dev.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_1/chroma-unlocked-v50.safetensors`", `"FLUX`", `"Stable-diffusion`")) | Out-Null # FLUX Text Encoder `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/clip_l.safetensors`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp16.safetensors`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5xxl_fp8_e4m3fn.safetensors`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_L.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q3_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q4_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_M.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q5_K_S.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q6_K.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-Q8_0.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f16.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_text_encoders/t5-v1_1-xxl-encoder-f32.gguf`", `"FLUX Text Encoder`", `"text_encoder`")) | Out-Null # FLUX VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/flux-model/resolve/master/flux_vae/ae.safetensors`", `"FLUX VAE`", `"VAE`")) | Out-Null # SD 1.5 VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"VAE`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors`", `"SD 1.5 VAE`", `"VAE`")) | Out-Null # SDXL VAE `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_vae.safetensors`", `"SDXL VAE`", `"VAE`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/sdxl_1.0/sdxl_fp16_fix_vae.safetensors`", `"SDXL VAE`", `"VAE`")) | Out-Null # VAE approx `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/model.pt`", `"VAE approx`", `"VAE-approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sdxl.pt`", `"VAE approx`", `"VAE-approx`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-vae/resolve/master/vae-approx/vaeapprox-sd3.pt`", `"VAE approx`", `"VAE-approx`")) | Out-Null # Upscale `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/Codeformer/codeformer-v0.1.0.pth`", `"Upscale`", `"Codeformer`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x2.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x3.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_2_x4.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x2.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x3.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_S_x4.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x2.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x3.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_light_x4.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x2.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x3.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/DAT/DAT_x4.pth`", `"Upscale`", `"DAT`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/16xPSNR.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x-ITF-SkinDiffDetail-Lite-v1.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-BrightenRedux_200k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKD-YandereInpaint_375000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NMKDDetoon_97500_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Poisson-Detailed_108000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/1x_NoiseToner-Uniform-Detailed_100000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x-UltraSharp.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4xPSNR.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_CountryRoads_377000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Fatality_Comix_260000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Siax_200k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-Artisoftject_210000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere-Lite_280k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-UltraYandere_300k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKD-YandereNeoXL_200k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NMKDSuperscale_Artisoft_120000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_NickelbackFS_72000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Nickelback_70000G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_RealisticRescaler_100000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_Valar_v1.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_fatal_Anime_500000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/4x_foolhardy_Remacri.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8xPSNR.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Superscale_150000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/8x_NMKD-Typescale_175k.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/A_ESRGAN_Single.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGAN.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRGANx2.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/BSRNet.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/ESRGAN_4x.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/LADDIER1_282500_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Neutral_115000_swaG.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharp_101000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/4x_UniversalUpscalerV2-Sharper_103000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Detailed_155000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/UniversalUpscaler/Legacy/4x_UniversalUpscaler-Soft_190000_G.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/WaifuGAN_v3_30000.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/lollypop.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/ESRGAN/sudo_rife4_269.662_testV1_scale1.pth`", `"Upscale`", `"ESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.3.pth`", `"Upscale`", `"GFPGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/GFPGANv1.4.pth`", `"Upscale`", `"GFPGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/detection_Resnet50_Final.pth`", `"Upscale`", `"GFPGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_bisenet.pth`", `"Upscale`", `"GFPGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/GFPGAN/parsing_parsenet.pth`", `"Upscale`", `"GFPGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus.pth`", `"Upscale`", `"RealESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth`", `"Upscale`", `"RealESRGAN`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x2_GAN-with-dict-keys-params-and-params_ema.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X2_64.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_ClassicalSR_X4_64.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_CompressedSR_X4_48.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth`", `"Upscale`", `"SwinIR`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-upscaler-models/resolve/master/SwinIR/SwinIR_4x.pth`", `"Upscale`", `"SwinIR`")) | Out-Null # Embedding `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/EasyNegativeV2.safetensors`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist-anime.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-artist.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-hands-5.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad-image-v2-39000.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/bad_prompt_version2.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/ng_deepnegative_v1_75t.pt`", `"Embedding`", `"../embeddings`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd-embeddings/resolve/master/sd_1.5/verybadimagenegative_v1.3.pt`", `"Embedding`", `"../embeddings`")) | Out-Null # SD 1.5 ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_ip2p_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11e_sd15_shuffle_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1e_sd15_tile_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11f1p_sd15_depth_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_canny_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_inpaint_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_lineart_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_mlsd_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_normalbae_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_openpose_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_scribble_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_seg_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15_softedge_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v11p_sd15s2_lineart_anime_fp16.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_brightness.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_illumination.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/control_v1p_sd15_qrcode_monster.safetensors`", `"SD 1.5 ControlNet`", `"ControlNet`")) | Out-Null # SDXL ControlNet `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/monster-labs-control_v1p_sdxl_qrcode_monster.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/mistoLine_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/destitech-controlnet-inpaint-dreamer-sdxl.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/control-lora/resolve/master/control-lora-recolor-rank128-sdxl.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/xinsir-controlnet-union-sdxl-1.0-promax.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/kohakuXLControlnet_canny.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/animagineXL40_canny.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLCanny_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineart_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLDepth_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLSoftedge_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLLineartRrealistic_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLShuffle_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLOpenPose_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLTile_v10.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv0.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_canny_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_depth_midas_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_inpainting_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/illustriousXLv1.1_tile_fp16.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsCanny.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidas.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartAnime.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsNormalMidas.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsSoftedgeHed.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsMangaLine.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsLineartRealistic.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsDepthMidasV11.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribbleHed.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsScribblePidinet.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_openposeModel.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/noobaiXLControlnet_epsTile.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/sd_control_collection/resolve/master/NoobAI_Inpainting_ControlNet.safetensors`", `"SDXL ControlNet`", `"ControlNet`")) | Out-Null # CLIP Vision `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_g.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_h.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1_annotator/resolve/master/clip_vision/clip_vitl.pth`", `"CLIP Vision`", `"clip_vision`")) | Out-Null # IP Adapter `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15.pth`", `"SD 1.5 IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_light.pth`", `"SD 1.5 IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_plus.pth`", `"SD 1.5 IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sd15_vit-G.safetensors`", `"SD 1.5 IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter-plus_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl.safetensors`", `"SDXL IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/noobIPAMARK1_mark1.safetensors`", `"SDXL IP Adapter`", `"ControlNet`")) | Out-Null `$model_list.Add(@(`"https://modelscope.cn/models/licyks/controlnet_v1.1/resolve/master/ip-adapter_sdxl_vit-h.safetensors`", `"SDXL IP Adapter`", `"ControlNet`")) | Out-Null # <<<<<<<<<< End return `$model_list } # 展示模型列表 function List-Model(`$model_list) { `$count = 0 `$point = `"None`" Print-Msg `"可下载的模型列表`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$point -ne `$ver) { Write-Host Write-Host `"- `$ver`" -ForegroundColor Cyan } `$point = `$ver Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan } Write-Host Write-Host `"关于部分模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md`" Write-Host `"-----------------------------------------------------`" } # 列出要下载的模型 function List-Download-Task (`$download_list) { Print-Msg `"当前选择要下载的模型`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan Write-Host for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$type = `$content[2] Write-Host `"- `" -ForegroundColor Yellow -NoNewline Write-Host `"`$name`" -ForegroundColor White -NoNewline Write-Host `" (`$type) `" -ForegroundColor Cyan } Write-Host Write-Host `"总共要下载的模型数量: `$(`$i)`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } # 模型下载器 function Model-Downloader (`$download_list) { `$sum = `$download_list.Count for (`$i = 0; `$i -lt `$download_list.Count; `$i++) { `$content = `$download_list[`$i] `$name = `$content[0] `$url = `$content[1] `$type = `$content[2] `$path = ([System.IO.Path]::GetFullPath(`$content[3])) `$model_name = Split-Path `$url -Leaf Print-Msg `"[`$(`$i + 1)/`$sum] 下载 `$name (`$type) 模型到 `$path 中`" aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x 16 -k 1M `$url -d `"`$path`" -o `"`$model_name`" if (`$?) { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载成功`" } else { Print-Msg `"[`$(`$i + 1)/`$sum] `$name (`$type) 下载失败`" } } } # 获取用户输入 function Get-User-Input { return (Read-Host `"=========================================>`").Trim() } # 搜索模型列表 function Search-Model-List (`$model_list, `$key) { `$count = 0 `$result = 0 Print-Msg `"模型列表搜索结果`" Write-Host `"-----------------------------------------------------`" Write-Host `"模型序号`" -ForegroundColor Yellow -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型名称`" -ForegroundColor White -NoNewline Write-Host `" | `" -NoNewline Write-Host `"模型种类`" -ForegroundColor Cyan for (`$i = 0; `$i -lt `$model_list.Count; `$i++) { `$content = `$model_list[`$i] `$count += 1 `$url = `$content[0] # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) `$name = [System.IO.Path]::GetFileName(`$url) `$ver = `$content[1] if (`$name -like `"*`$key*`") { Write-Host `" - `${count}、`" -ForegroundColor Yellow -NoNewline Write-Host `"`$name `" -ForegroundColor White -NoNewline Write-Host `"(`$ver)`" -ForegroundColor Cyan `$result += 1 } } Write-Host Write-Host `"搜索 `$key 得到的结果数量: `$result`" -ForegroundColor White Write-Host `"-----------------------------------------------------`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy if (`$BuildMode) { Print-Msg `"SD WebUI Installer 构建模式已启用, 跳过 SD WebUI Installer 更新检查`" } else { Check-Stable-Diffusion-WebUI-Installer-Update } Check-Aria2-Version if (!(Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$PSScriptRoot\`$Env:CORE_PREFIX 未找到, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" Read-Host | Out-Null return } `$to_exit = 0 `$go_to = 0 `$has_error = `$false `$model_list = Get-Model-List `$download_list = New-Object System.Collections.ArrayList `$after_list_model_option = `"`" while (`$True) { List-Model `$model_list switch (`$after_list_model_option) { list_search_result { Search-Model-List `$model_list `$find_key break } display_input_error { Print-Msg `"输入有误, 请重试`" } Default { break } } `$after_list_model_option = `"`" Print-Msg `"请选择要下载的模型`" Print-Msg `"提示:`" Print-Msg `"1. 输入数字后回车`" Print-Msg `"2. 如果需要下载多个模型, 可以输入多个数字并使用空格隔开`" Print-Msg `"3. 输入 search 可以进入列表搜索模式, 可搜索列表中已有的模型`" Print-Msg `"4. 输入 exit 退出模型下载脚本`" if (`$BuildMode) { `$arg = `$BuildWitchModel `$go_to = 1 } else { `$arg = Get-User-Input } switch (`$arg) { exit { `$to_exit = 1 `$go_to = 1 break } search { Print-Msg `"请输入要从模型列表搜索的模型名称`" `$find_key = Get-User-Input `$after_list_model_option = `"list_search_result`" } Default { `$arg = `$arg.Split() # 拆分成列表 ForEach (`$i in `$arg) { try { # 检测输入是否符合列表 `$i = [int]`$i if ((!((`$i -ge 1) -and (`$i -le `$model_list.Count)))) { `$has_error = `$true break } # 创建下载列表 `$content = `$model_list[(`$i - 1)] `$url = `$content[0] # 下载链接 `$type = `$content[1] # 类型 `$path = `"`$PSScriptRoot/`$Env:CORE_PREFIX/models/`$(`$content[2])`" # 模型放置路径 # `$name = [System.IO.Path]::GetFileNameWithoutExtension(`$url) # 模型名称 `$name = [System.IO.Path]::GetFileName(`$url) # 模型名称 `$task = @(`$name, `$url, `$type, `$path) # 检查重复元素 `$has_duplicate = `$false for (`$j = 0; `$j -lt `$download_list.Count; `$j++) { `$task_tmp = `$download_list[`$j] `$comparison = Compare-Object -ReferenceObject `$task_tmp -DifferenceObject `$task if (`$comparison.Count -eq 0) { `$has_duplicate = `$true break } } if (!(`$has_duplicate)) { `$download_list.Add(`$task) | Out-Null # 添加列表 } `$has_duplicate = `$false } catch { `$has_error = `$true break } } if (`$has_error) { `$after_list_model_option = `"display_input_error`" `$has_error = `$false `$download_list.Clear() # 出现错误时清除下载列表 break } `$go_to = 1 break } } if (`$go_to -eq 1) { break } } if (`$to_exit -eq 1) { Print-Msg `"退出模型下载脚本`" Read-Host | Out-Null exit 0 } List-Download-Task `$download_list Print-Msg `"是否确认下载模型?`" Print-Msg `"提示: 输入 yes 确认或 no 取消 (默认为 no)`" if (`$BuildMode) { `$download_operate = `"yes`" } else { `$download_operate = Get-User-Input } if (`$download_operate -eq `"yes`" -or `$download_operate -eq `"y`" -or `$download_operate -eq `"YES`" -or `$download_operate -eq `"Y`") { Model-Downloader `$download_list } Print-Msg `"退出模型下载脚本`" if (!(`$BuildMode)) { Read-Host | Out-Null } } ################### Main ".Trim() if (Test-Path "$InstallPath/download_models.ps1") { Print-Msg "更新 download_models.ps1 中" } else { Print-Msg "生成 download_models.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/download_models.ps1" -Value $content } # SD WebUI Installer 设置脚本 function Write-Stable-Diffusion-WebUI-Installer-Settings-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableProxys, [string]`$UseCustomProxy ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 消息输出 function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # 获取代理设置 function Get-Proxy-Setting { if (Test-Path `"`$PSScriptRoot/disable_proxy.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/proxy.txt`") { return `"启用 (使用自定义代理服务器: `$(Get-Content `"`$PSScriptRoot/proxy.txt`"))`" } else { return `"启用 (使用系统代理)`" } } # 获取 Python 包管理器设置 function Get-Python-Package-Manager-Setting { if (Test-Path `"`$PSScriptRoot/disable_uv.txt`") { return `"Pip`" } else { return `"uv`" } } # 获取 HuggingFace 镜像源设置 function Get-HuggingFace-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/hf_mirror.txt`") { return `"启用 (自定义镜像源: `$(Get-Content `"`$PSScriptRoot/hf_mirror.txt`"))`" } else { return `"启用 (默认镜像源)`" } } # 获取 Github 镜像源设置 function Get-Github-Mirror-Setting { if (Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") { return `"禁用`" } elseif (Test-Path `"`$PSScriptRoot/gh_mirror.txt`") { return `"启用 (使用自定义镜像源: `$(Get-Content `"`$PSScriptRoot/gh_mirror.txt`"))`" } else { return `"启用 (自动选择镜像源)`" } } # 获取 SD WebUI Installer 自动检测更新设置 function Get-Stable-Diffusion-WebUI-Installer-Auto-Check-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取 SD WebUI Installer 自动应用更新设置 function Get-Stable-Diffusion-WebUI-Installer-Auto-Apply-Update-Setting { if (Test-Path `"`$PSScriptRoot/disable_auto_apply_update.txt`") { return `"禁用`" } else { return `"启用`" } } # 获取启动参数设置 function Get-Launch-Args-Setting { if (Test-Path `"`$PSScriptRoot/launch_args.txt`") { return Get-Content `"`$PSScriptRoot/launch_args.txt`" } else { return `"无`" } } # 获取自动创建快捷启动方式 function Get-Auto-Set-Launch-Shortcut-Setting { if (Test-Path `"`$PSScriptRoot/enable_shortcut.txt`") { return `"启用`" } else { return `"禁用`" } } # 获取 PyPI 镜像源配置 function Get-PyPI-Mirror-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 Stable Diffusion WebUI 运行环境检测配置 function Get-Stable-Diffusion-WebUI-Env-Check-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_check_env.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取 CUDA 内存分配器设置 function Get-PyTorch-CUDA-Memory-Alloc-Setting { if (!(Test-Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`")) { return `"启用`" } else { return `"禁用`" } } # 获取路径前缀设置 function Get-Core-Prefix-Setting { if (Test-Path `"`$PSScriptRoot/core_prefix.txt`") { return `"自定义 (使用自定义路径前缀: `$(Get-Content `"`$PSScriptRoot/core_prefix.txt`"))`" } else { return `"自动`" } } # 获取用户输入 function Get-User-Input { return (Read-Host `"=========================================>`").Trim() } # 代理设置 function Update-Proxy-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用代理 (使用系统代理)`" Print-Msg `"2. 启用代理 (手动设置代理服务器)`" Print-Msg `"3. 禁用代理`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"启用代理成功, 当设置了系统代理后将自动读取并使用`" break } 2 { Print-Msg `"请输入代理服务器地址`" Print-Msg `"提示: 代理地址可查看代理软件获取, 代理地址的格式如 http://127.0.0.1:10809、socks://127.0.0.1:7890 等, 输入后回车保存`" `$proxy_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/proxy.txt`" -Value `$proxy_address Print-Msg `"启用代理成功, 使用的代理服务器为: `$proxy_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_proxy.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/proxy.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用代理成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Python 包管理器设置 function Update-Python-Package-Manager-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前使用的 Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 使用 uv 作为 Python 包管理器`" Print-Msg `"2. 使用 Pip 作为 Python 包管理器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_uv.txt`" -Force -Recurse 2> `$null Print-Msg `"设置 uv 作为 Python 包管理器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_uv.txt`" -Force > `$null Print-Msg `"设置 Pip 作为 Python 包管理器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 HuggingFace 镜像源 function Update-HuggingFace-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 HuggingFace 镜像源 (使用默认镜像源)`" Print-Msg `"2. 启用 HuggingFace 镜像源 (使用自定义 HuggingFace 镜像源)`" Print-Msg `"3. 禁用 HuggingFace 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 HuggingFace 镜像成功, 使用默认的 HuggingFace 镜像源 (https://hf-mirror.com)`" break } 2 { Print-Msg `"请输入 HuggingFace 镜像源地址`" Print-Msg `"提示: 可用的 HuggingFace 镜像源有:`" Print-Msg `" https://hf-mirror.com`" Print-Msg `" https://huggingface.sukaka.top`" Print-Msg `"提示: 输入 HuggingFace 镜像源地址后回车保存`" `$huggingface_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/hf_mirror.txt`" -Value `$huggingface_mirror_address Print-Msg `"启用 HuggingFace 镜像成功, 使用的 HuggingFace 镜像源为: `$huggingface_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_hf_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/hf_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 HuggingFace 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 设置 Github 镜像源 function Update-Github-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Github 镜像源 (自动检测可用的 Github 镜像源并使用)`" Print-Msg `"2. 启用 Github 镜像源 (使用自定义 Github 镜像源)`" Print-Msg `"3. 禁用 Github 镜像源`" Print-Msg `"4. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Github 镜像成功, 在更新 Stable Diffusion WebUI 时将自动检测可用的 Github 镜像源并使用`" break } 2 { Print-Msg `"请输入 Github 镜像源地址`" Print-Msg `"提示: 可用的 Github 镜像源有: `" Print-Msg `" https://ghfast.top/https://github.com`" Print-Msg `" https://mirror.ghproxy.com/https://github.com`" Print-Msg `" https://ghproxy.net/https://github.com`" Print-Msg `" https://gh.api.99988866.xyz/https://github.com`" Print-Msg `" https://ghproxy.1888866.xyz/github.com`" Print-Msg `" https://slink.ltd/https://github.com`" Print-Msg `" https://github.boki.moe/github.com`" Print-Msg `" https://github.moeyy.xyz/https://github.com`" Print-Msg `" https://gh-proxy.net/https://github.com`" Print-Msg `" https://gh-proxy.ygxz.in/https://github.com`" Print-Msg `" https://wget.la/https://github.com`" Print-Msg `" https://kkgithub.com`" Print-Msg `" https://gh-proxy.com/https://github.com`" Print-Msg `" https://ghps.cc/https://github.com`" Print-Msg `" https://gh.idayer.com/https://github.com`" Print-Msg `" https://gitclone.com/github.com`" Print-Msg `"提示: 输入 Github 镜像源地址后回车保存`" `$github_mirror_address = Get-User-Input Remove-Item -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force -Recurse 2> `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/gh_mirror.txt`" -Value `$github_mirror_address Print-Msg `"启用 Github 镜像成功, 使用的 Github 镜像源为: `$github_mirror_address`" break } 3 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_gh_mirror.txt`" -Force > `$null Remove-Item -Path `"`$PSScriptRoot/gh_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用 Github 镜像成功`" break } 4 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD WebUI Installer 自动检查更新设置 function Update-Stable-Diffusion-WebUI-Installer-Auto-Check-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD WebUI Installer 自动检测更新设置: `$(Get-Stable-Diffusion-WebUI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD WebUI Installer 自动更新检查`" Print-Msg `"2. 禁用 SD WebUI Installer 自动更新检查`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" Print-Msg `"警告: 当 SD WebUI Installer 有重要更新(如功能性修复)时, 禁用自动更新检查后将得不到及时提示`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD WebUI Installer 自动更新检查成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_update.txt`" -Force > `$null Print-Msg `"禁用 SD WebUI Installer 自动更新检查成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # SD WebUI Installer 自动应用更新设置 function Update-Stable-Diffusion-WebUI-Installer-Auto-Apply-Update-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 SD WebUI Installer 自动应用更新设置: `$(Get-Stable-Diffusion-WebUI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 SD WebUI Installer 自动应用更新`" Print-Msg `"2. 禁用 SD WebUI Installer 自动应用更新`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 SD WebUI Installer 自动应用更新成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_auto_apply_update.txt`" -Force > `$null Print-Msg `"禁用 SD WebUI Installer 自动应用更新成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Stable Diffusion WebUI 启动参数设置 function Update-Stable-Diffusion-WebUI-Launch-Args-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Stable Diffusion WebUI 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 设置 Stable Diffusion WebUI 启动参数`" Print-Msg `"2. 删除 Stable Diffusion WebUI 启动参数`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入 Stable Diffusion WebUI 启动参数`" Print-Msg `"提示: 保存启动参数后原有的启动参数将被覆盖, Stable Diffusion WebUI 可用的启动参数可阅读: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Command-Line-Arguments-and-Settings`" Print-Msg `"输入启动参数后回车保存`" `$stable_diffusion_webui_launch_args = Get-User-Input Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/launch_args.txt`" -Value `$stable_diffusion_webui_launch_args Print-Msg `"设置 Stable Diffusion WebUI 启动参数成功, 使用的 Stable Diffusion WebUI 启动参数为: `$stable_diffusion_webui_launch_args`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/launch_args.txt`" -Force -Recurse 2> `$null Print-Msg `"删除 Stable Diffusion WebUI 启动参数成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 自动创建 Stable Diffusion WebUI 快捷启动方式设置 function Auto-Set-Launch-Shortcut-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动创建 Stable Diffusion WebUI 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动创建 Stable Diffusion WebUI 快捷启动方式`" Print-Msg `"2. 禁用自动创建 Stable Diffusion WebUI 快捷启动方式`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { New-Item -ItemType File -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force > `$null Print-Msg `"启用自动创建 Stable Diffusion WebUI 快捷启动方式成功`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/enable_shortcut.txt`" -Force -Recurse 2> `$null Print-Msg `"禁用自动创建 Stable Diffusion WebUI 快捷启动方式成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # PyPI 镜像源设置 function PyPI-Mirror-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 PyPI 镜像源`" Print-Msg `"2. 禁用 PyPI 镜像源`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 PyPI 镜像源成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_pypi_mirror.txt`" -Force > `$null Print-Msg `"禁用 PyPI 镜像源成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # CUDA 内存分配器设置 function PyTorch-CUDA-Memory-Alloc-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用自动设置 CUDA 内存分配器`" Print-Msg `"2. 禁用自动设置 CUDA 内存分配器`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动设置 CUDA 内存分配器成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_set_pytorch_cuda_memory_alloc.txt`" -Force > `$null Print-Msg `"禁用自动设置 CUDA 内存分配器成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # Stable Diffusion WebUI 运行环境检测设置 function Stable-Diffusion-WebUI-Env-Check-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前 Stable Diffusion WebUI 运行环境检测设置: `$(Get-Stable-Diffusion-WebUI-Env-Check-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 启用 Stable Diffusion WebUI 运行环境检测`" Print-Msg `"2. 禁用 Stable Diffusion WebUI 运行环境检测`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Remove-Item -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force -Recurse 2> `$null Print-Msg `"启用 Stable Diffusion WebUI 运行环境检测成功`" break } 2 { New-Item -ItemType File -Path `"`$PSScriptRoot/disable_check_env.txt`" -Force > `$null Print-Msg `"禁用 Stable Diffusion WebUI 运行环境检测成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 内核路径前缀设置 function Update-Core-Prefix-Setting { while (`$true) { `$go_to = 0 Print-Msg `"当前内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"可选操作:`" Print-Msg `"1. 配置自定义路径前缀`" Print-Msg `"2. 启用自动选择路径前缀`" Print-Msg `"3. 返回`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Print-Msg `"请输入自定义内核路径前缀`" Print-Msg `"提示: 路径前缀为内核在当前脚本目录中的名字 (也可以通过绝对路径指定当前脚本目录外的内核), 输入后回车保存`" `$custom_core_prefix = Get-User-Input `$origin_path = `$origin_core_prefix `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$custom_core_prefix)) { Print-Msg `"将绝对路径转换为内核路径前缀中`" `$from_path = `$PSScriptRoot `$to_path = `$custom_core_prefix `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$custom_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$origin_path -> `$custom_core_prefix`" } Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/core_prefix.txt`" -Value `$custom_core_prefix Print-Msg `"自定义内核路径前缀成功, 使用的路径前缀为: `$custom_core_prefix`" break } 2 { Remove-Item -Path `"`$PSScriptRoot/core_prefix.txt`" -Force -Recurse 2> `$null Print-Msg `"启用自动选择内核路径前缀成功`" break } 3 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" } } if (`$go_to -eq 1) { break } } } # 检查 SD WebUI Installer 更新 function Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$PSScriptRoot/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -gt `$SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 有新版本可用`" Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$PSScriptRoot`" -UseUpdateMode `$raw_params = `$script:MyInvocation.Line -replace `"^.*\.ps1[\s]*`", `"`" Print-Msg `"更新结束, 重新启动 SD WebUI Installer 管理脚本中, 使用的命令行参数: `$raw_params`" Invoke-Expression `"& ```"`$PSCommandPath```" `$raw_params`" exit 0 } else { Print-Msg `"SD WebUI Installer 已是最新版本`" } } # 检查环境完整性 function Check-Env { Print-Msg `"检查环境完整性中`" `$broken = 0 if ((Test-Path `"`$PSScriptRoot/python/python.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/python.exe`")) { `$python_status = `"已安装`" } else { `$python_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/git.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/git.exe`")) { `$git_status = `"已安装`" } else { `$git_status = `"未安装`" `$broken = 1 } python -m pip show uv --quiet 2> `$null if (`$?) { `$uv_status = `"已安装`" } else { `$uv_status = `"未安装`" `$broken = 1 } if ((Test-Path `"`$PSScriptRoot/git/bin/aria2c.exe`") -or (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin/aria2c.exe`")) { `$aria2_status = `"已安装`" } else { `$aria2_status = `"未安装`" `$broken = 1 } if (Test-Path `"`$PSScriptRoot/`$Env:CORE_PREFIX/launch.py`") { `$stable_diffusion_webui_status = `"已安装`" } else { `$stable_diffusion_webui_status = `"未安装`" `$broken = 1 } python -m pip show torch --quiet 2> `$null if (`$?) { `$torch_status = `"已安装`" } else { `$torch_status = `"未安装`" `$broken = 1 } python -m pip show xformers --quiet 2> `$null if (`$?) { `$xformers_status = `"已安装`" } else { `$xformers_status = `"未安装`" `$broken = 1 } Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境:`" Print-Msg `"Python: `$python_status`" Print-Msg `"Git: `$git_status`" Print-Msg `"uv: `$uv_status`" Print-Msg `"Aria2: `$aria2_status`" Print-Msg `"PyTorch: `$torch_status`" Print-Msg `"xFormers: `$xformers_status`" Print-Msg `"stable-diffusion-webui: `$stable_diffusion_webui_status`" Print-Msg `"-----------------------------------------------------`" if (`$broken -eq 1) { Print-Msg `"检测到环境出现组件缺失, 可尝试运行 SD WebUI Installer 进行安装`" } else { Print-Msg `"当前环境无缺失组件`" } } # 查看 SD WebUI Installer 文档 function Get-Stable-Diffusion-WebUI-Installer-Help-Docs { Print-Msg `"调用浏览器打开 SD WebUI Installer 文档中`" Start-Process `"https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md`" } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy while (`$true) { `$go_to = 0 Print-Msg `"-----------------------------------------------------`" Print-Msg `"当前环境配置:`" Print-Msg `"代理设置: `$(Get-Proxy-Setting)`" Print-Msg `"Python 包管理器: `$(Get-Python-Package-Manager-Setting)`" Print-Msg `"HuggingFace 镜像源设置: `$(Get-HuggingFace-Mirror-Setting)`" Print-Msg `"Github 镜像源设置: `$(Get-Github-Mirror-Setting)`" Print-Msg `"SD WebUI Installer 自动检查更新: `$(Get-Stable-Diffusion-WebUI-Installer-Auto-Check-Update-Setting)`" Print-Msg `"SD WebUI Installer 自动应用更新: `$(Get-Stable-Diffusion-WebUI-Installer-Auto-Apply-Update-Setting)`" Print-Msg `"Stable Diffusion WebUI 启动参数: `$(Get-Launch-Args-Setting)`" Print-Msg `"自动创建 Stable Diffusion WebUI 快捷启动方式设置: `$(Get-Auto-Set-Launch-Shortcut-Setting)`" Print-Msg `"PyPI 镜像源设置: `$(Get-PyPI-Mirror-Setting)`" Print-Msg `"自动设置 CUDA 内存分配器设置: `$(Get-PyTorch-CUDA-Memory-Alloc-Setting)`" Print-Msg `"Stable Diffusion WebUI 运行环境检测设置: `$(Get-Stable-Diffusion-WebUI-Env-Check-Setting)`" Print-Msg `"Stable Diffusion WebUI 内核路径前缀设置: `$(Get-Core-Prefix-Setting)`" Print-Msg `"-----------------------------------------------------`" Print-Msg `"可选操作:`" Print-Msg `"1. 进入代理设置`" Print-Msg `"2. 进入 Python 包管理器设置`" Print-Msg `"3. 进入 HuggingFace 镜像源设置`" Print-Msg `"4. 进入 Github 镜像源设置`" Print-Msg `"5. 进入 SD WebUI Installer 自动检查更新设置`" Print-Msg `"6. 进入 SD WebUI Installer 自动应用更新设置`" Print-Msg `"7. 进入 Stable Diffusion WebUI 启动参数设置`" Print-Msg `"8. 进入自动创建 Stable Diffusion WebUI 快捷启动方式设置`" Print-Msg `"9. 进入 PyPI 镜像源设置`" Print-Msg `"10. 进入自动设置 CUDA 内存分配器设置`" Print-Msg `"11. 进入 Stable Diffusion WebUI 运行环境检测设置`" Print-Msg `"12. 进入 Stable Diffusion WebUI 内核路径前缀设置`" Print-Msg `"13 更新 SD WebUI Installer 管理脚本`" Print-Msg `"14. 检查环境完整性`" Print-Msg `"15. 查看 SD WebUI Installer 文档`" Print-Msg `"16. 退出 SD WebUI Installer 设置`" Print-Msg `"提示: 输入数字后回车`" `$arg = Get-User-Input switch (`$arg) { 1 { Update-Proxy-Setting break } 2 { Update-Python-Package-Manager-Setting break } 3 { Update-HuggingFace-Mirror-Setting break } 4 { Update-Github-Mirror-Setting break } 5 { Update-Stable-Diffusion-WebUI-Installer-Auto-Check-Update-Setting break } 6 { Update-Stable-Diffusion-WebUI-Installer-Auto-Apply-Update-Setting break } 7 { Update-Stable-Diffusion-WebUI-Launch-Args-Setting break } 8 { Auto-Set-Launch-Shortcut-Setting break } 9 { PyPI-Mirror-Setting break } 10 { PyTorch-CUDA-Memory-Alloc-Setting break } 11 { Stable-Diffusion-WebUI-Env-Check-Setting break } 12 { Update-Core-Prefix-Setting break } 13 { Check-Stable-Diffusion-WebUI-Installer-Update break } 14 { Check-Env break } 15 { Get-Stable-Diffusion-WebUI-Installer-Help-Docs break } 16 { `$go_to = 1 break } Default { Print-Msg `"输入有误, 请重试`" break } } if (`$go_to -eq 1) { Print-Msg `"退出 SD WebUI Installer 设置`" break } } } ################### Main Read-Host | Out-Null ".Trim() if (Test-Path "$InstallPath/settings.ps1") { Print-Msg "更新 settings.ps1 中" } else { Print-Msg "生成 settings.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/settings.ps1" -Value $content } # 虚拟环境激活脚本 function Write-Env-Activate-Script { $content = " param ( [switch]`$Help, [string]`$CorePrefix, [switch]`$DisablePyPIMirror, [switch]`$DisableGithubMirror, [string]`$UseCustomGithubMirror, [switch]`$DisableProxy, [string]`$UseCustomProxy, [switch]`$DisableHuggingFaceMirror, [string]`$UseCustomHuggingFaceMirror ) & { `$prefix_list = @(`"core`", `"stable-diffusion-webui`", `"stable-diffusion-webui-forge`", `"stable-diffusion-webui-reForge`", `"sd-webui-forge-classic`", `"stable-diffusion-webui-amdgpu`", `"automatic`", `"sd_webui`", `"sd_webui_forge`", `"sd-webui-aki-v4.10`", `"sd-webui-aki-v4.11.1-cu128`", `"sd-webui-forge-aki-v1.0`") if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } `$origin_core_prefix = `$origin_core_prefix.Trim('/').Trim('\') if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix `$from_uri = New-Object System.Uri(`$PSScriptRoot.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')) `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') } `$Env:CORE_PREFIX = `$origin_core_prefix return } ForEach (`$i in `$prefix_list) { if (Test-Path `"`$PSScriptRoot/`$i`") { `$Env:CORE_PREFIX = `$i return } } `$Env:CORE_PREFIX = `"core`" } # SD WebUI Installer 版本和检查更新间隔 `$Env:SD_WEBUI_INSTALLER_VERSION = $SD_WEBUI_INSTALLER_VERSION `$Env:UPDATE_TIME_SPAN = $UPDATE_TIME_SPAN # PyPI 镜像源 `$PIP_INDEX_ADDR = `"$PIP_INDEX_ADDR`" `$PIP_INDEX_ADDR_ORI = `"$PIP_INDEX_ADDR_ORI`" `$PIP_EXTRA_INDEX_ADDR = `"$PIP_EXTRA_INDEX_ADDR`" `$PIP_EXTRA_INDEX_ADDR_ORI = `"$PIP_EXTRA_INDEX_ADDR_ORI`" `$PIP_FIND_ADDR = `"$PIP_FIND_ADDR`" `$PIP_FIND_ADDR_ORI = `"$PIP_FIND_ADDR_ORI`" `$USE_PIP_MIRROR = if ((!(Test-Path `"`$PSScriptRoot/disable_pypi_mirror.txt`")) -and (!(`$DisablePyPIMirror))) { `$true } else { `$false } `$PIP_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_INDEX_ADDR } else { `$PIP_INDEX_ADDR_ORI } `$PIP_EXTRA_INDEX_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_EXTRA_INDEX_ADDR } else { `$PIP_EXTRA_INDEX_ADDR_ORI } `$PIP_FIND_MIRROR = if (`$USE_PIP_MIRROR) { `$PIP_FIND_ADDR } else { `$PIP_FIND_ADDR_ORI } `$PIP_FIND_MIRROR_CU121 = `"$PIP_FIND_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_PYTORCH = `"$PIP_EXTRA_INDEX_MIRROR_PYTORCH`" `$PIP_EXTRA_INDEX_MIRROR_CPU = `"$PIP_EXTRA_INDEX_MIRROR_CPU`" `$PIP_EXTRA_INDEX_MIRROR_XPU = `"$PIP_EXTRA_INDEX_MIRROR_XPU`" `$PIP_EXTRA_INDEX_MIRROR_CU118 = `"$PIP_EXTRA_INDEX_MIRROR_CU118`" `$PIP_EXTRA_INDEX_MIRROR_CU121 = `"$PIP_EXTRA_INDEX_MIRROR_CU121`" `$PIP_EXTRA_INDEX_MIRROR_CU124 = `"$PIP_EXTRA_INDEX_MIRROR_CU124`" `$PIP_EXTRA_INDEX_MIRROR_CU126 = `"$PIP_EXTRA_INDEX_MIRROR_CU126`" `$PIP_EXTRA_INDEX_MIRROR_CU128 = `"$PIP_EXTRA_INDEX_MIRROR_CU128`" `$PIP_EXTRA_INDEX_MIRROR_CU129 = `"$PIP_EXTRA_INDEX_MIRROR_CU129`" `$PIP_EXTRA_INDEX_MIRROR_CPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_XPU_NJU = `"$PIP_EXTRA_INDEX_MIRROR_XPU_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU118_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU118_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU121_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU121_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU124_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU124_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU126_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU126_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU128_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU128_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU129_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU129_NJU`" `$PIP_EXTRA_INDEX_MIRROR_CU130_NJU = `"$PIP_EXTRA_INDEX_MIRROR_CU130_NJU`" # Github 镜像源 `$GITHUB_MIRROR_LIST = @( `"https://ghfast.top/https://github.com`", `"https://mirror.ghproxy.com/https://github.com`", `"https://ghproxy.net/https://github.com`", `"https://gh.api.99988866.xyz/https://github.com`", `"https://gh-proxy.com/https://github.com`", `"https://ghps.cc/https://github.com`", `"https://gh.idayer.com/https://github.com`", `"https://ghproxy.1888866.xyz/github.com`", `"https://slink.ltd/https://github.com`", `"https://github.boki.moe/github.com`", `"https://github.moeyy.xyz/https://github.com`", `"https://gh-proxy.net/https://github.com`", `"https://gh-proxy.ygxz.in/https://github.com`", `"https://wget.la/https://github.com`", `"https://kkgithub.com`", `"https://gitclone.com/github.com`" ) # uv 最低版本 `$UV_MINIMUM_VER = `"$UV_MINIMUM_VER`" # Aria2 最低版本 `$ARIA2_MINIMUM_VER = `"$ARIA2_MINIMUM_VER`" # PATH `$PYTHON_PATH = `"`$PSScriptRoot/python`" `$PYTHON_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python`" `$PYTHON_SCRIPTS_PATH = `"`$PSScriptRoot/python/Scripts`" `$PYTHON_SCRIPTS_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/python/Scripts`" `$GIT_PATH = `"`$PSScriptRoot/git/bin`" `$GIT_EXTRA_PATH = `"`$PSScriptRoot/`$Env:CORE_PREFIX/git/bin`" `$Env:PATH = `"`$PYTHON_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$GIT_EXTRA_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_PATH`$([System.IO.Path]::PathSeparator)`$PYTHON_SCRIPTS_PATH`$([System.IO.Path]::PathSeparator)`$GIT_PATH`$([System.IO.Path]::PathSeparator)`$Env:PATH`" # 环境变量 `$Env:PIP_INDEX_URL = `"`$PIP_INDEX_MIRROR`" `$Env:PIP_EXTRA_INDEX_URL = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:PIP_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_DEFAULT_INDEX = `"`$PIP_INDEX_MIRROR`" `$Env:UV_INDEX = if (`$PIP_EXTRA_INDEX_MIRROR -ne `$PIP_EXTRA_INDEX_MIRROR_PYTORCH) { `"`$PIP_EXTRA_INDEX_MIRROR `$PIP_EXTRA_INDEX_MIRROR_PYTORCH`".Trim() } else { `$PIP_EXTRA_INDEX_MIRROR } `$Env:UV_FIND_LINKS = `"`$PIP_FIND_MIRROR`" `$Env:UV_LINK_MODE = `"copy`" `$Env:UV_HTTP_TIMEOUT = 30 `$Env:UV_CONCURRENT_DOWNLOADS = 50 `$Env:UV_INDEX_STRATEGY = `"unsafe-best-match`" `$Env:UV_CONFIG_FILE = `"nul`" `$Env:PIP_CONFIG_FILE = `"nul`" `$Env:PIP_DISABLE_PIP_VERSION_CHECK = 1 `$Env:PIP_NO_WARN_SCRIPT_LOCATION = 0 `$Env:PIP_TIMEOUT = 30 `$Env:PIP_RETRIES = 5 `$Env:PIP_PREFER_BINARY = 1 `$Env:PIP_YES = 1 `$Env:PYTHONUTF8 = 1 `$Env:PYTHONIOENCODING = `"utf-8`" `$Env:PYTHONUNBUFFERED = 1 `$Env:PYTHONNOUSERSITE = 1 `$Env:PYTHONFAULTHANDLER = 1 `$Env:PYTHONWARNINGS = `"$Env:PYTHONWARNINGS`" `$Env:GRADIO_ANALYTICS_ENABLED = `"False`" `$Env:HF_HUB_DISABLE_SYMLINKS_WARNING = 1 `$Env:BITSANDBYTES_NOWELCOME = 1 `$Env:ClDeviceGlobalMemSizeAvailablePercent = 100 `$Env:CUDA_MODULE_LOADING = `"LAZY`" `$Env:TORCH_CUDNN_V8_API_ENABLED = 1 `$Env:USE_LIBUV = 0 `$Env:SYCL_CACHE_PERSISTENT = 1 `$Env:TF_CPP_MIN_LOG_LEVEL = 3 `$Env:SAFETENSORS_FAST_GPU = 1 `$Env:CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:HF_HOME = `"`$PSScriptRoot/cache/huggingface`" `$Env:MATPLOTLIBRC = `"`$PSScriptRoot/cache`" `$Env:MODELSCOPE_CACHE = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:MS_CACHE_HOME = `"`$PSScriptRoot/cache/modelscope/hub`" `$Env:SYCL_CACHE_DIR = `"`$PSScriptRoot/cache/libsycl_cache`" `$Env:TORCH_HOME = `"`$PSScriptRoot/cache/torch`" `$Env:U2NET_HOME = `"`$PSScriptRoot/cache/u2net`" `$Env:XDG_CACHE_HOME = `"`$PSScriptRoot/cache`" `$Env:PIP_CACHE_DIR = `"`$PSScriptRoot/cache/pip`" `$Env:PYTHONPYCACHEPREFIX = `"`$PSScriptRoot/cache/pycache`" `$Env:TORCHINDUCTOR_CACHE_DIR = `"`$PSScriptRoot/cache/torchinductor`" `$Env:TRITON_CACHE_DIR = `"`$PSScriptRoot/cache/triton`" `$Env:UV_CACHE_DIR = `"`$PSScriptRoot/cache/uv`" `$Env:UV_PYTHON = `"`$PSScriptRoot/python/python.exe`" `$Env:SD_WEBUI_INSTALLER_ROOT = `$PSScriptRoot # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { `$content = `" 使用: .\`$(`$script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-DisablePyPIMirror] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像源地址>] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -DisablePyPIMirror 禁用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy ```"http://127.0.0.1:10809```" 设置代理服务器地址 -DisableHuggingFaceMirror 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror ```"https://hf-mirror.com```" 设置 HuggingFace 镜像源地址 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `".Trim() if (`$Help) { Write-Host `$content exit 0 } } # 提示符信息 function global:prompt { `"`$(Write-Host `"[SD WebUI Env]`" -ForegroundColor Green -NoNewLine) `$(Get-Location)> `" } # 消息输出 function global:Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } # 更新 uv function global:Update-uv { Print-Msg `"更新 uv 中`" python -m pip install uv --upgrade if (`$?) { Print-Msg `"更新 uv 成功`" } else { Print-Msg `"更新 uv 失败, 可尝试重新运行更新命令`" } } # 更新 Aria2 function global:Update-Aria2 { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/aria2c.exe`", `"https://huggingface.co/licyk/invokeai-core-model/resolve/main/pypatchmatch/aria2c.exe`" ) `$aria2_tmp_path = `"`$Env:CACHE_HOME/aria2c.exe`" `$i = 0 Print-Msg `"下载 Aria2 中`" New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null ForEach (`$url in `$urls) { Print-Msg `"下载 Aria2 中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$aria2_tmp_path`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载 Aria2 中`" } else { Print-Msg `"下载 Aria2 失败, 无法进行更新, 可尝试重新运行更新命令`" return } } } Move-Item -Path `"`$Env:CACHE_HOME/aria2c.exe`" -Destination `"`$Env:SD_WEBUI_INSTALLER_ROOT/git/bin/aria2c.exe`" -Force Print-Msg `"更新 Aria2 完成`" } # SD WebUI Installer 更新检测 function global:Check-Stable-Diffusion-WebUI-Installer-Update { # 可用的下载源 `$urls = @( `"https://github.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/raw/main/installer/stable_diffusion_webui_installer.ps1`", `"https://github.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitee.com/licyk/sd-webui-all-in-one/releases/download/stable_diffusion_webui_installer/stable_diffusion_webui_installer.ps1`", `"https://gitlab.com/licyk/sd-webui-all-in-one/-/raw/main/installer/stable_diffusion_webui_installer.ps1`" ) `$i = 0 New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null Set-Content -Encoding UTF8 -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/update_time.txt`" -Value `$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`") # 记录更新时间 ForEach (`$url in `$urls) { Print-Msg `"检查 SD WebUI Installer 更新中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" `$latest_version = [int]`$( Get-Content `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" | Select-String -Pattern `"SD_WEBUI_INSTALLER_VERSION`" | ForEach-Object { `$_.ToString() } )[0].Split(`"=`")[1].Trim() break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试检查 SD WebUI Installer 更新中`" } else { Print-Msg `"检查 SD WebUI Installer 更新失败`" return } } } if (`$latest_version -gt `$Env:SD_WEBUI_INSTALLER_VERSION) { Print-Msg `"SD WebUI Installer 有新版本可用`" Print-Msg `"调用 SD WebUI Installer 进行更新中`" . `"`$Env:CACHE_HOME/stable_diffusion_webui_installer.ps1`" -InstallPath `"`$Env:SD_WEBUI_INSTALLER_ROOT`" -UseUpdateMode Print-Msg `"更新结束, 需重新启动 SD WebUI Installer 管理脚本以应用更新, 回车退出 SD WebUI Installer 管理脚本`" Read-Host | Out-Null exit 0 } else { Print-Msg `"SD WebUI Installer 已是最新版本`" } } # 启用 Github 镜像源 function global:Test-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$Env:SD_WEBUI_INSTALLER_ROOT/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/.gitconfig`") { Remove-Item -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } if ((Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { # 使用自定义 Github 镜像源 if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$Env:SD_WEBUI_INSTALLER_ROOT/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" return } # 自动检测可用镜像源并使用 `$status = 0 ForEach(`$i in `$GITHUB_MIRROR_LIST) { Print-Msg `"测试 Github 镜像源: `$i`" if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } git clone `$i/licyk/empty `"`$Env:CACHE_HOME/github-mirror-test`" --quiet if (`$?) { Print-Msg `"该 Github 镜像源可用`" `$github_mirror = `$i `$status = 1 break } else { Print-Msg `"镜像源不可用, 更换镜像源进行测试`" } } if (Test-Path `"`$Env:CACHE_HOME/github-mirror-test`") { Remove-Item -Path `"`$Env:CACHE_HOME/github-mirror-test`" -Force -Recurse } if (`$status -eq 0) { Print-Msg `"无可用 Github 镜像源, 取消使用 Github 镜像源`" } else { Print-Msg `"设置 Github 镜像源`" git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" } } # 安装 Stable Diffusion WebUI 扩展 function global:Install-Stable-Diffusion-WebUI-Extension (`$url) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$extension_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" `$cache_path = `"`$Env:CACHE_HOME/`${extension_name}_tmp`" `$path = `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/extensions/`$extension_name`" if (!(Test-Path `"`$path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"安装 `$extension_name 扩展中`" # 清理缓存路径 if (Test-Path `"`$cache_path`") { Remove-Item -Path `"`$cache_path`" -Force -Recurse } git clone --recurse-submodules `$url `"`$cache_path`" if (`$?) { # 清理空文件夹 if (Test-Path `"`$path`") { `$random_string = [Guid]::NewGuid().ToString().Substring(0, 18) Move-Item -Path `"`$path`" -Destination `"`$Env:CACHE_HOME/`$random_string`" -Force } # 将下载好的文件从缓存文件夹移动到指定路径 New-Item -ItemType Directory -Path `"`$([System.IO.Path]::GetDirectoryName(`$path))`" -Force > `$null Move-Item -Path `"`$cache_path`" -Destination `"`$path`" -Force Print-Msg `"`$extension_name 扩展安装成功`" } else { Print-Msg `"`$extension_name 扩展安装失败`" } } else { Print-Msg `"`$extension_name 扩展已安装`" } } # Git 下载命令 function global:Git-Clone (`$url, `$path) { # 应用 Github 镜像源 if (`$global:is_test_gh_mirror -ne 1) { Test-Github-Mirror `$global:is_test_gh_mirror = 1 } `$repo_name = `$(Split-Path `$url -Leaf) -replace `".git`", `"`" if (`$path.Length -ne 0) { `$repo_path = `$path } else { `$repo_path = `"`$(`$(Get-Location).ToString())/`$repo_name`" } if (!(Test-Path `"`$repo_path`")) { `$status = 1 } else { `$items = Get-ChildItem `"`$repo_path`" if (`$items.Count -eq 0) { `$status = 1 } } if (`$status -eq 1) { Print-Msg `"下载 `$repo_name 中`" git clone --recurse-submodules `$url `"`$path`" if (`$?) { Print-Msg `"`$repo_name 下载成功`" } else { Print-Msg `"`$repo_name 下载失败`" } } else { Print-Msg `"`$repo_name 已存在`" } } # 列出已安装的 Stable Diffusion WebUI 扩展 function global:List-Extension { `$extension_list = Get-ChildItem -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/extensions`" | Select-Object -ExpandProperty FullName Print-Msg `"当前 Stable Diffusion WebUI 已安装的扩展`" `$count = 0 ForEach (`$i in `$extension_list) { if (Test-Path `"`$i`" -PathType Container) { `$count += 1 `$name = [System.IO.Path]::GetFileNameWithoutExtension(`"`$i`") Print-Msg `"- `$name`" } } Print-Msg `"Stable Diffusion WebUI 扩展路径: `$([System.IO.Path]::GetFullPath(`"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/extensions`"))`" Print-Msg `"Stable Diffusion WebUI 扩展数量: `$count`" } # 安装绘世启动器 function global:Install-Hanamizuki { `$urls = @( `"https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe`", `"https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`", `"https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe`" ) `$i = 0 if (!(Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`")) { Print-Msg `"内核路径 `$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX 未找到, 无法安装绘世启动器, 请检查 Stable Diffusion WebUI 是否已正确安装, 或者尝试运行 SD WebUI Installer 进行修复`" return } New-Item -ItemType Directory -Path `"`$Env:CACHE_HOME`" -Force > `$null if (Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`") { Print-Msg `"绘世启动器已安装, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" } else { ForEach (`$url in `$urls) { Print-Msg `"下载绘世启动器中`" try { Invoke-WebRequest -Uri `$url -OutFile `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" Move-Item -Path `"`$Env:CACHE_HOME/hanamizuki_tmp.exe`" `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`" -Force Print-Msg `"绘世启动器安装成功, 路径: `$([System.IO.Path]::GetFullPath(`"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/hanamizuki.exe`"))`" Print-Msg `"可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器`" break } catch { `$i += 1 if (`$i -lt `$urls.Length) { Print-Msg `"重试下载绘世启动器中`" } else { Print-Msg `"下载绘世启动器失败`" return } } } } `$content = `" @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=stable-diffusion-webui if exist ```"%~dp0%DefaultCorePrefix%```" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if ```"%%i```"==```"-CorePrefix```" ( set NextIsValue=1 ) ) ) if exist ```"%CorePrefixFile%```" ( for /f ```"delims=```" %%i in ('powershell -command ```"Get-Content -Path '%CorePrefixFile%'```"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f ```"delims=```" %%i in ('powershell -command ```"```$current_path = '%CurrentPath%'.Trim('/').Trim('\'); ```$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(```$origin_core_prefix)) { ```$to_path = ```$origin_core_prefix; ```$from_uri = New-Object System.Uri(```$current_path.Replace('\', '/') + '/'); ```$to_uri = New-Object System.Uri(```$to_path.Replace('\', '/')); ```$origin_core_prefix = ```$from_uri.MakeRelativeUri(```$to_uri).ToString().Trim('/') }; Write-Host ```$origin_core_prefix```"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist ```"%RootPath%```" ( cd /d ```"%RootPath%```" ) else ( echo %CorePrefix% not found echo Please check if Stable Diffusion WebUI is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d ```"%CurrentPath%```" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d ```"%CurrentPath%```" pause exit 1 ) `".Trim() Set-Content -Encoding Default -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/hanamizuki.bat`" -Value `$content Print-Msg `"检查绘世启动器运行环境`" if (!(Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`")) { if (Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/python`") { Print-Msg `"尝试将 Python 移动至 `$Env:SD_WEBUI_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/python`" `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Python 路径移动成功`" } else { Print-Msg `"Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境`" Print-Msg `"请关闭所有占用 Python 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 SD WebUI Installer 修复环境`" } } if (!(Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/git/bin/git.exe`")) { if (Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/git`") { Print-Msg `"尝试将 Git 移动至 `$Env:SD_WEBUI_INSTALLER_ROOT\`$Env:CORE_PREFIX 中`" Move-Item -Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/git`" `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX`" -Force if (`$?) { Print-Msg `"Git 路径移动成功`" } else { Print-Msg `"Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境`" Print-Msg `"请关闭所有占用 Git 的进程, 并重新运行该命令`" } } else { Print-Msg `"环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 SD WebUI Installer 修复环境`" } } Print-Msg `"检查绘世启动器运行环境结束`" } # 获取指定路径的内核路径前缀 function global:Get-Core-Prefix (`$to_path) { `$from_path = `$Env:SD_WEBUI_INSTALLER_ROOT `$from_uri = New-Object System.Uri(`$from_path.Replace('\', '/') + '/') `$to_uri = New-Object System.Uri(`$to_path.Trim('/').Trim('\').Replace('\', '/')) `$relative_path = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') Print-Msg `"`$to_path 路径的内核路径前缀: `$relative_path`" Print-Msg `"提示: 可使用 settings.ps1 设置内核路径前缀`" } # 设置 Python 命令别名 function global:pip { python -m pip @args } Set-Alias pip3 pip Set-Alias pip3.11 pip Set-Alias python3 python Set-Alias python3.11 python # 列出 SD WebUI Installer 内置命令 function global:List-CMD { Write-Host `" ================================== SD WebUI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ================================== 当前可用的 SD WebUI Installer 内置命令: Update-uv Update-Aria2 Check-Stable-Diffusion-WebUI-Installer-Update Test-Github-Mirror Install-Stable-Diffusion-WebUI-Extension Git-Clone Install-Hanamizuki List-Extension Get-Core-Prefix List-CMD 更多帮助信息可在 SD WebUI Installer 文档中查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md `" } # 显示 SD WebUI Installer 版本 function Get-Stable-Diffusion-WebUI-Installer-Version { `$ver = `$([string]`$Env:SD_WEBUI_INSTALLER_VERSION).ToCharArray() `$major = (`$ver[0..(`$ver.Length - 3)]) `$minor = `$ver[-2] `$micro = `$ver[-1] Print-Msg `"SD WebUI Installer 版本: v`${major}.`${minor}.`${micro}`" } # 获取内核路径前缀状态 function Get-Core-Prefix-Status { if ((Test-Path `"`$PSScriptRoot/core_prefix.txt`") -or (`$CorePrefix)) { Print-Msg `"检测到 core_prefix.txt 配置文件 / -CorePrefix 命令行参数, 使用自定义内核路径前缀`" if (`$CorePrefix) { `$origin_core_prefix = `$CorePrefix } else { `$origin_core_prefix = Get-Content `"`$PSScriptRoot/core_prefix.txt`" } if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix.Trim('/').Trim('\'))) { Print-Msg `"转换绝对路径为内核路径前缀: `$origin_core_prefix -> `$Env:CORE_PREFIX`" } } Print-Msg `"当前内核路径前缀: `$Env:CORE_PREFIX`" Print-Msg `"完整内核路径: `$PSScriptRoot\`$Env:CORE_PREFIX`" } # PyPI 镜像源状态 function PyPI-Mirror-Status { if (`$USE_PIP_MIRROR) { Print-Msg `"使用 PyPI 镜像源`" } else { Print-Msg `"检测到 disable_pypi_mirror.txt 配置文件 / -DisablePyPIMirror 命令行参数, 已将 PyPI 源切换至官方源`" } } # 代理配置 function Set-Proxy { `$Env:NO_PROXY = `"localhost,127.0.0.1,::1`" # 检测是否禁用自动设置镜像源 if ((Test-Path `"`$PSScriptRoot/disable_proxy.txt`") -or (`$DisableProxy)) { Print-Msg `"检测到本地存在 disable_proxy.txt 代理配置文件 / -DisableProxy 命令行参数, 禁用自动设置代理`" return } `$internet_setting = Get-ItemProperty -Path `"HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings`" if ((Test-Path `"`$PSScriptRoot/proxy.txt`") -or (`$UseCustomProxy)) { # 本地存在代理配置 if (`$UseCustomProxy) { `$proxy_value = `$UseCustomProxy } else { `$proxy_value = Get-Content `"`$PSScriptRoot/proxy.txt`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到本地存在 proxy.txt 代理配置文件 / -UseCustomProxy 命令行参数, 已读取代理配置文件并设置代理`" } elseif (`$internet_setting.ProxyEnable -eq 1) { # 系统已设置代理 `$proxy_addr = `$(`$internet_setting.ProxyServer) # 提取代理地址 if ((`$proxy_addr -match `"http=(.*?);`") -or (`$proxy_addr -match `"https=(.*?);`")) { `$proxy_value = `$matches[1] # 去除 http / https 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"http://`${proxy_value}`" } elseif (`$proxy_addr -match `"socks=(.*)`") { `$proxy_value = `$matches[1] # 去除 socks 前缀 `$proxy_value = `$proxy_value.ToString().Replace(`"http://`", `"`").Replace(`"https://`", `"`") `$proxy_value = `"socks://`${proxy_value}`" } else { `$proxy_value = `"http://`${proxy_addr}`" } `$Env:HTTP_PROXY = `$proxy_value `$Env:HTTPS_PROXY = `$proxy_value Print-Msg `"检测到系统设置了代理, 已读取系统中的代理配置并设置代理`" } } # HuggingFace 镜像源 function Set-HuggingFace-Mirror { if ((Test-Path `"`$PSScriptRoot/disable_hf_mirror.txt`") -or (`$DisableHuggingFaceMirror)) { # 检测是否禁用了自动设置 HuggingFace 镜像源 Print-Msg `"检测到本地存在 disable_hf_mirror.txt 镜像源配置文件 / -DisableHuggingFaceMirror 命令行参数, 禁用自动设置 HuggingFace 镜像源`" return } if ((Test-Path `"`$PSScriptRoot/hf_mirror.txt`") -or (`$UseCustomHuggingFaceMirror)) { # 本地存在 HuggingFace 镜像源配置 if (`$UseCustomHuggingFaceMirror) { `$hf_mirror_value = `$UseCustomHuggingFaceMirror } else { `$hf_mirror_value = Get-Content `"`$PSScriptRoot/hf_mirror.txt`" } `$Env:HF_ENDPOINT = `$hf_mirror_value Print-Msg `"检测到本地存在 hf_mirror.txt 配置文件 / -UseCustomHuggingFaceMirror 命令行参数, 已读取该配置并设置 HuggingFace 镜像源`" } else { # 使用默认设置 `$Env:HF_ENDPOINT = `"https://hf-mirror.com`" Print-Msg `"使用默认 HuggingFace 镜像源`" } } # Github 镜像源 function Set-Github-Mirror { `$Env:GIT_CONFIG_GLOBAL = `"`$PSScriptRoot/.gitconfig`" # 设置 Git 配置文件路径 if (Test-Path `"`$PSScriptRoot/.gitconfig`") { Remove-Item -Path `"`$PSScriptRoot/.gitconfig`" -Force -Recurse } # 默认 Git 配置 git config --global --add safe.directory `"*`" git config --global core.longpaths true if ((Test-Path `"`$PSScriptRoot/disable_gh_mirror.txt`") -or (`$DisableGithubMirror)) { # 禁用 Github 镜像源 Print-Msg `"检测到本地存在 disable_gh_mirror.txt Github 镜像源配置文件 / -DisableGithubMirror 命令行参数, 禁用 Github 镜像源`" return } # 使用自定义 Github 镜像源 if ((Test-Path `"`$PSScriptRoot/gh_mirror.txt`") -or (`$UseCustomGithubMirror)) { if (`$UseCustomGithubMirror) { `$github_mirror = `$UseCustomGithubMirror } else { `$github_mirror = Get-Content `"`$PSScriptRoot/gh_mirror.txt`" } git config --global url.`"`$github_mirror`".insteadOf `"https://github.com`" Print-Msg `"检测到本地存在 gh_mirror.txt Github 镜像源配置文件 / -UseCustomGithubMirror 命令行参数, 已读取 Github 镜像源配置文件并设置 Github 镜像源`" } } function Main { Print-Msg `"初始化中`" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status Set-Proxy Set-HuggingFace-Mirror Set-Github-Mirror PyPI-Mirror-Status # 切换 uv 指定的 Python if (Test-Path `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`") { `$Env:UV_PYTHON = `"`$Env:SD_WEBUI_INSTALLER_ROOT/`$Env:CORE_PREFIX/python/python.exe`" } Print-Msg `"激活 Stable Diffusion WebUI Env`" Print-Msg `"更多帮助信息可在 SD WebUI Installer 项目地址查看: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md`" } ################### Main ".Trim() if (Test-Path "$InstallPath/activate.ps1") { Print-Msg "更新 activate.ps1 中" } else { Print-Msg "生成 activate.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/activate.ps1" -Value $content } # 快捷启动终端脚本, 启动后将自动运行环境激活脚本 function Write-Launch-Terminal-Script { $content = " function Print-Msg (`$msg) { Write-Host `"[`$(Get-Date -Format `"yyyy-MM-dd HH:mm:ss`")]`" -ForegroundColor Yellow -NoNewline Write-Host `"[SD WebUI Installer]`" -ForegroundColor Cyan -NoNewline Write-Host `":: `" -ForegroundColor Blue -NoNewline Write-Host `"`$msg`" } Print-Msg `"执行 SD WebUI Installer 激活环境脚本`" powershell -NoExit -File `"`$PSScriptRoot/activate.ps1`" ".Trim() if (Test-Path "$InstallPath/terminal.ps1") { Print-Msg "更新 terminal.ps1 中" } else { Print-Msg "生成 terminal.ps1 中" } Set-Content -Encoding $PS_SCRIPT_ENCODING -Path "$InstallPath/terminal.ps1" -Value $content } # 帮助文档 function Write-ReadMe { $content = " ==================================================================== SD WebUI Installer created by licyk 哔哩哔哩:https://space.bilibili.com/46497516 Github:https://github.com/licyk ==================================================================== ########## 使用帮助 ########## 这是关于 Stable Diffusion WebUI 的简单使用文档。 使用 SD WebUI Installer 进行安装并安装成功后,将在当前目录生成 Stable Diffusion WebUI 文件夹,以下为文件夹中不同文件 / 文件夹的作用。 - launch.ps1:启动 Stable Diffusion WebUI。 - update.ps1:更新 Stable Diffusion WebUI。 - update_extension.ps1:更新 Stable Diffusion WebUI 扩展。 - download_models.ps1:下载模型的脚本,下载的模型将存放在 Stable Diffusion WebUI 的模型文件夹中。关于模型的介绍可阅读:https://github.com/licyk/README-collection/blob/main/model-info/README.md。 - reinstall_pytorch.ps1:重新安装 PyTorch 的脚本,在 PyTorch 出问题或者需要切换 PyTorch 版本时可使用。 - switch_branch.ps1:切换 Stable Diffusion WebUI 分支。 - settings.ps1:管理 SD WebUI Installer 的设置。 - terminal.ps1:启动 PowerShell 终端并自动激活虚拟环境,激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - activate.ps1:虚拟环境激活脚本,使用该脚本激活虚拟环境后即可使用 Python、Pip、Git 的命令。 - launch_stable_diffusion_webui_installer.ps1:获取最新的 SD WebUI Installer 安装脚本并运行。 - configure_env.bat:配置环境脚本,修复 PowerShell 运行闪退和启用 Windows 长路径支持。 - cache:缓存文件夹,保存着 Pip / HuggingFace 等缓存文件。 - python:Python 的存放路径。请注意,请勿将该 Python 文件夹添加到环境变量,这可能导致不良后果。 - git:Git 的存放路径。 - stable-diffusion-webui / core:Stable Diffusion WebUI 内核。 详细的 SD WebUI Installer 使用帮助:https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md Stable Diffusion WebUI 的使用教程: https://sdnote.netlify.app/guide/sd_webui https://sdnote.netlify.app/help/sd_webui ==================================================================== ########## Github 项目 ########## sd-webui-all-in-one 项目地址:https://github.com/licyk/sd-webui-all-in-one Stable Diffusion WebUI 项目地址:https://github.com/AUTOMATIC1111/stable-diffusion-webui Stable Diffusion WebUI Forge 项目地址:https://github.com/lllyasviel/stable-diffusion-webui-forge Stable Diffusion WebUI reForge 项目地址:https://github.com/Panchovix/stable-diffusion-webui-reForge Stable Diffusion WebUI Forge Classic 项目地址:https://github.com/Haoming02/sd-webui-forge-classic Stable Diffusion WebUI AMDGPU 项目地址:https://github.com/lshqqytiger/stable-diffusion-webui-amdgpu SD Next 项目地址:https://github.com/vladmandic/sdnext ==================================================================== ########## 用户协议 ########## 使用该软件代表您已阅读并同意以下用户协议: 您不得实施包括但不限于以下行为,也不得为任何违反法律法规的行为提供便利: 反对宪法所规定的基本原则的。 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的。 损害国家荣誉和利益的。 煽动民族仇恨、民族歧视,破坏民族团结的。 破坏国家宗教政策,宣扬邪教和封建迷信的。 散布谣言,扰乱社会秩序,破坏社会稳定的。 散布淫秽、色情、赌博、暴力、凶杀、恐怖或教唆犯罪的。 侮辱或诽谤他人,侵害他人合法权益的。 实施任何违背`“七条底线`”的行为。 含有法律、行政法规禁止的其他内容的。 因您的数据的产生、收集、处理、使用等任何相关事项存在违反法律法规等情况而造成的全部结果及责任均由您自行承担。 ".Trim() if (Test-Path "$InstallPath/help.txt") { Print-Msg "更新 help.txt 中" } else { Print-Msg "生成 help.txt 中" } Set-Content -Encoding UTF8 -Path "$InstallPath/help.txt" -Value $content } # 写入管理脚本和文档 function Write-Manager-Scripts { New-Item -ItemType Directory -Path "$InstallPath" -Force > $null Write-Launch-Script Write-Update-Script Write-Update-Extension-Script Write-Switch-Branch-Script Write-Launch-Stable-Diffusion-WebUI-Install-Script Write-PyTorch-ReInstall-Script Write-Download-Model-Script Write-Stable-Diffusion-WebUI-Installer-Settings-Script Write-Env-Activate-Script Write-Launch-Terminal-Script Write-ReadMe Write-Configure-Env-Script Write-Hanamizuki-Script } # 将安装器配置文件复制到管理脚本路径 function Copy-Stable-Diffusion-WebUI-Installer-Config { Print-Msg "为 SD WebUI Installer 管理脚本复制 SD WebUI Installer 配置文件中" if ((!($DisablePyPIMirror)) -and (Test-Path "$PSScriptRoot/disable_pypi_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_pypi_mirror.txt" -Destination "$InstallPath" Print-Msg "$PSScriptRoot/disable_pypi_mirror.txt -> $InstallPath/disable_pypi_mirror.txt" -Force } if ((!($DisableProxy)) -and (Test-Path "$PSScriptRoot/disable_proxy.txt")) { Copy-Item -Path "$PSScriptRoot/disable_proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_proxy.txt -> $InstallPath/disable_proxy.txt" -Force } elseif ((!($DisableProxy)) -and ($UseCustomProxy -eq "") -and (Test-Path "$PSScriptRoot/proxy.txt") -and (!(Test-Path "$PSScriptRoot/disable_proxy.txt"))) { Copy-Item -Path "$PSScriptRoot/proxy.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/proxy.txt -> $InstallPath/proxy.txt" } if ((!($DisableUV)) -and (Test-Path "$PSScriptRoot/disable_uv.txt")) { Copy-Item -Path "$PSScriptRoot/disable_uv.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_uv.txt -> $InstallPath/disable_uv.txt" -Force } if ((!($DisableGithubMirror)) -and (Test-Path "$PSScriptRoot/disable_gh_mirror.txt")) { Copy-Item -Path "$PSScriptRoot/disable_gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/disable_gh_mirror.txt -> $InstallPath/disable_gh_mirror.txt" } elseif ((!($DisableGithubMirror)) -and (!($UseCustomGithubMirror)) -and (Test-Path "$PSScriptRoot/gh_mirror.txt") -and (!(Test-Path "$PSScriptRoot/disable_gh_mirror.txt"))) { Copy-Item -Path "$PSScriptRoot/gh_mirror.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/gh_mirror.txt -> $InstallPath/gh_mirror.txt" } if ((!($CorePrefix)) -and (Test-Path "$PSScriptRoot/core_prefix.txt")) { Copy-Item -Path "$PSScriptRoot/core_prefix.txt" -Destination "$InstallPath" -Force Print-Msg "$PSScriptRoot/core_prefix.txt -> $InstallPath/core_prefix.txt" -Force } } # 写入启动绘世启动器脚本 function Write-Hanamizuki-Script { param ( [switch]$Force ) $content = " @echo off echo Initialize configuration setlocal enabledelayedexpansion set CurrentPath=%~dp0 set DefaultCorePrefix=stable-diffusion-webui if exist `"%~dp0%DefaultCorePrefix%`" ( set CorePrefix=%DefaultCorePrefix% ) else ( set CorePrefix=core ) set CorePrefixFile=%~dp0core_prefix.txt set ArgIndex=0 set NextIsValue=0 for %%i in (%*) do ( set /a ArgIndex+=1 if !NextIsValue!==1 ( set CorePrefix=%%i set NextIsValue=0 goto :convert ) else ( if `"%%i`"==`"-CorePrefix`" ( set NextIsValue=1 ) ) ) if exist `"%CorePrefixFile%`" ( for /f `"delims=`" %%i in ('powershell -command `"Get-Content -Path '%CorePrefixFile%'`"') do ( set CorePrefix=%%i goto :convert ) ) :convert for /f `"delims=`" %%i in ('powershell -command `"`$current_path = '%CurrentPath%'.Trim('/').Trim('\'); `$origin_core_prefix = '%CorePrefix%'.Trim('/').Trim('\'); if ([System.IO.Path]::IsPathRooted(`$origin_core_prefix)) { `$to_path = `$origin_core_prefix; `$from_uri = New-Object System.Uri(`$current_path.Replace('\', '/') + '/'); `$to_uri = New-Object System.Uri(`$to_path.Replace('\', '/')); `$origin_core_prefix = `$from_uri.MakeRelativeUri(`$to_uri).ToString().Trim('/') }; Write-Host `$origin_core_prefix`"') do ( set CorePrefix=%%i goto :continue ) :continue set RootPath=%~dp0%CorePrefix% echo CorePrefix: %CorePrefix% echo RootPath: %RootPath% if exist `"%RootPath%`" ( cd /d `"%RootPath%`" ) else ( echo %CorePrefix% not found echo Please check if Stable Diffusion WebUI is installed, or if the CorePrefix is set correctly pause exit 1 ) if exist .\hanamizuki.exe ( echo Launch Hanamizuki start /B .\hanamizuki.exe cd /d `"%CurrentPath%`" ) else ( echo Hanamizuki not found echo Try running terminal.ps1 to open the terminal and execute the Install-Hanamizuki command to install Hanamizuki cd /d `"%CurrentPath%`" pause exit 1 ) ".Trim() if ((!($Force)) -and (!(Test-Path "$InstallPath/hanamizuki.bat"))) { return } if (Test-Path "$InstallPath/hanamizuki.bat") { Print-Msg "更新 hanamizuki.bat 中" } else { Print-Msg "生成 hanamizuki.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/hanamizuki.bat" -Value $content } # 安装绘世启动器 function Install-Hanamizuki { $urls = @( "https://modelscope.cn/models/licyks/invokeai-core-model/resolve/master/pypatchmatch/hanamizuki.exe", "https://github.com/licyk/term-sd/releases/download/archive/hanamizuki.exe", "https://gitee.com/licyk/term-sd/releases/download/archive/hanamizuki.exe" ) $i = 0 if (!($InstallHanamizuki)) { return } New-Item -ItemType Directory -Path "$Env:CACHE_HOME" -Force > $null if (Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe") { Print-Msg "绘世启动器已安装, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" } else { ForEach ($url in $urls) { Print-Msg "下载绘世启动器中" try { Invoke-WebRequest -Uri $url -OutFile "$Env:CACHE_HOME/hanamizuki_tmp.exe" Move-Item -Path "$Env:CACHE_HOME/hanamizuki_tmp.exe" "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe" -Force Print-Msg "绘世启动器安装成功, 路径: $([System.IO.Path]::GetFullPath("$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe"))" Print-Msg "可以进入该路径启动绘世启动器, 也可运行 hanamizuki.bat 启动绘世启动器" break } catch { $i += 1 if ($i -lt $urls.Length) { Print-Msg "重试下载绘世启动器中" } else { Print-Msg "下载绘世启动器失败" return } } } } } # 配置绘世启动器运行环境 function Configure-Hanamizuki-Env { if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/hanamizuki.exe")) { return } Write-Hanamizuki-Script -Force Print-Msg "检查绘世启动器运行环境" if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/python/python.exe")) { if (Test-Path "$InstallPath/python") { Print-Msg "尝试将 Python 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/python" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Python 路径移动成功" } else { Print-Msg "Python 路径移动失败, 这将导致绘世启动器无法正确识别到 Python 环境" Print-Msg "请关闭所有占用 Python 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Python, 无法为绘世启动器准备 Python 环境, 请重新运行 SD WebUI Installer 修复环境" } } if (!(Test-Path "$InstallPath/$Env:CORE_PREFIX/git/bin/git.exe")) { if (Test-Path "$InstallPath/git") { Print-Msg "尝试将 Git 移动至 $InstallPath\$Env:CORE_PREFIX 中" Move-Item -Path "$InstallPath/git" "$InstallPath/$Env:CORE_PREFIX" -Force if ($?) { Print-Msg "Git 路径移动成功" } else { Print-Msg "Git 路径移动失败, 这将导致绘世启动器无法正确识别到 Git 环境" Print-Msg "请关闭所有占用 Git 的进程, 并重新运行该命令" } } else { Print-Msg "环境缺少 Git, 无法为绘世启动器准备 Git 环境, 请重新运行 SD WebUI Installer 修复环境" } } Print-Msg "检查绘世启动器运行环境结束" } # 执行安装 function Use-Install-Mode { Set-Proxy Set-uv PyPI-Mirror-Status Print-Msg "启动 Stable Diffusion WebUI 安装程序" Print-Msg "提示: 若出现某个步骤执行失败, 可尝试再次运行 SD WebUI Installer, 更多的说明请阅读 SD WebUI Installer 使用文档" Print-Msg "SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md" Print-Msg "即将进行安装的路径: $InstallPath" if ((Test-Path "$PSScriptRoot/install_sd_webui.txt") -or ($InstallBranch -eq "sd_webui")) { Print-Msg "检测到 install_sd_webui.txt 配置文件 / -InstallBranch sd_webui 命令行参数, 选择安装 AUTOMATIC1111/Stable-Diffusion-WebUI" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge.txt") -or ($InstallBranch -eq "sd_webui_forge")) { Print-Msg "检测到 install_sd_webui_forge.txt 配置文件 / -InstallBranch sd_webui_forge 命令行参数, 选择安装 lllyasviel/Stable-Diffusion-WebUI-Forge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_reforge.txt") -or ($InstallBranch -eq "sd_webui_reforge")) { Print-Msg "检测到 install_sd_webui_reforge.txt 配置文件 / -InstallBranch sd_webui_reforge 命令行参数, 选择安装 Panchovix/Stable-Diffusion-WebUI-reForge" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_forge_classic.txt") -or ($InstallBranch -eq "sd_webui_forge_classic")) { Print-Msg "检测到 install_sd_webui_forge_classic.txt 配置文件 / -InstallBranch sd_webui_forge_classic 命令行参数, 选择安装 Haoming02/Stable-Diffusion-WebUI-Forge-Classic" } elseif ((Test-Path "$PSScriptRoot/install_sd_webui_amdgpu.txt") -or ($InstallBranch -eq "sd_webui_amdgpu")) { Print-Msg "检测到 install_sd_webui_amdgpu.txt 配置文件 / -InstallBranch sd_webui_amdgp 命令行参数u, 选择安装 lshqqytiger/Stable-Diffusion-WebUI-AMDGPU" } elseif ((Test-Path "$PSScriptRoot/install_sd_next.txt") -or ($InstallBranch -eq "sdnext")) { Print-Msg "检测到 install_sd_next.txt 配置文件 / -InstallBranch sdnext 命令行参数, 选择安装 vladmandic/SD.NEXT" } else { Print-Msg "未指定安装的 SD WebUI 分支, 默认选择安装 AUTOMATIC1111/Stable-Diffusion-WebUI" } Check-Install Print-Msg "添加管理脚本和文档中" Write-Manager-Scripts Copy-Stable-Diffusion-WebUI-Installer-Config if ($BuildMode) { Use-Build-Mode Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "SD WebUI 环境构建完成, 路径: $InstallPath" } else { Install-Hanamizuki Configure-Hanamizuki-Env Print-Msg "Stable Diffusion WebUI 安装结束, 安装路径为: $InstallPath" } Print-Msg "帮助文档可在 Stable Diffusion WebUI 文件夹中查看, 双击 help.txt 文件即可查看, 更多的说明请阅读 SD WebUI Installer 使用文档" Print-Msg "SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md" Print-Msg "退出 SD WebUI Installer" if (!($BuildMode)) { Read-Host | Out-Null } } # 执行管理脚本更新 function Use-Update-Mode { Print-Msg "更新管理脚本和文档中" Write-Manager-Scripts Print-Msg "更新管理脚本和文档完成" } # 执行管理脚本完成其他环境构建 function Use-Build-Mode { Print-Msg "执行其他环境构建脚本中" if ($BuildWithTorch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWithTorch", $BuildWithTorch) if ($BuildWithTorchReinstall) { $launch_args.Add("-BuildWithTorchReinstall", $true) } if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行重装 PyTorch 脚本中" . "$InstallPath/reinstall_pytorch.ps1" @launch_args } if ($BuildWitchModel) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchModel", $BuildWitchModel) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行模型安装脚本中" . "$InstallPath/download_models.ps1" @launch_args } if ($BuildWitchBranch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) $launch_args.Add("-BuildWitchBranch", $BuildWitchBranch) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Stable Diffusion WebUI 分支切换脚本中" . "$InstallPath/switch_branch.ps1" @launch_args } if ($BuildWithUpdate) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Stable Diffusion WebUI 更新脚本中" . "$InstallPath/update.ps1" @launch_args } if ($BuildWithUpdateExtension) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Stable Diffusion WebUI 插件更新脚本中" . "$InstallPath/update_extension.ps1" @launch_args } if ($BuildWithLaunch) { $launch_args = @{} $launch_args.Add("-BuildMode", $true) if ($DisablePyPIMirror) { $launch_args.Add("-DisablePyPIMirror", $true) } if ($DisableUpdate) { $launch_args.Add("-DisableUpdate", $true) } if ($DisableProxy) { $launch_args.Add("-DisableProxy", $true) } if ($UseCustomProxy) { $launch_args.Add("-UseCustomProxy", $UseCustomProxy) } if ($DisableHuggingFaceMirror) { $launch_args.Add("-DisableHuggingFaceMirror", $true) } if ($UseCustomHuggingFaceMirror) { $launch_args.Add("-UseCustomHuggingFaceMirror", $UseCustomHuggingFaceMirror) } if ($DisableGithubMirror) { $launch_args.Add("-DisableGithubMirror", $true) } if ($UseCustomGithubMirror) { $launch_args.Add("-UseCustomGithubMirror", $UseCustomGithubMirror) } if ($DisableUV) { $launch_args.Add("-DisableUV", $true) } if ($LaunchArg) { $launch_args.Add("-LaunchArg", $LaunchArg) } if ($EnableShortcut) { $launch_args.Add("-EnableShortcut", $true) } if ($DisableCUDAMalloc) { $launch_args.Add("-DisableCUDAMalloc", $true) } if ($DisableEnvCheck) { $launch_args.Add("-DisableEnvCheck", $true) } if ($DisableAutoApplyUpdate) { $launch_args.Add("-DisableAutoApplyUpdate", $true) } if ($CorePrefix) { $launch_args.Add("-CorePrefix", $CorePrefix) } Print-Msg "执行 Stable Diffusion WebUI 启动脚本中" . "$InstallPath/launch.ps1" @launch_args } # 清理缓存 if ($NoCleanCache) { Print-Msg "跳过清理下载 Python 软件包的缓存" } else { Print-Msg "清理下载 Python 软件包的缓存中" python -m pip cache purge uv cache clean } } # 环境配置脚本 function Write-Configure-Env-Script { $content = " @echo off echo ================================================================= echo :: More information: https://github.com/licyk/sd-webui-all-in-one echo ================================================================= >nul 2>&1 `"%SYSTEMROOT%\system32\icacls.exe`" `"%SYSTEMROOT%\system32\config\system`" if '%errorlevel%' NEQ '0' ( echo :: Requesting administrative privileges goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo :: Write vbs script to request administrative privileges echo Set UAC = CreateObject^(`"Shell.Application`"^) > `"%temp%\getadmin.vbs`" echo :: Executing vbs script echo UAC.ShellExecute `"%~s0`", `"`", `"`", `"runas`", 1 >> `"%temp%\getadmin.vbs`" `"%temp%\getadmin.vbs`" exit /B :gotAdmin echo :: Launch CMD with administrative privileges if exist `"%temp%\getadmin.vbs`" ( del `"%temp%\getadmin.vbs`" ) pushd `"%CD%`" CD /D `"%~dp0`" goto configureEnv :configureEnv title Configure environment echo :: Set PowerShell execution policies echo :: Executing command: `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" powershell `"Set-ExecutionPolicy Unrestricted -Scope CurrentUser`" echo :: Enable long paths supported echo :: Executing command: `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" powershell `"New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1 -PropertyType DWORD -Force`" echo :: Configure completed echo :: Exit environment configuration script pause ".Trim() if (Test-Path "$InstallPath/configure_env.bat") { Print-Msg "更新 configure_env.bat 中" } else { Print-Msg "生成 configure_env.bat 中" } Set-Content -Encoding Default -Path "$InstallPath/configure_env.bat" -Value $content } # 帮助信息 function Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help { $content = " 使用: .\$($script:MyInvocation.MyCommand.Name) [-Help] [-CorePrefix <内核路径前缀>] [-InstallPath <安装 Stable Diffusion WebUI 的绝对路径>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-PyTorchMirrorType <PyTorch 镜像源类型>] [-InstallBranch <安装的 Stable Diffusion WebUI 分支>] [-UseUpdateMode] [-DisablePyPIMirror] [-DisableProxy] [-UseCustomProxy <代理服务器地址>] [-DisableUV] [-DisableGithubMirror] [-UseCustomGithubMirror <Github 镜像站地址>] [-BuildMode] [-BuildWithUpdate] [-BuildWithUpdateExtension] [-BuildWithLaunch] [-BuildWithTorch <PyTorch 版本编号>] [-BuildWithTorchReinstall] [-BuildWitchModel <模型编号列表>] [-BuildWitchBranch <Stable Diffusion WebUI 分支编号>] [-NoPreDownloadExtension] [-NoPreDownloadModel] [-PyTorchPackage <PyTorch 软件包>] [-InstallHanamizuki] [-NoCleanCache] [-xFormersPackage <xFormers 软件包>] [-DisableUpdate] [-DisableHuggingFaceMirror] [-UseCustomHuggingFaceMirror <HuggingFace 镜像源地址>] [-LaunchArg <Stable Diffusion WebUI 启动参数>] [-EnableShortcut] [-DisableCUDAMalloc] [-DisableEnvCheck] [-DisableAutoApplyUpdate] 参数: -Help 获取 SD WebUI Installer 的帮助信息 -CorePrefix <内核路径前缀> 设置内核的路径前缀, 默认路径前缀为 core -InstallPath <安装 Stable Diffusion WebUI 的绝对路径> 指定 SD WebUI Installer 安装 Stable Diffusion WebUI 的路径, 使用绝对路径表示 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallPath `"D:\Donwload`", 这将指定 SD WebUI Installer 安装 Stable Diffusion WebUI 到 D:\Donwload 这个路径 -PyTorchMirrorType <PyTorch 镜像源类型> 指定安装 PyTorch 时使用的 PyTorch 镜像源类型, 可指定的类型: cpu, xpu, cu11x, cu118, cu121, cu124, cu126, cu128, cu129 -InstallBranch <安装的 Stable Diffusion WebUI 分支> 指定 SD WebUI Installer 安装的 Stable Diffusion WebUI 分支 (sd_webui, sd_webui_forge, sd_webui_reforge, sd_webui_forge_classic, sd_webui_amdgpu, sdnext) 例如: .\$($script:MyInvocation.MyCommand.Name) -InstallBranch `"sd_webui_forge`", 这将指定 SD WebUI Installer 安装 lllyasviel/Stable-Diffusion-WebUI-Forge 分支 未指定该参数时, 默认安装 AUTOMATIC1111/Stable-Diffusion-WebUI 分支 支持指定安装的分支如下: sd_webui: AUTOMATIC1111/Stable-Diffusion-WebUI sd_webui_forge: lllyasviel/Stable-Diffusion-WebUI-Forge sd_webui_reforge: Panchovix/Stable-Diffusion-WebUI-reForge sd_webui_forge_classic: Haoming02/Stable-Diffusion-WebUI-Forge-Classic sd_webui_amdgpu: lshqqytiger/Stable-Diffusion-WebUI-AMDGPU sdnext: vladmandic/SD.NEXT -UseUpdateMode 指定 SD WebUI Installer 使用更新模式, 只对 SD WebUI Installer 的管理脚本进行更新 -DisablePyPIMirror 禁用 SD WebUI Installer 使用 PyPI 镜像源, 使用 PyPI 官方源下载 Python 软件包 -DisableProxy 禁用 SD WebUI Installer 自动设置代理服务器 -UseCustomProxy <代理服务器地址> 使用自定义的代理服务器地址, 例如代理服务器地址为 http://127.0.0.1:10809, 则使用 -UseCustomProxy `"http://127.0.0.1:10809`" 设置代理服务器地址 -DisableUV 禁用 SD WebUI Installer 使用 uv 安装 Python 软件包, 使用 Pip 安装 Python 软件包 -DisableGithubMirror 禁用 SD WebUI Installer 自动设置 Github 镜像源 -UseCustomGithubMirror <Github 镜像站地址> 使用自定义的 Github 镜像站地址 可用的 Github 镜像站地址: https://ghfast.top/https://github.com https://mirror.ghproxy.com/https://github.com https://ghproxy.net/https://github.com https://gh.api.99988866.xyz/https://github.com https://gh-proxy.com/https://github.com https://ghps.cc/https://github.com https://gh.idayer.com/https://github.com https://ghproxy.1888866.xyz/github.com https://slink.ltd/https://github.com https://github.boki.moe/github.com https://github.moeyy.xyz/https://github.com https://gh-proxy.net/https://github.com https://gh-proxy.ygxz.in/https://github.com https://wget.la/https://github.com https://kkgithub.com https://gitclone.com/github.com -BuildMode 启用 SD WebUI Installer 构建模式, 在基础安装流程结束后将调用 SD WebUI Installer 管理脚本执行剩余的安装任务, 并且出现错误时不再暂停 SD WebUI Installer 的执行, 而是直接退出 当指定调用多个 SD WebUI Installer 脚本时, 将按照优先顺序执行 (按从上到下的顺序) - reinstall_pytorch.ps1 (对应 -BuildWithTorch, -BuildWithTorchReinstall 参数) - switch_branch.ps1 (对应 -BuildWitchBranch 参数) - download_models.ps1 (对应 -BuildWitchModel 参数) - update.ps1 (对应 -BuildWithUpdate 参数) - update_extension.ps1 (对应 -BuildWithUpdateExtension 参数) - launch.ps1 (对应 -BuildWithLaunch 参数) -BuildWithUpdate (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 update.ps1 脚本, 更新 Stable Diffusion WebUI 内核 -BuildWithUpdateExtension (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 update_extension.ps1 脚本, 更新 Stable Diffusion WebUI 扩展 -BuildWithLaunch (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 launch.ps1 脚本, 执行启动 Stable Diffusion WebUI 前的环境检查流程, 但跳过启动 Stable Diffusion WebUI -BuildWithTorch <PyTorch 版本编号> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 reinstall_pytorch.ps1 脚本, 根据 PyTorch 版本编号安装指定的 PyTorch 版本 PyTorch 版本编号可运行 reinstall_pytorch.ps1 脚本进行查看 -BuildWithTorchReinstall (需添加 -BuildMode 启用 SD WebUI Installer 构建模式, 并且添加 -BuildWithTorch) 在 SD WebUI Installer 构建模式下, 执行 reinstall_pytorch.ps1 脚本对 PyTorch 进行指定版本安装时使用强制重新安装 -BuildWitchModel <模型编号列表> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 download_models.ps1 脚本, 根据模型编号列表下载指定的模型 模型编号可运行 download_models.ps1 脚本进行查看 -BuildWitchBranch <Stable Diffusion WebUI 分支编号> (需添加 -BuildMode 启用 SD WebUI Installer 构建模式) SD WebUI Installer 执行完基础安装流程后调用 SD WebUI Installer 的 switch_branch.ps1 脚本, 根据 Stable Diffusion WebUI 分支编号切换到对应的 Stable Diffusion WebUI 分支 Stable Diffusion WebUI 分支编号可运行 switch_branch.ps1 脚本进行查看 -NoPreDownloadExtension 安装 Stable Diffusion WebUI 时跳过下载 Stable Diffusion WebUI 扩展 -NoPreDownloadModel 安装 Stable Diffusion WebUI 时跳过预下载模型 -PyTorchPackage <PyTorch 软件包> (需要同时搭配 -xFormersPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 PyTorch 版本, 如 -PyTorchPackage `"torch==2.3.0+cu118 torchvision==0.18.0+cu118 torchaudio==2.3.0+cu118`" -xFormersPackage <xFormers 软件包> (需要同时搭配 -PyTorchPackage 一起使用, 否则可能会出现 PyTorch 和 xFormers 不匹配的问题) 指定要安装 xFormers 版本, 如 -xFormersPackage `"xformers===0.0.26.post1+cu118`" -InstallHanamizuki 安装绘世启动器, 并生成 hanamizuki.bat 用于启动绘世启动器 -NoCleanCache 安装结束后保留下载 Python 软件包缓存 -DisableUpdate (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 禁用 SD WebUI Installer 更新检查 -DisableHuggingFaceMirror (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 禁用 HuggingFace 镜像源, 不使用 HuggingFace 镜像源下载文件 -UseCustomHuggingFaceMirror <HuggingFace 镜像源地址> (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 使用自定义 HuggingFace 镜像源地址, 例如代理服务器地址为 https://hf-mirror.com, 则使用 -UseCustomHuggingFaceMirror `"https://hf-mirror.com`" 设置 HuggingFace 镜像源地址 -LaunchArg <Stable Diffusion WebUI 启动参数> (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 设置 Stable Diffusion WebUI 自定义启动参数, 如启用 --autolaunch 和 --xformers, 则使用 -LaunchArg `"--autolaunch --xformers`" 进行启用 -EnableShortcut (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 创建 Stable Diffusion WebUI 启动快捷方式 -DisableCUDAMalloc (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 禁用 SD WebUI Installer 通过 PYTORCH_CUDA_ALLOC_CONF / PYTORCH_ALLOC_CONF 环境变量设置 CUDA 内存分配器 -DisableEnvCheck (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 禁用 SD WebUI Installer 检查 Stable Diffusion WebUI 运行环境中存在的问题, 禁用后可能会导致 Stable Diffusion WebUI 环境中存在的问题无法被发现并修复 -DisableAutoApplyUpdate (仅在 SD WebUI Installer 构建模式下生效, 并且只作用于 SD WebUI Installer 管理脚本) 禁用 SD WebUI Installer 自动应用新版本更新 更多的帮助信息请阅读 SD WebUI Installer 使用文档: https://github.com/licyk/sd-webui-all-in-one/blob/main/docs/stable_diffusion_webui_installer.md ".Trim() if ($Help) { Write-Host $content exit 0 } } # 主程序 function Main { Print-Msg "初始化中" Get-Stable-Diffusion-WebUI-Installer-Version Get-Stable-Diffusion-WebUI-Installer-Cmdlet-Help Get-Core-Prefix-Status if ($UseUpdateMode) { Print-Msg "使用更新模式" Use-Update-Mode Set-Content -Encoding UTF8 -Path "$InstallPath/update_time.txt" -Value $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") # 记录更新时间 } else { if ($BuildMode) { Print-Msg "SD WebUI Installer 构建模式已启用" } Print-Msg "使用安装模式" Use-Install-Mode } } ################### Main
2301_81996401/sd-webui-all-in-one
installer/stable_diffusion_webui_installer.ps1
PowerShell
agpl-3.0
569,314
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xlyptNJ2ICnN" }, "source": [ "# ComfyUI Colab\n", "Colab NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Colab](https://colab.research.google.com) 部署 [ComfyUI](https://github.com/comfyanonymous/ComfyUI) 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "Colab 链接:<a href=\"https://colab.research.google.com/github/licyk/sd-webui-all-in-one/blob/main/notebook/comfyui_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式,并安装 [ComfyUI](https://github.com/comfyanonymous/ComfyUI),默认设置下已启用`配置环境完成后立即启动 ComfyUI`选项,则安装完成后将直接启动 ComfyUI,并显示访问地址。\n", "2. 下载模型:下载可选列表中的模型(可选)。\n", "3. 自定义模型下载:使用链接下载模型(可选)。\n", "4. 自定义节点下载:使用链接下载自定义节点(可选)。\n", "5. 启动 ComfyUI:启动 ComfyUI,并显示访问地址。\n", "\n", "\n", "## 使用\n", "1. 在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择`GPU T4`或者其他 GPU。\n", "2. `环境配置`单元中的选项通常不需要修改,保持默认即可。\n", "3. 运行`环境配置`单元,默认设置下已启用`配置环境完成后立即启动 ComfyUI`选项,则环境配置完成后立即启动 ComfyUI,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 ComfyUI,ComfyUI 的访问地址可在日志中查看。\n", "4. 如果未启用`配置环境完成后立即启动 ComfyUI`选项,需要运行`启动 ComfyUI`单元,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 ComfyUI,ComfyUI 的访问地址可在日志中查看。\n", "5. 提示词查询工具:[SD 绘画提示词查询](https://licyk.github.io/t/tag)\n", "\n", "## 提示\n", "1. Colab 在关机后将会清除所有数据,所以每次重新启动时必须运行`环境配置`单元才能运行`启动 ComfyUI`单元。\n", "2. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "3. [Zrok](https://zrok.io) 内网穿透在使用前需要填写 Zrok Token, 可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取。\n", "4. 每次启动 Colab 后必须运行`环境配置`单元,才能运行`启动 ComfyUI`单元启动 ComfyUI。\n", "5. 其他功能有自定义模型下载等功能,根据自己的需求进行使用。\n", "6. 运行`启动 ComfyUI`时将弹出 Google Drive 访问授权提示,根据提示进行授权。授权后,使用 ComfyUI 生成的图片将保存在 Google Drive 的`comfyui_output`文件夹中。\n", "7. 在`额外挂载目录设置`中可以挂载一些额外目录,如 LoRA 模型、扩展目录,挂载后的目录可在 Google Drive 的`comfyui_output`文件夹中查看和修改。可通过该功能在 Google Drive 上传模型并在 ComfyUI 中使用。\n", "8. 默认挂载以下目录到 Google Drive,可在 Google Drive 的`comfyui_output`文件夹中上传和修改文件:`output`, `user`, `input`, `extra_model_paths.yaml`\n", "9. ComfyUI 使用教程可阅读:[ComfyUI 部署与使用 - SD Note](https://sdnote.netlify.app/guide/comfyui)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "VjYy0F2gZIPR" }, "outputs": [], "source": [ "#@title 👇 环境配置\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, ComfyUIManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "\n", "#######################################################\n", "\n", "#@markdown ## ComfyUI 核心配置选项\n", "#@markdown - ComfyUI 分支仓库地址:\n", "COMFYUI_REPO = \"https://github.com/comfyanonymous/ComfyUI\" #@param {type:\"string\"}\n", "#@markdown - ComfyUI 设置文件地址:\n", "COMFYUI_SETTING = \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/comfy.settings.json\" #@param {type:\"string\"}\n", "#@markdown - ComfyUI 依赖表名:\n", "COMFYUI_REQUIREMENTS = \"requirements.txt\" #@param {type:\"string\"}\n", "#@markdown - ComfyUI 启动参数:\n", "COMFYUI_LAUNCH_ARGS = \"--highvram --preview-method auto\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## PyTorch 组件版本选项:\n", "#@markdown - PyTorch:\n", "PYTORCH_VER = \"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126\" #@param {type:\"string\"}\n", "#@markdown - xFormers:\n", "XFORMERS_VER = \"xformers==0.0.32.post2\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 包管理器选项:\n", "#@markdown - 使用 uv 作为 Python 包管理器\n", "USE_UV = True #@param {type:\"boolean\"}\n", "#@markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" #@param {type:\"string\"}\n", "#@markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"\" #@param {type:\"string\"}\n", "#@markdown - PyTorch 镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 内网穿透选项:\n", "#@markdown - 使用 remote.moe 内网穿透\n", "USE_REMOTE_MOE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 localhost.run 内网穿透\n", "USE_LOCALHOST_RUN = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 pinggy.io 内网穿透\n", "USE_PINGGY_IO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 CloudFlare 内网穿透\n", "USE_CLOUDFLARE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Gradio 内网穿透\n", "USE_GRADIO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Ngrok 内网穿透(需填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取)\n", "USE_NGROK = True #@param {type:\"boolean\"}\n", "#@markdown - Ngrok Token\n", "NGROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown - 使用 Zrok 内网穿透(需填写 Zrok Token,可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取)\n", "USE_ZROK = True #@param {type:\"boolean\"}\n", "#@markdown - Zrok Token\n", "ZROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 快速启动选项:\n", "#@markdown - 配置环境完成后立即启动 ComfyUI(并挂载 Google Drive)\n", "QUICK_LAUNCH = True #@param {type:\"boolean\"}\n", "#@markdown - 不重复配置环境(当重复运行环境配置时将不会再进行安装)\n", "NO_REPEAT_CONFIGURE_ENV = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "#@markdown ## 其他选项:\n", "#@markdown - 清理无用日志\n", "CLEAR_LOG = True #@param {type:\"boolean\"}\n", "#@markdown - 检查可用 GPU\n", "CHECK_AVALIABLE_GPU = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 出现冲突组件时按顺序安装组件依赖\n", "INSTALL_CONFLICT_COMPONENT = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核和扩展\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# @markdown ---\n", "#######################################################\n", "# @markdown ## 自定义节点设置, 在安装时将会下载选择的自定义节点:\n", "CUSTOM_NODE_LIST = []\n", "\n", "comfyui_manager = True # @param {type:\"boolean\"}\n", "comfyui_controlnet_aux = True # @param {type:\"boolean\"}\n", "comfyui_advanced_controlnet = True # @param {type:\"boolean\"}\n", "comfyui_ipadapter_plus = True # @param {type:\"boolean\"}\n", "comfyui_marigold = True # @param {type:\"boolean\"}\n", "comfyui_wd14_tagger = True # @param {type:\"boolean\"}\n", "comfyui_tiledksampler = True # @param {type:\"boolean\"}\n", "comfyui_custom_scripts = True # @param {type:\"boolean\"}\n", "images_grid_comfy_plugin = True # @param {type:\"boolean\"}\n", "comfyui_ultimatesdupscale = True # @param {type:\"boolean\"}\n", "comfyui_custom_nodes_alekpet = True # @param {type:\"boolean\"}\n", "comfyui_browser = True # @param {type:\"boolean\"}\n", "comfyui_inspire_pack = True # @param {type:\"boolean\"}\n", "comfyui_comfyroll_customnodes = True # @param {type:\"boolean\"}\n", "comfyui_crystools = True # @param {type:\"boolean\"}\n", "comfyui_tileddiffusion = True # @param {type:\"boolean\"}\n", "comfyui_openpose_editor = True # @param {type:\"boolean\"}\n", "comfyui_restart_sampler = True # @param {type:\"boolean\"}\n", "weilin_comfyui_prompt_all_in_one = True # @param {type:\"boolean\"}\n", "comfyui_hakuimg = True # @param {type:\"boolean\"}\n", "comfyui_easy_use = True # @param {type:\"boolean\"}\n", "rgthree_comfy = True # @param {type:\"boolean\"}\n", "\n", "\n", "comfyui_manager and CUSTOM_NODE_LIST.append(\"https://github.com/Comfy-Org/ComfyUI-Manager\")\n", "comfyui_controlnet_aux and CUSTOM_NODE_LIST.append(\"https://github.com/Fannovel16/comfyui_controlnet_aux\")\n", "comfyui_advanced_controlnet and CUSTOM_NODE_LIST.append(\"https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet\")\n", "comfyui_ipadapter_plus and CUSTOM_NODE_LIST.append(\"https://github.com/cubiq/ComfyUI_IPAdapter_plus\")\n", "comfyui_marigold and CUSTOM_NODE_LIST.append(\"https://github.com/kijai/ComfyUI-Marigold\")\n", "comfyui_wd14_tagger and CUSTOM_NODE_LIST.append(\"https://github.com/pythongosssss/ComfyUI-WD14-Tagger\")\n", "comfyui_tiledksampler and CUSTOM_NODE_LIST.append(\"https://github.com/BlenderNeko/ComfyUI_TiledKSampler\")\n", "comfyui_custom_scripts and CUSTOM_NODE_LIST.append(\"https://github.com/pythongosssss/ComfyUI-Custom-Scripts\")\n", "images_grid_comfy_plugin and CUSTOM_NODE_LIST.append(\"https://github.com/LEv145/images-grid-comfy-plugin\")\n", "comfyui_ultimatesdupscale and CUSTOM_NODE_LIST.append(\"https://github.com/ssitu/ComfyUI_UltimateSDUpscale\")\n", "comfyui_custom_nodes_alekpet and CUSTOM_NODE_LIST.append(\"https://github.com/AlekPet/ComfyUI_Custom_Nodes_AlekPet\")\n", "comfyui_browser and CUSTOM_NODE_LIST.append(\"https://github.com/talesofai/comfyui-browser\")\n", "comfyui_inspire_pack and CUSTOM_NODE_LIST.append(\"https://github.com/ltdrdata/ComfyUI-Inspire-Pack\")\n", "comfyui_comfyroll_customnodes and CUSTOM_NODE_LIST.append(\"https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes\")\n", "comfyui_crystools and CUSTOM_NODE_LIST.append(\"https://github.com/crystian/ComfyUI-Crystools\")\n", "comfyui_tileddiffusion and CUSTOM_NODE_LIST.append(\"https://github.com/shiimizu/ComfyUI-TiledDiffusion\")\n", "comfyui_openpose_editor and CUSTOM_NODE_LIST.append(\"https://github.com/huchenlei/ComfyUI-openpose-editor\")\n", "comfyui_restart_sampler and CUSTOM_NODE_LIST.append(\"https://github.com/licyk/ComfyUI-Restart-Sampler\")\n", "weilin_comfyui_prompt_all_in_one and CUSTOM_NODE_LIST.append(\"https://github.com/weilin9999/WeiLin-ComfyUI-prompt-all-in-one\")\n", "comfyui_hakuimg and CUSTOM_NODE_LIST.append(\"https://github.com/licyk/ComfyUI-HakuImg\")\n", "comfyui_easy_use and CUSTOM_NODE_LIST.append(\"https://github.com/yolain/ComfyUI-Easy-Use\")\n", "rgthree_comfy and CUSTOM_NODE_LIST.append(\"https://github.com/rgthree/rgthree-comfy\")\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 模型设置, 在安装时将会下载选择的模型:\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = True # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = True # @param {type:\"boolean\"}\n", "# @markdown - VAE Approx 模型\n", "vae_approx_model = True # @param {type:\"boolean\"}\n", "vae_approx_sdxl = True # @param {type:\"boolean\"}\n", "vae_approx_sd3 = True # @param {type:\"boolean\"}\n", "# @markdown - 放大模型\n", "upscale_dat_x2 = False # @param {type:\"boolean\"}\n", "upscale_dat_x3 = False # @param {type:\"boolean\"}\n", "upscale_dat_x4 = True # @param {type:\"boolean\"}\n", "upscale_4x_nmkd_superscale_sp_178000_g = False # @param {type:\"boolean\"}\n", "upscale_8x_nmkd_superscale_150000_g = False # @param {type:\"boolean\"}\n", "upscale_lollypop = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus_anime_6b = True # @param {type:\"boolean\"}\n", "upscale_swinir_4x = False # @param {type:\"boolean\"}\n", "# @markdown - ControlNet 模型\n", "illustriousxlcanny_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineart_v10 = False # @param {type:\"boolean\"}\n", "illustriousxldepth_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlsoftedge_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineartrrealistic_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlshuffle_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlopenpose_v10 = False # @param {type:\"boolean\"}\n", "illustriousxltile_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlv0_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_canny_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_depth_midas_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_tile_fp16 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epscanny = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartanime = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsnormalmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epssoftedgehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsmangaline = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartrealistic = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidasv11 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblepidinet = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_openposemodel = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epstile = False # @param {type:\"boolean\"}\n", "noobai_inpainting_controlnet = False # @param {type:\"boolean\"}\n", "noobipamark1_mark1 = False # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", \"type\": \"checkpoints\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", \"type\": \"checkpoints\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", \"type\": \"checkpoints\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", \"type\": \"checkpoints\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", \"type\": \"checkpoints\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", \"type\": \"checkpoints\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", \"type\": \"checkpoints\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", \"type\": \"checkpoints\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", \"type\": \"checkpoints\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", \"type\": \"checkpoints\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", \"type\": \"checkpoints\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", \"type\": \"checkpoints\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", \"type\": \"checkpoints\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", \"type\": \"checkpoints\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", \"type\": \"checkpoints\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", \"type\": \"vae\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", \"type\": \"vae\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", \"type\": \"vae\"})\n", "# VAE Approx 模型\n", "vae_approx_model and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/model.pt\", \"type\": \"vae_approx\"})\n", "vae_approx_sdxl and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sdxl.pt\", \"type\": \"vae_approx\"})\n", "vae_approx_sd3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sd3.pt\", \"type\": \"vae_approx\"})\n", "# 放大模型\n", "upscale_dat_x2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", \"type\": \"upscale_models\"})\n", "upscale_dat_x3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", \"type\": \"upscale_models\"})\n", "upscale_dat_x4 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", \"type\": \"upscale_models\"})\n", "upscale_4x_nmkd_superscale_sp_178000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", \"type\": \"upscale_models\"})\n", "upscale_8x_nmkd_superscale_150000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/8x_NMKD-Superscale_150000_G.pth\", \"type\": \"upscale_models\"})\n", "upscale_lollypop and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/lollypop.pth\", \"type\": \"upscale_models\"})\n", "upscale_realesrgan_x4plus and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", \"type\": \"upscale_models\"})\n", "upscale_realesrgan_x4plus_anime_6b and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", \"type\": \"upscale_models\"})\n", "upscale_swinir_4x and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/SwinIR/SwinIR_4x.pth\", \"type\": \"upscale_models\"})\n", "# ControlNet 模型\n", "illustriousxlcanny_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLCanny_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxllineart_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineart_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxldepth_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLDepth_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlsoftedge_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLSoftedge_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxllineartrrealistic_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineartRrealistic_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlshuffle_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLShuffle_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlopenpose_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLOpenPose_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxltile_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLTile_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv0_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv0.1_inpainting_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_canny_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_canny_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_depth_midas_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_depth_midas_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_inpainting_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_tile_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_tile_fp16.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epscanny and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsCanny.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsdepthmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidas.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epslineartanime and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartAnime.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsnormalmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsNormalMidas.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epssoftedgehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsSoftedgeHed.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsmangaline and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsMangaLine.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epslineartrealistic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartRealistic.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsdepthmidasv11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidasV11.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsscribblehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribbleHed.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsscribblepidinet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribblePidinet.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_openposemodel and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_openposeModel.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epstile and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsTile.safetensors\", \"type\": \"controlnet\"})\n", "noobai_inpainting_controlnet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/NoobAI_Inpainting_ControlNet.safetensors\", \"type\": \"controlnet\"})\n", "noobipamark1_mark1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/noobIPAMARK1_mark1.safetensors\", \"type\": \"controlnet\"})\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 额外挂载目录设置, 在启动时挂载目录到 Google Drive:\n", "EXTRA_LINK_DIR = []\n", "\n", "#@markdown - models/checkpoints 目录\n", "link_checkpoints_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/diffusers 目录\n", "link_diffusers_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/unet 目录\n", "link_unet_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/text_encoders 目录\n", "link_text_encoders_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/clip 目录\n", "link_clip_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/clip_vision 目录\n", "link_clip_vision_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/diffusion_models 目录\n", "link_diffusion_models_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/loras 目录\n", "link_loras_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/vae 目录\n", "link_vae_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/controlnet 目录\n", "link_controlnet_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/embeddings 目录\n", "link_embeddings_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/upscale_models 目录\n", "link_upscale_models_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/vae_approx 目录\n", "link_vae_approx_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/style_models 目录\n", "link_style_models_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/animatediff_models 目录\n", "link_animatediff_models_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/animatediff_motion_lora 目录\n", "link_animatediff_motion_lora_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/gligen 目录\n", "link_gligen_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/hypernetworks 目录\n", "link_hypernetworks_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/kgen 目录\n", "link_kgen_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/layer_model 目录\n", "link_layer_model_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/mmdets 目录\n", "link_mmdets_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/model_patches 目录\n", "link_model_patches_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/onnx 目录\n", "link_onnx_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/photomaker 目录\n", "link_photomaker_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/sams 目录\n", "link_sams_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/ultralytics 目录\n", "link_ultralytics_dir = False # @param {type:\"boolean\"}\n", "#@markdown - custom_nodes 目录\n", "link_custom_nodes_dir = False # @param {type:\"boolean\"}\n", "#@markdown - alembic_db 目录\n", "link_alembic_db_dir = False # @param {type:\"boolean\"}\n", "#@markdown - alembic.ini 文件\n", "link_alembic_ini_file = False # @param {type:\"boolean\"}\n", "\n", "\n", "link_checkpoints_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/checkpoints\"})\n", "link_diffusers_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/diffusers\"})\n", "link_unet_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/unet\"})\n", "link_text_encoders_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/text_encoders\"})\n", "link_clip_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/clip\"})\n", "link_clip_vision_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/clip_vision\"})\n", "link_diffusion_models_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/diffusion_models\"})\n", "link_loras_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/loras\"})\n", "link_vae_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/vae\"})\n", "link_controlnet_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/controlnet\"})\n", "link_embeddings_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/embeddings\"})\n", "link_upscale_models_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/upscale_models\"})\n", "link_vae_approx_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/vae_approx\"})\n", "link_style_models_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/style_models\"})\n", "link_animatediff_models_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/animatediff_models\"})\n", "link_animatediff_motion_lora_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/animatediff_motion_lora\"})\n", "link_gligen_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/gligen\"})\n", "link_hypernetworks_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/hypernetworks\"})\n", "link_kgen_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/kgen\"})\n", "link_layer_model_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/layer_model\"})\n", "link_mmdets_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/mmdets\"})\n", "link_model_patches_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/model_patches\"})\n", "link_onnx_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/onnx\"})\n", "link_photomaker_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/photomaker\"})\n", "link_sams_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/sams\"})\n", "link_ultralytics_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/ultralytics\"})\n", "link_custom_nodes_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"custom_nodes\"})\n", "link_alembic_db_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"alembic_db\"})\n", "link_alembic_ini_file and EXTRA_LINK_DIR.append({\"link_dir\": \"alembic.ini\", \"is_file\": True})\n", "\n", "##############################################################################\n", "\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": PYTORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Colab 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"comfyui_repo\": COMFYUI_REPO or None,\n", " \"comfyui_requirements\": COMFYUI_REQUIREMENTS or None,\n", " \"comfyui_setting\": COMFYUI_SETTING or None,\n", " \"custom_node_list\": CUSTOM_NODE_LIST,\n", " \"model_list\": SD_MODEL,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"huggingface_token\": None,\n", " \"modelscope_token\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "\n", "TUNNEL_PARAMS = {\n", " \"use_ngrok\": USE_NGROK,\n", " \"ngrok_token\": NGROK_TOKEN or None,\n", " \"use_cloudflare\": USE_CLOUDFLARE,\n", " \"use_remote_moe\": USE_REMOTE_MOE,\n", " \"use_localhost_run\": USE_LOCALHOST_RUN,\n", " \"use_gradio\": USE_GRADIO,\n", " \"use_pinggy_io\": USE_PINGGY_IO,\n", " \"use_zrok\": USE_ZROK,\n", " \"zrok_token\": ZROK_TOKEN or None,\n", " \"message\": \"##### ComfyUI 访问地址 #####\",\n", "}\n", "\n", "COMFYUI_PATH = \"/content/ComfyUI\"\n", "try:\n", " _ = comfyui_manager_has_init # noqa: F821\n", "except Exception:\n", " comfyui = ComfyUIManager(os.path.dirname(COMFYUI_PATH), os.path.basename(COMFYUI_PATH), port=8188)\n", " comfyui_manager_has_init = True\n", "\n", "try:\n", " _ = comfyui_has_init # noqa: F821\n", "except Exception:\n", " comfyui_has_init = False\n", "\n", "if NO_REPEAT_CONFIGURE_ENV:\n", " if not comfyui_has_init:\n", " comfyui.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " comfyui_has_init = True\n", " CLEAR_LOG and comfyui.clear_up()\n", " logger.info(\"ComfyUI 运行环境配置完成\")\n", " else:\n", " logger.info(\"检测到不重复配置环境已启用, 并且在当前 Colab 实例中已配置 ComfyUI 运行环境, 不再重复配置 ComfyUI 运行环境\")\n", " logger.info(\"如需在当前 Colab 实例中重新配置 ComfyUI 运行环境, 请在快速启动选项中取消不重复配置环境功能\")\n", "else:\n", " comfyui.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " CLEAR_LOG and comfyui.clear_up()\n", " logger.info(\"ComfyUI 运行环境配置完成\")\n", "\n", "LAUNCH_CMD = comfyui.get_launch_command(COMFYUI_LAUNCH_ARGS)\n", "\n", "if QUICK_LAUNCH:\n", " logger.info(\"启动 ComfyUI 中\")\n", " os.chdir(COMFYUI_PATH)\n", " comfyui.check_env(\n", " use_uv=USE_UV,\n", " install_conflict_component_requirement=INSTALL_CONFLICT_COMPONENT,\n", " requirements_file=COMFYUI_REQUIREMENTS,\n", " )\n", " comfyui.mount_drive(EXTRA_LINK_DIR)\n", " comfyui.tun.start_tunnel(**TUNNEL_PARAMS)\n", " logger.info(\"ComfyUI 启动参数: %s\", COMFYUI_LAUNCH_ARGS)\n", " !{LAUNCH_CMD}\n", " os.chdir(JUPYTER_ROOT_PATH)\n", " CLEAR_LOG and comfyui.clear_up()\n", " logger.info(\"已关闭 ComfyUI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "ZWnei0cZwWzK" }, "outputs": [], "source": [ "#@title 👇 下载模型(可选)\n", "\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 ComfyUI\")\n", "\n", "#@markdown 选择下载的模型:\n", "##############################\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = False # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = False # @param {type:\"boolean\"}\n", "# @markdown - Upscale 模型\n", "upscale_dat_x2 = False # @param {type:\"boolean\"}\n", "upscale_dat_x3 = False # @param {type:\"boolean\"}\n", "upscale_dat_x4 = False # @param {type:\"boolean\"}\n", "upscale_4x_nmkd_superscale_sp_178000_g = False # @param {type:\"boolean\"}\n", "upscale_8x_nmkd_superscale_150000_g = False # @param {type:\"boolean\"}\n", "upscale_lollypop = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus_anime_6b = False # @param {type:\"boolean\"}\n", "upscale_swinir_4x = False # @param {type:\"boolean\"}\n", "# @markdown - ControlNet 模型\n", "illustriousxlcanny_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineart_v10 = False # @param {type:\"boolean\"}\n", "illustriousxldepth_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlsoftedge_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineartrrealistic_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlshuffle_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlopenpose_v10 = False # @param {type:\"boolean\"}\n", "illustriousxltile_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlv0_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_canny_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_depth_midas_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_tile_fp16 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epscanny = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartanime = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsnormalmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epssoftedgehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsmangaline = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartrealistic = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidasv11 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblepidinet = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_openposemodel = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epstile = False # @param {type:\"boolean\"}\n", "noobai_inpainting_controlnet = False # @param {type:\"boolean\"}\n", "noobipamark1_mark1 = False # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", \"type\": \"checkpoints\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", \"type\": \"checkpoints\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", \"type\": \"checkpoints\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", \"type\": \"checkpoints\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", \"type\": \"checkpoints\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", \"type\": \"checkpoints\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", \"type\": \"checkpoints\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", \"type\": \"checkpoints\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", \"type\": \"checkpoints\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", \"type\": \"checkpoints\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", \"type\": \"checkpoints\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", \"type\": \"checkpoints\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", \"type\": \"checkpoints\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", \"type\": \"checkpoints\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", \"type\": \"checkpoints\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", \"type\": \"checkpoints\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", \"type\": \"vae\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", \"type\": \"vae\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", \"type\": \"vae\"})\n", "# 放大模型\n", "upscale_dat_x2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", \"type\": \"upscale_models\"})\n", "upscale_dat_x3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", \"type\": \"upscale_models\"})\n", "upscale_dat_x4 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", \"type\": \"upscale_models\"})\n", "upscale_4x_nmkd_superscale_sp_178000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", \"type\": \"upscale_models\"})\n", "upscale_8x_nmkd_superscale_150000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/8x_NMKD-Superscale_150000_G.pth\", \"type\": \"upscale_models\"})\n", "upscale_lollypop and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/lollypop.pth\", \"type\": \"upscale_models\"})\n", "upscale_realesrgan_x4plus and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", \"type\": \"upscale_models\"})\n", "upscale_realesrgan_x4plus_anime_6b and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", \"type\": \"upscale_models\"})\n", "upscale_swinir_4x and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/SwinIR/SwinIR_4x.pth\", \"type\": \"upscale_models\"})\n", "# ControlNet 模型\n", "illustriousxlcanny_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLCanny_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxllineart_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineart_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxldepth_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLDepth_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlsoftedge_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLSoftedge_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxllineartrrealistic_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineartRrealistic_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlshuffle_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLShuffle_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlopenpose_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLOpenPose_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxltile_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLTile_v10.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv0_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv0.1_inpainting_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_canny_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_canny_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_depth_midas_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_depth_midas_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_inpainting_fp16.safetensors\", \"type\": \"controlnet\"})\n", "illustriousxlv1_1_tile_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_tile_fp16.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epscanny and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsCanny.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsdepthmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidas.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epslineartanime and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartAnime.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsnormalmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsNormalMidas.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epssoftedgehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsSoftedgeHed.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsmangaline and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsMangaLine.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epslineartrealistic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartRealistic.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsdepthmidasv11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidasV11.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsscribblehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribbleHed.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epsscribblepidinet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribblePidinet.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_openposemodel and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_openposeModel.safetensors\", \"type\": \"controlnet\"})\n", "noobaixlcontrolnet_epstile and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsTile.safetensors\", \"type\": \"controlnet\"})\n", "noobai_inpainting_controlnet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/NoobAI_Inpainting_ControlNet.safetensors\", \"type\": \"controlnet\"})\n", "noobipamark1_mark1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/noobIPAMARK1_mark1.safetensors\", \"type\": \"controlnet\"})\n", "\n", "##############################\n", "logger.info(\"下载模型中\")\n", "comfyui.get_sd_model_from_list(SD_MODEL)\n", "CLEAR_LOG and comfyui.clear_up()\n", "logger.info(\"模型下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MbpZVvRMPIAC" }, "outputs": [], "source": [ "#@title 👇 自定义模型下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 ComfyUI\")\n", "\n", "#@markdown ### 选择模型种类:\n", "model_type = \"loras\" # @param [\"checkpoints\", \"diffusers\", \"unet\", \"text_encoders\", \"clip\", \"clip_vision\", \"diffusion_models\", \"loras\", \"vae\", \"controlnet\", \"embeddings\", \"upscale_models\", \"vae_approx\", \"style_models\", \"animatediff_models\", \"animatediff_motion_lora\", \"gligen\", \"hypernetworks\", \"kgen\", \"layer_model\", \"mmdets\", \"model_patches\", \"onnx\", \"photomaker\", \"sams\", \"ultralytics\"]\n", "#@markdown ### 填写模型的下载链接:\n", "model_url = \"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "#@markdown ### 填写模型的名称(包括后缀名):\n", "model_name = \"CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "\n", "comfyui.get_sd_model(\n", " url=model_url,\n", " filename=model_name or None,\n", " model_type=model_type,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "8y0FPv15wHP9" }, "outputs": [], "source": [ "#@title 👇 自定义节点下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 ComfyUI\")\n", "\n", "#@markdown ### 填写自定义节点的下载链接:\n", "custom_node_url = \"https://github.com/QuangLe97/ComfyUI-rgthree-comfy\" #@param {type:\"string\"}\n", "\n", "comfyui.install_custom_node(custom_node_url)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "cLB6sKhErcG8" }, "outputs": [], "source": [ "#@title 👇 启动 ComfyUI\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 ComfyUI\")\n", "\n", "logger.info(\"启动 ComfyUI\")\n", "os.chdir(COMFYUI_PATH)\n", "comfyui.check_env(\n", " use_uv=USE_UV,\n", " install_conflict_component_requirement=INSTALL_CONFLICT_COMPONENT,\n", " requirements_file=COMFYUI_REQUIREMENTS,\n", ")\n", "comfyui.mount_drive(EXTRA_LINK_DIR)\n", "comfyui.tun.start_tunnel(**TUNNEL_PARAMS)\n", "logger.info(\"ComfyUI 启动参数: %s\", COMFYUI_LAUNCH_ARGS)\n", "!{LAUNCH_CMD}\n", "os.chdir(JUPYTER_ROOT_PATH)\n", "CLEAR_LOG and comfyui.clear_up()\n", "logger.info(\"已关闭 ComfyUI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "4FHCvTL1XFqO" }, "outputs": [], "source": [ "#@title 👇 文件下载工具\n", "\n", "#@markdown ### 填写文件的下载链接:\n", "url = \"\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存路径:\n", "file_path = \"/content\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存名称 (可选):\n", "filename = \"\" #@param {type:\"string\"}\n", "\n", "comfyui.download_file(\n", " url=url,\n", " path=file_path or None,\n", " save_name=filename or None,\n", ")\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/comfyui_colab.ipynb
Jupyter Notebook
agpl-3.0
80,733
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xlyptNJ2ICnN" }, "source": [ "# Fooooooooooooooocus\n", "Colab NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Colab](https://colab.research.google.com) 部署 [Fooocus](https://github.com/lllyasviel/Fooocus) 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "Colab 链接:<a href=\"https://colab.research.google.com/github/licyk/sd-webui-all-in-one/blob/main/notebook/fooocus_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式,并安装 [Fooocus](https://github.com/lllyasviel/Fooocus),默认设置下已启用`配置环境完成后立即启动 Fooocus`选项,则安装完成后将直接启动 Fooocus,并显示访问地址。\n", "2. 下载模型:下载可选列表中的模型(可选)。\n", "3. 自定义模型下载:使用链接下载模型(可选)。\n", "4. 启动 Fooocus:启动 Fooocus,并显示访问地址。\n", "\n", "\n", "## 使用\n", "1. 在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择`GPU T4`或者其他 GPU。\n", "2. `环境配置`单元中的选项通常不需要修改,保持默认即可。\n", "3. 运行`环境配置`单元,默认设置下已启用`配置环境完成后立即启动 Fooocus`选项,则环境配置完成后立即启动 Fooocus,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 Fooocus,Fooocus 的访问地址可在日志中查看。\n", "4. 如果未启用`配置环境完成后立即启动 Fooocus`选项,需要运行`启动 Fooocus`单元,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 Fooocus,Fooocus 的访问地址可在日志中查看。\n", "5. 提示词查询工具:[SD 绘画提示词查询](https://licyk.github.io/t/tag)\n", "\n", "## 提示\n", "1. Colab 在关机后将会清除所有数据,所以每次重新启动时必须运行`环境配置`单元才能运行`启动 Fooocus`单元。\n", "2. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "3. [Zrok](https://zrok.io) 内网穿透在使用前需要填写 Zrok Token, 可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取。\n", "4. 每次启动 Colab 后必须运行`环境配置`单元,才能运行`启动 Fooocus`单元启动 Fooocus。\n", "5. 其他功能有自定义模型下载等功能,根据自己的需求进行使用。\n", "6. 运行`启动 Fooocus`时将弹出 Google Drive 访问授权提示,根据提示进行授权。授权后,使用 Fooocus 生成的图片将保存在 Google Drive 的`fooocus_output`文件夹中。\n", "7. Gradio 的内网穿透地址可在启动 Fooocus 后日志中的`Running on public URL`查看。\n", "8. Fooocus 启动预设文件可自行编写,并上传到 Github 或者其他平台并获取下载链接后,可以替换`Fooocus 启动预设文件地址`中的链接,进行环境配置时将使用该预设文件启动 Fooocus。预设文件可自行下载下来进行参考,其他有关说明可阅读:[Customization - lllyasviel/Fooocus](https://github.com/lllyasviel/Fooocus?tab=readme-ov-file#customization)。\n", "9. 在`额外挂载目录设置`中可以挂载一些额外目录,如 LoRA 模型目录,挂载后的目录可在 Google Drive 的`fooocus_output`文件夹中查看和修改。可通过该功能在 Google Drive 上传模型并在 Fooocus 中使用。\n", "10. 默认挂载以下目录到 Google Drive,可在 Google Drive 的`fooocus_output`文件夹中上传和修改文件:`outputs`, `presets`, `language`, `wildcards`, `config.txt`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "VjYy0F2gZIPR" }, "outputs": [], "source": [ "#@title 👇 环境配置\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, FooocusManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "\n", "#######################################################\n", "\n", "#@markdown ## Fooocus 核心配置选项\n", "#@markdown - Fooocus 分支仓库地址:\n", "FOOOCUS_REPO = \"https://github.com/lllyasviel/Fooocus\" #@param {type:\"string\"}\n", "#@markdown - Fooocus 启动预设文件地址:\n", "FOOOCUS_PRESET = \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/fooocus_config.json\" #@param {type:\"string\"}\n", "#@markdown - Fooocus 翻译文件下载地址:\n", "FOOOCUS_TRANSLATION = \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/fooocus_zh_cn.json\" #@param {type:\"string\"}\n", "#@markdown - Fooocus 依赖表名:\n", "FOOOCUS_REQUIREMENTS = \"requirements_versions.txt\" #@param {type:\"string\"}\n", "#@markdown - Fooocus 启动参数:\n", "FOOOCUS_LAUNCH_ARGS = \"--preset custom --language zh --async-cuda-allocation --disable-analytics --always-high-vram --always-download-new-model\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## PyTorch 组件版本选项:\n", "#@markdown - PyTorch:\n", "PYTORCH_VER = \"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126\" #@param {type:\"string\"}\n", "#@markdown - xFormers:\n", "XFORMERS_VER = \"xformers==0.0.32.post2\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 包管理器选项:\n", "#@markdown - 使用 uv 作为 Python 包管理器\n", "USE_UV = True #@param {type:\"boolean\"}\n", "#@markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" #@param {type:\"string\"}\n", "#@markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"\" #@param {type:\"string\"}\n", "#@markdown - PyTorch 镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 内网穿透选项:\n", "#@markdown - 使用 remote.moe 内网穿透\n", "USE_REMOTE_MOE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 localhost.run 内网穿透\n", "USE_LOCALHOST_RUN = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 pinggy.io 内网穿透\n", "USE_PINGGY_IO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 CloudFlare 内网穿透\n", "USE_CLOUDFLARE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Gradio 内网穿透\n", "USE_GRADIO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Ngrok 内网穿透(需填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取)\n", "USE_NGROK = True #@param {type:\"boolean\"}\n", "#@markdown - Ngrok Token\n", "NGROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown - 使用 Zrok 内网穿透(需填写 Zrok Token,可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取)\n", "USE_ZROK = True #@param {type:\"boolean\"}\n", "#@markdown - Zrok Token\n", "ZROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 快速启动选项:\n", "#@markdown - 配置环境完成后立即启动 Fooocus(并挂载 Google Drive)\n", "QUICK_LAUNCH = True #@param {type:\"boolean\"}\n", "#@markdown - 不重复配置环境(当重复运行环境配置时将不会再进行安装)\n", "NO_REPEAT_CONFIGURE_ENV = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "#@markdown ## 其他选项:\n", "#@markdown - 预下载模型时使用的下载器\n", "MODEL_DOWNLOADER = \"mix\" #@param [\"aria2\", \"requests\", \"mix\"]\n", "#@markdown - 预下载模型时下载线程\n", "DOWNLOAD_MODEL_THREAD = 16 #@param {type:\"slider\", min:1, max:64, step:1}\n", "#@markdown - 清理无用日志\n", "CLEAR_LOG = True #@param {type:\"boolean\"}\n", "#@markdown - 检查可用 GPU\n", "CHECK_AVALIABLE_GPU = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 额外挂载目录设置, 在启动时挂载目录到 Google Drive:\n", "EXTRA_LINK_DIR = []\n", "\n", "#@markdown - models/checkpoints 目录\n", "link_checkpoints_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/loras 目录\n", "link_loras_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/embeddings 目录\n", "link_embeddings_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/vae_approx 目录\n", "link_vae_approx_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/vae 目录\n", "link_vae_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/upscale_models 目录\n", "link_upscale_models_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/inpaint 目录\n", "link_inpaint_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/controlnet 目录\n", "link_controlnet_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/clip_vision 目录\n", "link_clip_vision_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/prompt_expansion 目录\n", "link_prompt_expansion_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/safety_checker 目录\n", "link_safety_checker_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/sam 目录\n", "link_sam_dir = False # @param {type:\"boolean\"}\n", "\n", "\n", "link_checkpoints_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/checkpoints\"})\n", "link_loras_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/loras\"})\n", "link_embeddings_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/embeddings\"})\n", "link_vae_approx_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/vae_approx\"})\n", "link_vae_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/vae\"})\n", "link_upscale_models_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/upscale_models\"})\n", "link_inpaint_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/inpaint\"})\n", "link_controlnet_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/controlnet\"})\n", "link_clip_vision_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/clip_vision\"})\n", "link_prompt_expansion_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/prompt_expansion\"})\n", "link_safety_checker_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/safety_checker\"})\n", "link_sam_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/sam\"})\n", "\n", "#######################################################\n", "\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": PYTORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Colab 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"fooocus_repo\": FOOOCUS_REPO or None,\n", " \"fooocus_requirements\": FOOOCUS_REQUIREMENTS or None,\n", " \"fooocus_preset\": FOOOCUS_PRESET or None,\n", " \"fooocus_translation\": FOOOCUS_TRANSLATION or None,\n", " \"model_downloader\": MODEL_DOWNLOADER,\n", " \"download_model_thread\": DOWNLOAD_MODEL_THREAD,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"huggingface_token\": None,\n", " \"modelscope_token\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "\n", "TUNNEL_PARAMS = {\n", " \"use_ngrok\": USE_NGROK,\n", " \"ngrok_token\": NGROK_TOKEN or None,\n", " \"use_cloudflare\": USE_CLOUDFLARE,\n", " \"use_remote_moe\": USE_REMOTE_MOE,\n", " \"use_localhost_run\": USE_LOCALHOST_RUN,\n", " \"use_gradio\": USE_GRADIO,\n", " \"use_pinggy_io\": USE_PINGGY_IO,\n", " \"use_zrok\": USE_ZROK,\n", " \"zrok_token\": ZROK_TOKEN or None,\n", " \"message\": \"##### Fooocus 访问地址 #####\",\n", "}\n", "\n", "FOOOCUS_PATH = \"/content/Fooocus\"\n", "try:\n", " _ = fooocus_manager_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " fooocus = FooocusManager(os.path.dirname(FOOOCUS_PATH), os.path.basename(FOOOCUS_PATH), port=7865)\n", " fooocus_manager_has_init = True\n", "\n", "try:\n", " _ = fooocus_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " fooocus_has_init = False\n", "\n", "if NO_REPEAT_CONFIGURE_ENV:\n", " if not fooocus_has_init:\n", " fooocus.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " fooocus_has_init = True\n", " CLEAR_LOG and fooocus.clear_up()\n", " logger.info(\"Fooocus 运行环境配置完成\")\n", " else:\n", " logger.info(\"检测到不重复配置环境已启用, 并且在当前 Colab 实例中已配置 Fooocus 运行环境, 不再重复配置 Fooocus 运行环境\")\n", " logger.info(\"如需在当前 Colab 实例中重新配置 Fooocus 运行环境, 请在快速启动选项中取消不重复配置环境功能\")\n", "else:\n", " fooocus.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " CLEAR_LOG and fooocus.clear_up()\n", " logger.info(\"Fooocus 运行环境配置完成\")\n", "\n", "if USE_GRADIO:\n", " FOOOCUS_LAUNCH_ARGS = f\"{FOOOCUS_LAUNCH_ARGS} --share\"\n", "\n", "LAUNCH_CMD = fooocus.get_launch_command(FOOOCUS_LAUNCH_ARGS)\n", "\n", "if QUICK_LAUNCH:\n", " logger.info(\"启动 Fooocus 中\")\n", " os.chdir(FOOOCUS_PATH)\n", " fooocus.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=FOOOCUS_REQUIREMENTS,\n", " )\n", " fooocus.mount_drive(EXTRA_LINK_DIR)\n", " fooocus.tun.start_tunnel(**TUNNEL_PARAMS)\n", " logger.info(\"Fooocus 启动参数: %s\", FOOOCUS_LAUNCH_ARGS)\n", " !{LAUNCH_CMD}\n", " CLEAR_LOG and fooocus.clear_up()\n", " logger.info(\"已关闭 Fooocus\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "ZWnei0cZwWzK" }, "outputs": [], "source": [ "#@title 👇 下载模型(可选)\n", "\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Fooocus\")\n", "\n", "# 模型下载\n", "logger.info(\"下载模型中\")\n", "MODEL_LIST = []\n", "#@markdown 选择下载的模型:\n", "##############################\n", "\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "animapencilxl_v200 = False # @param {type:\"boolean\"}\n", "bluepencilxl_v401 = False # @param {type:\"boolean\"}\n", "anythingxl_xl = False # @param {type:\"boolean\"}\n", "abyssorangexlelse_v10 = False # @param {type:\"boolean\"}\n", "counterfeitxl_v1_0 = False # @param {type:\"boolean\"}\n", "animeillustdiffusion_v061 = False # @param {type:\"boolean\"}\n", "nekorayxl_v06w3 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "heartofapplexl_v20 = False # @param {type:\"boolean\"}\n", "heartofapplexl_v30 = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "sd_xl_anime_v52 = False # @param {type:\"boolean\"}\n", "kohaku_xl_gamma_rev1 = False # @param {type:\"boolean\"}\n", "kohakuxlbeta_beta7 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryxlv52_v52 = False # @param {type:\"boolean\"}\n", "baxlbartstylexlbluearchiveflatcelluloid_xlv1 = False # @param {type:\"boolean\"}\n", "baxlbluearchiveflatcelluloidstyle_xlv3 = False # @param {type:\"boolean\"}\n", "ponydiffusionv6xl_v6startwiththisone = False # @param {type:\"boolean\"}\n", "pdforanime_v20 = False # @param {type:\"boolean\"}\n", "tponynai3_v51weightoptimized = False # @param {type:\"boolean\"}\n", "omegaponyxlanime_v20 = False # @param {type:\"boolean\"}\n", "illustrious_xl_v0_1 = False # @param {type:\"boolean\"}\n", "illustrious_xl_v1_0 = False # @param {type:\"boolean\"}\n", "illustrious_xl_v1_1 = False # @param {type:\"boolean\"}\n", "illustrious_xl_v2_0_stable = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_earlyaccessversion = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_epsilonpred05version = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_epsilonpred075 = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_epsilonpred077 = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_epsilonpred10version = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_epsilonpred11version = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpredtestversion = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred05version = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred06version = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred065sversion = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred075sversion = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred09rversion = False # @param {type:\"boolean\"}\n", "noobaixlnaixl_vpred10version = False # @param {type:\"boolean\"}\n", "\n", "\n", "sd_xl_base_1_0_0_9vae and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", \"type\": \"checkpoints\"})\n", "animapencilxl_v200 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animaPencilXL_v200.safetensors\", \"type\": \"checkpoints\"})\n", "bluepencilxl_v401 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/bluePencilXL_v401.safetensors\", \"type\": \"checkpoints\"})\n", "anythingxl_xl and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/AnythingXL_xl.safetensors\", \"type\": \"checkpoints\"})\n", "abyssorangexlelse_v10 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/abyssorangeXLElse_v10.safetensors\", \"type\": \"checkpoints\"})\n", "counterfeitxl_v1_0 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/CounterfeitXL-V1.0.safetensors\", \"type\": \"checkpoints\"})\n", "animeillustdiffusion_v061 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animeIllustDiffusion_v061.safetensors\", \"type\": \"checkpoints\"})\n", "nekorayxl_v06w3 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/nekorayxl_v06W3.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_0 and MODEL_LIST.append({\"url\": \"https://huggingface.co/cagliostrolab/animagine-xl-3.0/resolve/main/animagine-xl-3.0.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_3_1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/cagliostrolab/animagine-xl-3.1/resolve/main/animagine-xl-3.1.safetensors\", \"type\": \"checkpoints\"})\n", "animagine_xl_4_0 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", \"type\": \"checkpoints\"})\n", "heartofapplexl_v20 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", \"type\": \"checkpoints\"})\n", "heartofapplexl_v30 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", \"type\": \"checkpoints\"})\n", "holodayo_xl_2_1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", \"type\": \"checkpoints\"})\n", "kivotos_xl_2_0 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", \"type\": \"checkpoints\"})\n", "sd_xl_anime_v52 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_anime_V52.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_gamma_rev1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-gamma/resolve/main/kohaku-xl-gamma-rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohakuxlbeta_beta7 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLBeta_beta7.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_delta_rev1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-Delta/resolve/main/kohaku-xl-delta-rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-Epsilon/resolve/main/kohaku-xl-epsilon-rev1.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev2 and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-Epsilon-rev2/resolve/main/kohaku-xl-epsilon-rev2.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_epsilon_rev3 and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-Epsilon-rev3/resolve/main/kohaku-xl-epsilon-rev3.safetensors\", \"type\": \"checkpoints\"})\n", "kohaku_xl_zeta and MODEL_LIST.append({\"url\": \"https://huggingface.co/KBlueLeaf/Kohaku-XL-Zeta/resolve/main/kohaku-xl-zeta.safetensors\", \"type\": \"checkpoints\"})\n", "starryxlv52_v52 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", \"type\": \"checkpoints\"})\n", "baxlbartstylexlbluearchiveflatcelluloid_xlv1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors\", \"type\": \"checkpoints\"})\n", "baxlbluearchiveflatcelluloidstyle_xlv3 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors\", \"type\": \"checkpoints\"})\n", "ponydiffusionv6xl_v6startwiththisone and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", \"type\": \"checkpoints\"})\n", "pdforanime_v20 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "tponynai3_v51weightoptimized and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors\", \"type\": \"checkpoints\"})\n", "omegaponyxlanime_v20 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", \"type\": \"checkpoints\"})\n", "illustrious_xl_v0_1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", \"type\": \"checkpoints\"})\n", "illustrious_xl_v1_0 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", \"type\": \"checkpoints\"})\n", "illustrious_xl_v1_1 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", \"type\": \"checkpoints\"})\n", "illustrious_xl_v2_0_stable and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_earlyaccessversion and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_epsilonpred05version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_epsilonpred075 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_epsilonpred077 and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_epsilonpred10version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_epsilonpred11version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpredtestversion and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred05version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred06version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred065sversion and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred075sversion and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred09rversion and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", \"type\": \"checkpoints\"})\n", "noobaixlnaixl_vpred10version and MODEL_LIST.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", \"type\": \"checkpoints\"})\n", "\n", "##############################\n", "fooocus.get_sd_model_from_list(MODEL_LIST)\n", "CLEAR_LOG and fooocus.clear_up()\n", "logger.info(\"模型下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MbpZVvRMPIAC" }, "outputs": [], "source": [ "#@title 👇 自定义模型下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Fooocus\")\n", "\n", "#@markdown ### 选择模型种类:\n", "model_type = \"loras\" # @param [\"checkpoints\", \"loras\", \"embeddings\", \"vae_approx\", \"vae\", \"upscale_models\", \"inpaint\", \"controlnet\", \"clip_vision\", \"prompt_expansion\", \"safety_checker\", \"sam\"]\n", "#@markdown ### 填写模型的下载链接:\n", "model_url = \"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "#@markdown ### 填写模型的名称(包括后缀名):\n", "model_name = \"CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "\n", "fooocus.get_sd_model(\n", " url=model_url,\n", " filename=model_name or None,\n", " model_type=model_type,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "cLB6sKhErcG8" }, "outputs": [], "source": [ "#@title 👇 启动 Fooocus\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Fooocus\")\n", "\n", "logger.info(\"启动 Fooocus\")\n", "os.chdir(FOOOCUS_PATH)\n", "fooocus.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=FOOOCUS_REQUIREMENTS,\n", ")\n", "fooocus.mount_drive(EXTRA_LINK_DIR)\n", "fooocus.tun.start_tunnel(**TUNNEL_PARAMS)\n", "logger.info(\"Fooocus 启动参数: %s\", FOOOCUS_LAUNCH_ARGS)\n", "!{LAUNCH_CMD}\n", "CLEAR_LOG and fooocus.clear_up()\n", "logger.info(\"已关闭 Fooocus\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "98sWyzwpXcR8" }, "outputs": [], "source": [ "#@title 👇 文件下载工具\n", "\n", "#@markdown ### 填写文件的下载链接:\n", "url = \"\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存路径:\n", "file_path = \"/content\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存名称 (可选):\n", "filename = \"\" #@param {type:\"string\"}\n", "\n", "fooocus.download_file(\n", " url=url,\n", " path=file_path or None,\n", " save_name=filename or None,\n", ")\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/fooocus_colab.ipynb
Jupyter Notebook
agpl-3.0
35,172
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Foooooooooooocus\n", "#### Kaggle NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Kaggle](https://www.kaggle.com) 部署 Fooocus 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式。\n", "2. 安装 Fooocus:根据环境配置安装 Fooocus 和运行环境。\n", "3. 下载模型:下载可选列表中的模型。\n", "4. 启动 Fooocus:启动 Fooocus,并显示访问地址。\n", "\n", "## 提示\n", "1. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "2. 已知 CloudFlare、Gradio 内网穿透会导致 [Kaggle](https://www.kaggle.com) 平台强制关机,在使用 [Kaggle](https://www.kaggle.com) 平台时请勿勾选这两个选项。\n", "3. 请不要生成违禁图片,这将导致 Kaggle 账号被永久封禁!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 参数配置\n", "1. [[下一个单元 →](#安装-Fooocus)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 消息格式输出\n", "def echo(*args):\n", " for i in args:\n", " print(f\":: {i}\")\n", "\n", "\n", "\n", "# ARIA2\n", "class ARIA2:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载器\n", " def aria2(self, url, path, filename):\n", " import os\n", " if not os.path.exists(path + \"/\" + filename):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " if os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " echo(f\"{filename} 文件已存在,路径: {path}/{filename}\")\n", "\n", "\n", " # 大模型下载\n", " def get_sd_model(self, url, filename):\n", " pass\n", "\n", "\n", " # lora下载\n", " def get_lora_model(self, url, filename):\n", " pass\n", "\n", "\n", "\n", "# GIT\n", "class GIT:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 检测要克隆的项目是否存在于指定路径\n", " def exists(self, addr=None, path=None, name=None):\n", " import os\n", " if addr is not None:\n", " if path is None and name is None:\n", " path = os.getcwd() + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " elif path is None and name is not None:\n", " path = os.getcwd() + \"/\" + name\n", " elif path is not None and name is None:\n", " path = os.path.normpath(path) + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", "\n", " if os.path.exists(path):\n", " return True\n", " else:\n", " return False\n", "\n", "\n", " # 克隆项目\n", " def clone(self, addr, path=None, name=None):\n", " import os\n", " repo = addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " if not self.exists(addr, path, name):\n", " echo(f\"开始下载 {repo}\")\n", " if path is None and name is None:\n", " path = os.getcwd()\n", " name = repo\n", " elif path is not None and name is None:\n", " name = repo\n", " elif path is None and name is not None:\n", " path = os.getcwd()\n", " !git clone {addr} \"{path}/{name}\" --recurse-submodules\n", " else:\n", " echo(f\"{repo} 已存在\")\n", "\n", "\n", "\n", "# TUNNEL\n", "class TUNNEL:\n", " LOCALHOST_RUN = \"localhost.run\"\n", " REMOTE_MOE = \"remote.moe\"\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", " PORT = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder, port) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", " self.PORT = port\n", "\n", "\n", " # ngrok内网穿透\n", " def ngrok(self, ngrok_token: str):\n", " from pyngrok import conf, ngrok\n", " conf.get_default().auth_token = ngrok_token\n", " conf.get_default().monitor_thread = False\n", " port = self.PORT\n", " ssh_tunnels = ngrok.get_tunnels(conf.get_default())\n", " if len(ssh_tunnels) == 0:\n", " ssh_tunnel = ngrok.connect(port, bind_tls=True)\n", " return ssh_tunnel.public_url\n", " else:\n", " return ssh_tunnels[0].public_url\n", "\n", "\n", " # cloudflare内网穿透\n", " def cloudflare(self):\n", " from pycloudflared import try_cloudflare\n", " port = self.PORT\n", " urls = try_cloudflare(port).tunnel\n", " return urls\n", "\n", "\n", " from typing import Union\n", " from pathlib import Path\n", "\n", " # 生成ssh密钥\n", " def gen_key(self, path: Union[str, Path]) -> None:\n", " import subprocess\n", " import shlex\n", " from pathlib import Path\n", " path = Path(path)\n", " arg_string = f'ssh-keygen -t rsa -b 4096 -N \"\" -q -f {path.as_posix()}'\n", " args = shlex.split(arg_string)\n", " subprocess.run(args, check=True)\n", " path.chmod(0o600)\n", "\n", "\n", " # ssh内网穿透\n", " def ssh_tunnel(self, host: str) -> None:\n", " import subprocess\n", " import atexit\n", " import shlex\n", " import re\n", " import os\n", " from pathlib import Path\n", " from tempfile import TemporaryDirectory\n", "\n", " ssh_name = \"id_rsa\"\n", " ssh_path = Path(self.WORKSPACE) / ssh_name\n", " port = self.PORT\n", "\n", " tmp = None\n", " if not ssh_path.exists():\n", " try:\n", " self.gen_key(ssh_path)\n", " # write permission error or etc\n", " except subprocess.CalledProcessError:\n", " tmp = TemporaryDirectory()\n", " ssh_path = Path(tmp.name) / ssh_name\n", " self.gen_key(ssh_path)\n", "\n", " arg_string = f\"ssh -R 80:127.0.0.1:{port} -o StrictHostKeyChecking=no -i {ssh_path.as_posix()} {host}\"\n", " args = shlex.split(arg_string)\n", "\n", " tunnel = subprocess.Popen(\n", " args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", " if tmp is not None:\n", " atexit.register(tmp.cleanup)\n", "\n", " tunnel_url = \"\"\n", " LOCALHOST_RUN = self.LOCALHOST_RUN\n", " lines = 27 if host == LOCALHOST_RUN else 5\n", " localhostrun_pattern = re.compile(r\"(?P<url>https?://\\S+\\.lhr\\.life)\")\n", " remotemoe_pattern = re.compile(r\"(?P<url>https?://\\S+\\.remote\\.moe)\")\n", " pattern = localhostrun_pattern if host == LOCALHOST_RUN else remotemoe_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", "\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " if lines == 27:\n", " os.environ['LOCALHOST_RUN'] = tunnel_url\n", " return tunnel_url\n", " else:\n", " os.environ['REMOTE_MOE'] = tunnel_url\n", " return tunnel_url\n", " # break\n", " else:\n", " echo(f\"启动 {host} 内网穿透失败\")\n", "\n", "\n", " # localhost.run穿透\n", " def localhost_run(self):\n", " urls = self.ssh_tunnel(self.LOCALHOST_RUN)\n", " return urls\n", "\n", "\n", " # remote.moe内网穿透\n", " def remote_moe(self):\n", " urls = self.ssh_tunnel(self.REMOTE_MOE)\n", " return urls\n", "\n", "\n", " # gradio内网穿透\n", " def gradio(self):\n", " import subprocess\n", " import shlex\n", " import atexit\n", " import re\n", " port = self.PORT\n", " cmd = f\"gradio-tunneling --port {port}\"\n", " cmd = shlex.split(cmd)\n", " tunnel = subprocess.Popen(\n", " cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", "\n", " tunnel_url = \"\"\n", " lines = 5\n", " gradio_pattern = re.compile(r\"(?P<url>https?://\\S+\\.gradio\\.live)\")\n", " pattern = gradio_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " return tunnel_url\n", " else:\n", " echo(f\"启动 Gradio 内网穿透失败\")\n", "\n", "\n", " # 启动内网穿透\n", " def start(self, ngrok=False, ngrok_token=None, cloudflare=False, remote_moe=False, localhost_run=False, gradio=False):\n", " if cloudflare is True or ngrok is True or ngrok_token is not None or remote_moe is True or localhost_run is True or gradio is True:\n", " echo(\"启动内网穿透\")\n", "\n", " if cloudflare is True:\n", " cloudflare_url = self.cloudflare()\n", " else:\n", " cloudflare_url = None\n", "\n", " if ngrok is True and ngrok_token is not None:\n", " ngrok_url = self.ngrok(ngrok_token)\n", " else:\n", " ngrok_url = None\n", "\n", " if remote_moe is True:\n", " remote_moe_url = self.remote_moe()\n", " else:\n", " remote_moe_url = None\n", "\n", " if localhost_run is True:\n", " localhost_run_url = self.localhost_run()\n", " else:\n", " localhost_run_url = None\n", "\n", " if gradio is True:\n", " gradio_url = self.gradio()\n", " else:\n", " gradio_url = None\n", "\n", " echo(\"下方为访问地址\")\n", " print(\"==================================================================================\")\n", " echo(f\"CloudFlare: {cloudflare_url}\")\n", " echo(f\"Ngrok: {ngrok_url}\")\n", " echo(f\"remote.moe: {remote_moe_url}\")\n", " echo(f\"localhost_run: {localhost_run_url}\")\n", " echo(f\"Gradio: {gradio_url}\")\n", " print(\"==================================================================================\")\n", "\n", "\n", "\n", "\n", "# ENV\n", "class ENV:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 准备ipynb笔记自身功能的依赖\n", " def prepare_env_depend(self, use_mirror=True):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " echo(\"安装自身组件依赖\")\n", " !pip install pyngrok pycloudflared gradio-tunneling {pip_mirror}\n", " !apt update\n", " !apt install aria2 ssh google-perftools -y\n", "\n", "\n", " # 安装pytorch和xformers\n", " def prepare_torch(self, torch_ver, xformers_ver, use_mirror=False):\n", " arg = \"--no-deps\"\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " if torch_ver != \"\":\n", " echo(\"安装 PyTorch\")\n", " !pip install {torch_ver} {pip_mirror}\n", " if xformers_ver != \"\":\n", " echo(\"安装 xFormers\")\n", " !pip install {xformers_ver} {pip_mirror} {arg}\n", "\n", "\n", " # python软件包安装\n", " # 可使用的操作:\n", " # 安装: install -> install\n", " # 仅安装: install_single -> install --no-deps\n", " # 强制重装: force_install -> install --force-reinstall\n", " # 仅强制重装: force_install_single -> install --force-reinstall --no-deps\n", " # 更新: update -> install --upgrade\n", " # 卸载: uninstall -y\n", " def py_pkg_manager(self, pkg, type=None, use_mirror=False):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " if type == \"install\":\n", " func = \"install\"\n", " args = \"\"\n", " elif type == \"install_single\":\n", " func = \"install\"\n", " args = \"--no-deps\"\n", " elif type == \"force_install\":\n", " func = \"install\"\n", " args = \"--force-reinstall\"\n", " elif type == \"force_install_single\":\n", " func = \"install\"\n", " args = \"install --force-reinstall --no-deps\"\n", " elif type == \"update\":\n", " func = \"install\"\n", " args = \"--upgrade\"\n", " elif type == \"uninstall\":\n", " func = \"uninstall\"\n", " args = \"-y\"\n", " pip_mirror = \"\"\n", " else:\n", " echo(f\"未知操作: {type}\")\n", " return\n", " echo(f\"执行操作: pip {func} {pkg} {args} {pip_mirror}\")\n", " !pip {func} {pkg} {args} {pip_mirror}\n", "\n", "\n", " # 安装requirements.txt依赖\n", " def install_requirements(self, path, use_mirror=False):\n", " import os\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " if os.path.exists(path):\n", " echo(\"安装依赖\")\n", " !pip install -r \"{path}\" {pip_mirror}\n", " else:\n", " echo(\"依赖文件路径为空\")\n", "\n", "\n", " # 配置内存优化\n", " def tcmalloc(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " os.environ[\"LD_PRELOAD\"] = \"/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4\"\n", "\n", "\n", "\n", "# MANAGER\n", "class MANAGER:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 清理ipynb笔记的输出\n", " def clear_up(self, opt):\n", " from IPython.display import clear_output\n", " clear_output(wait=opt)\n", "\n", "\n", " # 检查gpu是否可用\n", " def check_gpu(self):\n", " echo(\"检测 GPU 是否可用\")\n", " import tensorflow as tf\n", " echo(f\"TensorFlow 版本: {tf.__version__}\")\n", " if tf.test.gpu_device_name():\n", " echo(\"GPU 可用\")\n", " else:\n", " echo(\"GPU 不可用\")\n", " raise Exception(\"\\n没有使用GPU,请在代码执行程序-更改运行时类型-设置为GPU!\\n如果不能使用GPU,建议更换账号!\")\n", "\n", "\n", " # 配置google drive\n", " def config_google_drive(self):\n", " echo(\"挂载 Google Drive\")\n", " import os\n", " if not os.path.exists('/content/drive/MyDrive'):\n", " from google.colab import drive\n", " drive.mount('/content/drive')\n", " echo(\"Google Dirve 挂载完成\")\n", " else:\n", " echo(\"Google Drive 已挂载\")\n", "\n", " # 检测并创建输出文件夹\n", " if os.path.exists('/content/drive/MyDrive'):\n", " if not os.path.exists('/content/drive/MyDrive/fooocus_output'):\n", " echo(\"在 Google Drive 创建 fooocus_ouput 文件夹\")\n", " !mkdir -p /content/drive/MyDrive/fooocus_output\n", " else:\n", " raise Exception(\"未挂载 Google Drive,请重新挂载后重试!\")\n", "\n", "\n", "\n", "# FOOOCUS\n", "class FOOOCUS(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7865)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载大模型\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoints\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " # 下载lora模型\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " # 下载配置文件\n", " def install_config(self):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"下载配置文件\")\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_config.json\", path + \"/presets\", \"custom.json\")\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_path_config_kaggle.json\", path, \"config.txt\")\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_zh_cn.json\", path + \"/language\", \"zh.json\")\n", "\n", "\n", " # 安装fooocus\n", " def install(self, torch_ver, xformers_ver, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/lllyasviel/Fooocus\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver, use_mirror)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements_versions.txt\"\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.install_config()\n", " self.tcmalloc()\n", "\n", "\n", "#######################################################\n", "try: \n", " echo(\"尝试安装 ipywidgets 组件\")\n", " !pip install ipywidgets -qq\n", " from IPython.display import clear_output\n", " clear_output(wait=False)\n", " INIT_CONFIG = 1\n", "except:\n", " raise Exception(\"未初始化功能\")\n", "\n", "import ipywidgets as widgets\n", "\n", "\n", "# PyTorch 版本\n", "pytorch_ver = widgets.Textarea(value=\"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121\", placeholder=\"请填写 PyTorch 版本\", description=\"PyTorch 版本: \", disabled=False)\n", "xformers_ver = widgets.Textarea(value=\"xformers==0.0.25\", placeholder=\"请填写 xFormers 版本\", description=\"xFormers 版本: \", disabled=False)\n", "# 内网穿透方式\n", "use_remote_moe = widgets.Checkbox(value=True, description=\"使用 remote.moe 内网穿透\", disabled=False)\n", "use_localhost_run = widgets.Checkbox(value=True, description=\"使用 localhost.run 内网穿透\", disabled=False) #@param {type:\"boolean\"}\n", "use_cloudflare = widgets.Checkbox(value=False, description=\"使用 CloudFlare 内网穿透\", disabled=False) #@param {type:\"boolean\"}\n", "use_ngrok = widgets.Checkbox(value=False, description=\"使用 Ngrok 内网穿透\", disabled=False) #@param {type:\"boolean\"}\n", "ngrok_token = widgets.Textarea(value=\"\", placeholder=\"请填写 Ngrok Token(可在 Ngrok 官网获取)\", description=\"Ngrok Token: \", disabled=False) #@param {type:\"string\"}\n", "use_gradio = widgets.Checkbox(value=False, description=\"使用 Gradio 内网穿透\", disabled=False) #@param {type:\"boolean\"}\n", "# 模型下载\n", "sd_xl_base = widgets.Checkbox(value=False, description=\"下载 sd_xl_base 模型\", disabled=False)\n", "kohakuXLGamma_rev1 = widgets.Checkbox(value=False, description=\"下载 kohakuXLGamma_rev1 模型\", disabled=False)\n", "kohakuXLBeta_beta7 = widgets.Checkbox(value=False, description=\"下载 kohakuXLBeta_beta7 模型\", disabled=False)\n", "Kohaku_XL_Delta = widgets.Checkbox(value=False, description=\"下载 Kohaku_XL_Delta 模型\", disabled=False)\n", "kohakuXL_Epsilon = widgets.Checkbox(value=True, description=\"下载 kohakuXL_Epsilon 模型\", disabled=False)\n", "animagine_XL_3 = widgets.Checkbox(value=False, description=\"下载 animagine_XL_3 模型\", disabled=False)\n", "animagine_XL_3_1 = widgets.Checkbox(value=True, description=\"下载 animagine_XL_3_1 模型\", disabled=False)\n", "heart_of_apple_xl = widgets.Checkbox(value=False, description=\"下载 heart_of_apple_xl 模型\", disabled=False)\n", "CounterfeitXL = widgets.Checkbox(value=False, description=\"下载 CounterfeitXL 模型\", disabled=False)\n", "bluePencilXL = widgets.Checkbox(value=False, description=\"下载 bluePencilXL 模型\", disabled=False)\n", "animeIllustDiffusion = widgets.Checkbox(value=False, description=\"下载 animeIllustDiffusion 模型\", disabled=False)\n", "nekorayxl = widgets.Checkbox(value=False, description=\"下载 nekorayxl 模型\", disabled=False)\n", "anima_pencil_xl = widgets.Checkbox(value=False, description=\"下载 anima_pencil_xl 模型\", disabled=False)\n", "BArtstyleDB = widgets.Checkbox(value=False, description=\"下载 BArtstyleDB 模型\", disabled=False)\n", "pony_v6 = widgets.Checkbox(value=False, description=\"下载 pony_v6 模型\", disabled=False)\n", "# 自定义模型下载\n", "model_url = widgets.Textarea(value=\"\", placeholder=\"请填写模型下载链接\", description=\"模型链接: \", disabled=False) #@param {type:\"string\"}\n", "model_name = widgets.Textarea(value=\"\", placeholder=\"请填写模型名称,包括后缀名,例:kohaku-xl.safetensors\", description=\"模型名称: \", disabled=False) #@param {type:\"string\"}\n", "model_type = widgets.Dropdown(options=[(\"Stable Diffusion 模型(大模型)\", \"sd\"), (\"LoRA 模型\", \"lora\")], value=\"sd\", description='模型种类: ')\n", "# 创建实例\n", "fooocus = FOOOCUS(\"/kaggle\",\"Fooocus\")\n", "display(pytorch_ver, # PyTorch\n", " xformers_ver,\n", " use_remote_moe, # 内网穿透\n", " use_localhost_run,\n", " use_cloudflare,\n", " use_gradio,\n", " use_ngrok,\n", " ngrok_token,\n", " sd_xl_base, # 模型下载\n", " kohakuXLGamma_rev1,\n", " kohakuXLBeta_beta7,\n", " Kohaku_XL_Delta,\n", " kohakuXL_Epsilon,\n", " animagine_XL_3,\n", " animagine_XL_3_1,\n", " heart_of_apple_xl,\n", " CounterfeitXL,\n", " bluePencilXL,\n", " animeIllustDiffusion,\n", " nekorayxl,\n", " heart_of_apple_xl,\n", " anima_pencil_xl,\n", " BArtstyleDB,\n", " pony_v6,\n", " model_url, # 自定义模型下载\n", " model_name,\n", " model_type\n", " )\n", "\n", "echo(\"配置参数完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 安装 Fooocus\n", "2. [[← 上一个单元](#参数配置)|[下一个单元 →](#启动-Fooocus)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try: \n", " i = INIT_CONFIG\n", " INIT_CONFIG_1 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数配置\\\"单元\")\n", "\n", "fooocus.install(pytorch_ver.value, xformers_ver.value, False)\n", "fooocus.clear_up(False)\n", "echo(\"Fooocus 运行环境配置完成\")\n", "\n", "# 预设模型下载\n", "echo(\"下载模型中\")\n", "if sd_xl_base.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0_0.9vae.safetensors\", \"sd_xl_base_1.0_0.9vae.safetensors\")\n", "if kohakuXLGamma_rev1.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/KBlueLeaf/Kohaku-XL-gamma/resolve/main/kohaku-xl-gamma-rev1.safetensors\", \"kohakuXLGamma_rev1.safetensors\")\n", "if kohakuXLBeta_beta7.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLBeta_beta7.safetensors\", \"kohakuXLBeta_beta7.safetensors\")\n", "if Kohaku_XL_Delta.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/KBlueLeaf/Kohaku-XL-Delta/resolve/main/kohaku-xl-delta-rev1.safetensors\", \"kohaku-xl-delta-rev1.safetensors\")\n", "if kohakuXL_Epsilon.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/KBlueLeaf/Kohaku-XL-Epsilon/resolve/main/kohaku-xl-epsilon-rev1.safetensors\", \"kohaku-xl-epsilon-rev1.safetensors\")\n", "if animagine_XL_3_1.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/cagliostrolab/animagine-xl-3.1/resolve/main/animagine-xl-3.1.safetensors\", \"animagine-xl-3.1.safetensors\")\n", "if animagine_XL_3.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/cagliostrolab/animagine-xl-3.0/resolve/main/animagine-xl-3.0.safetensors\", \"animagine-xl-3.0.safetensors\")\n", "if CounterfeitXL.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/CounterfeitXL-V1.0.safetensors\", \"CounterfeitXL-V1.0.safetensors\")\n", "if bluePencilXL.value:\n", " fooocus.get_sd_model(\"https://civitai.com/api/download/models/323375\", \"bluePencilXL_v050.safetensors\")\n", "if animeIllustDiffusion.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animeIllustDiffusion_v061.safetensors\", \"animeIllustDiffusion_v061.safetensors\")\n", "if nekorayxl.value:\n", " fooocus.get_sd_model(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/nekorayxl_v06W3.safetensors\", \"nekorayxl_v06W3.safetensors\")\n", "if heart_of_apple_xl.value:\n", " fooocus.get_sd_model(\"https://civitai.com/api/download/models/337306\", \"heart-of-apple-xl.safetensors\")\n", "if anima_pencil_xl.value:\n", " fooocus.get_sd_model(\"https://civitai.com/api/download/models/323674\", \"anima_pencil_xl.safetensors\")\n", "if BArtstyleDB.value:\n", " fooocus.get_sd_model(\"https://civitai.com/api/download/models/299095\", \"BArtstyleDB_XL.safetensors\")\n", "if pony_v6.value:\n", " fooocus.get_sd_model(\"https://civitai.com/api/download/models/290640\", \"ponyDiffusionV6XL_v6StartWithThisOne.safetensors\")\n", "\n", "# 自定义模型下载\n", "echo(\"下载自定义模型中\")\n", "if model_url.value != \"\" and model_name.value != \"\":\n", " if model_type.value == \"sd\":\n", " fooocus.get_sd_model(model_url.value, model_name.value)\n", " elif model_type.value == \"lora\":\n", " fooocus.get_lora_model(model_url.value, model_name.value)\n", "else:\n", " echo(\"自定义模型下载未填写模型链接或者模型名称,请检查\")\n", "echo(\"模型下载完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 启动 Fooocus\n", "3. [[← 上一个单元](#安装-Fooocus)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "trusted": true }, "outputs": [], "source": [ "try: \n", " i = INIT_CONFIG_1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "echo(\"启动 Fooocus\")\n", "fooocus.tun.start(ngrok=use_ngrok.value, ngrok_token=ngrok_token.value, cloudflare=use_cloudflare.value, remote_moe=use_remote_moe.value, localhost_run=use_localhost_run.value, gradio=use_gradio.value)\n", "!python /kaggle/Fooocus/launch.py --preset custom --language zh --disable-offload-from-vram --async-cuda-allocation\n", "fooocus.clear_up(False)\n", "echo(\"已关闭 Fooocus\")" ] } ], "metadata": { "kaggle": { "accelerator": "nvidiaTeslaT4", "dataSources": [], "dockerImageVersionId": 30646, "isGpuEnabled": true, "isInternetEnabled": true, "language": "python", "sourceType": "notebook" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 4 }
2301_81996401/sd-webui-all-in-one
notebook/fooocus_kaggle.ipynb
Jupyter Notebook
agpl-3.0
42,492
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# HDM Train Kaggle\n", "Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "\n", "## 简介\n", "一个在 [Kaggle](https://www.kaggle.com) 部署 [HDM](https://github.com/KohakuBlueleaf/HDM) 的 Jupyter Notebook,可用于 HDM 模型的训练。[Colab](https://colab.research.google.com) 同样也可以使用。\n", "\n", "还有这个只是写来玩的,可能有 BUG 跑不了。\n", "\n", "<h2 style=\"color: red;\">切记,不要在 Kaggle 使用包含 NSFW 的训练集,这将导致 Kaggle 账号被封禁!!!</h2>\n", "\n", "## 不同运行单元的功能\n", "该 Notebook 分为以下几个单元:\n", "\n", "- [功能初始化](#功能初始化)\n", "- [参数配置](#参数配置)\n", "- [安装环境](#安装环境)\n", "- [模型训练](#模型训练)\n", "- [模型上传](#模型上传)\n", "\n", "使用时请按顺序运行笔记单元。\n", "\n", "通常情况下[功能初始化](#功能初始化)和[模型上传](#模型上传)单元的内容无需修改,其他单元包含不同功能的注释,可阅读注释获得帮助。\n", "\n", "[参数配置](#参数配置)单元用于修改安装,训练,上传模型时的配置。\n", "\n", "[安装](#安装)单元执行安装训练环境的命令和下载模型 / 训练集的命令,可根据需求进行修改。\n", "\n", "[模型训练](#模型训练)执行训练模型的命令,需要根据自己的需求进行修改,该单元也提供一些训练参数的例子,可在例子的基础上进行修改。\n", "\n", "如果需要快速取消注释,可以选中代码,按下`Ctrl + /`取消注释。\n", "\n", "\n", "## 提示\n", "1. 不同单元中包含注释, 可阅读注释获得帮助。\n", "2. 训练代码的部分需要根据自己的需求进行更改。\n", "3. 推荐使用 Kaggle 的 `Save Version` 的功能运行笔记,可让 Kaggle 笔记在无人值守下保持运行,直至所有单元运行完成。\n", "4. 如果有 [HuggingFace](https://huggingface.co) 账号或者 [ModelScope](https://modelscope.cn) 账号,可通过填写 Token 和仓库名后实现自动上传训练好的模型,仓库需要手动创建。\n", "5. 进入 Kaggle 笔记后,在 Kaggle 的右侧栏可以调整 kaggle 笔记的设置,也可以上传训练集等。注意,在 Kaggle 笔记的`Session options`->`ACCELERATOR`中,需要选择`GPU T4 x 2`,才能使用 GPU 进行模型训练。\n", "6. 使用 Kaggle 进行模型训练时,训练集中最好没有 NSFW 内容,否则可能会导致 Kaggle 账号被封禁。\n", "7. 不同单元的标题下方包含快捷跳转链接,可使用跳转链接翻阅 Notebook。\n", "8. 该 Notebook 的使用方法可阅读:</br>[使用 HuggingFace / ModelScope 保存和下载文件 - licyk的小窝](https://licyk.netlify.app/2025/01/16/use-huggingface-or-modelscope-to-save-file/)</br>[使用 Kaggle 进行模型训练 - licyk的小窝](https://licyk.netlify.app/2025/01/16/use-kaggle-to-training-sd-model)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 功能初始化\n", "通常不需要修改该单元的内容 \n", "1. [[下一个单元 →](#参数配置)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "from pathlib import Path\n", "\n", "os.environ[\"SD_WEBUI_ALL_IN_ONE_LOGGER_COLOR\"] = \"0\"\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import git_warpper, logger, VERSION, BaseManager\n", "from sd_webui_all_in_one.env import config_wandb_token, configure_pip\n", "from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, pip_install\n", "from sd_webui_all_in_one.mirror_manager import set_mirror\n", "from sd_webui_all_in_one.utils import check_gpu\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "#################################################################################################################\n", "\n", "\n", "class HDMTrainManager(BaseManager):\n", " def install(\n", " self,\n", " torch_ver: str | list | None = None,\n", " xformers_ver: str | list | None = None,\n", " model_path: str | Path = None,\n", " model_list: list[str, int] | None = None,\n", " use_uv: bool | None = True,\n", " pypi_index_mirror: str | None = None,\n", " pypi_extra_index_mirror: str | None = None,\n", " pypi_find_links_mirror: str | None = None,\n", " github_mirror: str | list | None = None,\n", " huggingface_mirror: str | None = None,\n", " pytorch_mirror: str | None = None,\n", " hdm_repo: str | None = None,\n", " retry: int | None = 3,\n", " huggingface_token: str | None = None,\n", " modelscope_token: str | None = None,\n", " wandb_token: str | None = None,\n", " git_username: str | None = None,\n", " git_email: str | None = None,\n", " check_avaliable_gpu: bool | None = False,\n", " enable_tcmalloc: bool | None = True,\n", " ) -> None:\n", " \"\"\"安装 HDM 和其余环境\n", "\n", " :param torch_ver`(str|None)`: 指定的 PyTorch 软件包包名, 并包括版本号\n", " :param xformers_ver`(str|None)`: 指定的 xFormers 软件包包名, 并包括版本号\n", " :param model_path`(str|Path|None)`: 指定模型下载的路径\n", " :param model_list`(list[str|int]|None)`: 模型下载列表\n", " :param use_uv`(bool|None)`: 使用 uv 替代 Pip 进行 Python 软件包的安装\n", " :param pypi_index_mirror`(str|None)`: PyPI Index 镜像源链接\n", " :param pypi_extra_index_mirror`(str|None)`: PyPI Extra Index 镜像源链接\n", " :param pypi_find_links_mirror`(str|None)`: PyPI Find Links 镜像源链接\n", " :param github_mirror`(str|list|None)`: Github 镜像源链接或者镜像源链接列表\n", " :param huggingface_mirror`(str|None)`: HuggingFace 镜像源链接\n", " :param pytorch_mirror`(str|None)`: PyTorch 镜像源链接\n", " :param hdm_repo`(str|None)`: HDM 仓库地址, 未指定时默认为`https://github.com/KohakuBlueleaf/HDM`\n", " :param retry`(int|None)`: 设置下载模型失败时重试次数\n", " :param huggingface_token`(str|None)`: 配置 HuggingFace Token\n", " :param modelscope_tokenn`(str|None)`: 配置 ModelScope Token\n", " :param wandb_token`(str|None)`: 配置 WandB Token\n", " :param git_username`(str|None)`: Git 用户名\n", " :param git_email`(str|None)`: Git 邮箱\n", " :param check_avaliable_gpu`(bool|None)`: 检查是否有可用的 GPU, 当 GPU 不可用时引发`Exception`\n", " :param enable_tcmalloc`(bool|None)`: 启用 TCMalloc 内存优化\n", " :notes\n", " self.install() 将会以下几件事\n", " 1. 配置 PyPI / Github / HuggingFace 镜像源\n", " 2. 配置 Pip / uv\n", " 3. 安装管理工具自身依赖\n", " 4. 安装 HDM\n", " 5. 安装 PyTorch / xFormers\n", " 6. 安装 HDM 的依赖\n", " 7. 下载模型\n", " 8. 配置 HuggingFace / ModelScope / WandB Token 环境变量\n", " 9. 配置其他工具\n", " \"\"\"\n", " logger.info(\"配置 HDM 环境中\")\n", " os.chdir(self.workspace)\n", " hdm_path = self.workspace / self.workfolder\n", " hdm_repo = hdm_repo if hdm_repo is not None else \"https://github.com/KohakuBlueleaf/HDM\"\n", " model_path = model_path if model_path is not None else (\n", " self.workspace / \"hdm-models\")\n", " model_list = model_list if model_list else []\n", " # 检查是否有可用的 GPU\n", " if check_avaliable_gpu and not check_gpu():\n", " raise Exception(\n", " \"没有可用的 GPU, 请在 kaggle -> Notebook -> Session options -> ACCELERATOR 选择 GPU T4 x 2\\n如果不能使用 GPU, 请检查 Kaggle 账号是否绑定了手机号或者尝试更换账号!\")\n", " # 配置镜像源\n", " set_mirror(\n", " pypi_index_mirror=pypi_index_mirror,\n", " pypi_extra_index_mirror=pypi_extra_index_mirror,\n", " pypi_find_links_mirror=pypi_find_links_mirror,\n", " github_mirror=github_mirror,\n", " huggingface_mirror=huggingface_mirror\n", " )\n", " configure_pip() # 配置 Pip / uv\n", " install_manager_depend(use_uv) # 准备 Notebook 的运行依赖\n", " # 下载 HDM\n", " git_warpper.clone(\n", " repo=hdm_repo,\n", " path=hdm_path,\n", " )\n", " git_warpper.update(hdm_path) # 更新 HDM\n", " # 安装 HDM 的依赖\n", " pip_install(\n", " \"-e\",\n", " f\"{hdm_path}[finetune,tipo,liger]\",\n", " use_uv=use_uv,\n", " )\n", " # 安装 PyTorch 和 xFormers\n", " install_pytorch(\n", " torch_package=torch_ver,\n", " xformers_package=xformers_ver,\n", " pytorch_mirror=pytorch_mirror,\n", " use_uv=use_uv\n", " )\n", " # 更新 urllib3\n", " try:\n", " pip_install(\n", " \"urllib3\",\n", " \"--upgrade\",\n", " use_uv=False\n", " )\n", " except Exception as e:\n", " logger.error(\"更新 urllib3 时发生错误: %s\", e)\n", " try:\n", " pip_install(\n", " \"numpy==1.26.4\",\n", " use_uv=use_uv\n", " )\n", " except Exception as e:\n", " logger.error(\"降级 numpy 时发生错误: %s\", e)\n", " self.get_model_from_list(\n", " path=model_path,\n", " model_list=model_list,\n", " retry=retry\n", " )\n", " self.restart_repo_manager(\n", " hf_token=huggingface_token,\n", " ms_token=modelscope_token,\n", " )\n", " config_wandb_token(wandb_token)\n", " git_warpper.set_git_config(\n", " username=git_username,\n", " email=git_email,\n", " )\n", " enable_tcmalloc and self.tcmalloc.configure_tcmalloc()\n", " logger.info(\"HDM 环境配置完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 参数配置\n", "设置必要的参数, 根据注释说明进行修改 \n", "2. [[← 上一个单元](#功能初始化)|[下一个单元 →](#安装环境)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 环境设置\n", "WORKSPACE = \"/kaggle\" # 工作路径, 通常不需要修改\n", "WORKFOLDER = \"HDM\" # 工作路径中文件夹名称, 通常不需要修改\n", "HDM_REPO = \"https://github.com/KohakuBlueleaf/HDM\" # HDM 仓库地址\n", "TORCH_VER = \"\" # PyTorch 版本\n", "XFORMERS_VER = \"\" # xFormers 版本\n", "USE_UV = True # 使用 uv 加速 Python 软件包安装, 修改为 True 为启用, False 为禁用\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" # PyPI 主镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu128\" # PyPI 扩展镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu124\" # 用于下载 PyTorch 的镜像源\n", "PIP_FIND_LINKS_MIRROR = \"https://download.pytorch.org/whl/cu121/torch_stable.html\" # PyPI 扩展镜像源\n", "HUGGINGFACE_MIRROR = \"https://hf-mirror.com\" # HuggingFace 镜像源\n", "GITHUB_MIRROR = [ # Github 镜像源\n", " \"https://ghfast.top/https://github.com\",\n", " \"https://mirror.ghproxy.com/https://github.com\",\n", " \"https://ghproxy.net/https://github.com\",\n", " \"https://gh.api.99988866.xyz/https://github.com\",\n", " \"https://gh-proxy.com/https://github.com\",\n", " \"https://ghps.cc/https://github.com\",\n", " \"https://gh.idayer.com/https://github.com\",\n", " \"https://ghproxy.1888866.xyz/github.com\",\n", " \"https://slink.ltd/https://github.com\",\n", " \"https://github.boki.moe/github.com\",\n", " \"https://github.moeyy.xyz/https://github.com\",\n", " \"https://gh-proxy.net/https://github.com\",\n", " \"https://gh-proxy.ygxz.in/https://github.com\",\n", " \"https://wget.la/https://github.com\",\n", " \"https://kkgithub.com\",\n", " \"https://gitclone.com/github.com\",\n", "]\n", "CHECK_AVALIABLE_GPU = False # 检查可用的 GPU, 当 GPU 不可用时强制终止安装进程\n", "RETRY = 3 # 重试下载次数\n", "DOWNLOAD_THREAD = 16 # 下载线程\n", "ENABLE_TCMALLOC = True # 启用 TCMalloc 内存优化\n", "UPDATE_CORE = True # 更新内核\n", "\n", "##############################################################################\n", "\n", "# 模型上传设置, 使用 HuggingFace / ModelScope 上传训练好的模型\n", "# HuggingFace: https://huggingface.co\n", "# ModelScope: https://modelscope.cn\n", "USE_HF_TO_SAVE_MODEL = False # 使用 HuggingFace 保存训练好的模型, 修改为 True 为启用, False 为禁用 (True / False)\n", "USE_MS_TO_SAVE_MODEL = False # 使用 ModelScope 保存训练好的模型, 修改为 True 为启用, False 为禁用 (True / False)\n", "\n", "# Token 配置, 用于上传 / 下载模型 (部分模型下载需要 Token 进行验证)\n", "# HuggingFace Token 在 Account -> Settings -> Access Tokens 中获取\n", "HF_TOKEN = \"\" # HuggingFace Token\n", "# ModelScope Token 在 首页 -> 访问令牌 -> SDK 令牌 中获取\n", "MS_TOKEN = \"\" # ModelScope Token\n", "\n", "# 用于上传模型的 HuggingFace 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "HF_REPO_ID = \"username/reponame\" # HuggingFace 仓库的 ID (格式: \"用户名/仓库名\")\n", "HF_REPO_TYPE = \"model\" # HuggingFace 仓库的种类 (可选的类型为: model / dataset / space), 如果在 HuggingFace 新建的仓库为模型仓库则不需要修改\n", "# HuggingFace 仓库类型和对应名称:\n", "# model: 模型仓库\n", "# dataset: 数据集仓库\n", "# space: 在线运行空间仓库\n", "\n", "# 用于上传模型的 ModelScope 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "MS_REPO_ID = \"username/reponame\" # ModelScope 仓库的 ID (格式: \"用户名/仓库名\")\n", "MS_REPO_TYPE = \"model\" # ModelScope 仓库的种类 (model / dataset / space), 如果在 ModelScope 新建的仓库为模型仓库则不需要修改\n", "# ModelScope 仓库类型和对应名称:\n", "# model: 模型仓库\n", "# dataset: 数据集仓库\n", "# space: 创空间仓库\n", "\n", "# 设置自动创建仓库时仓库的可见性, False 为私有仓库(不可见), True 为公有仓库(可见), 通常保持默认即可\n", "HF_REPO_VISIBILITY = False # 设置新建的 HuggingFace 仓库可见性 (True / False)\n", "MS_REPO_VISIBILITY = False # 设置新建的 ModelScope 仓库可见性 (True / False)\n", "\n", "# Git 信息设置, 可以使用默认值\n", "GIT_USER_EMAIL = \"username@example.com\" # Git 的邮箱\n", "GIT_USER_NAME = \"username\" # Git 的用户名\n", "\n", "##############################################################################\n", "\n", "# 训练日志设置, 使用 WandB 记录训练日志, 使用 WandB 可远程查看实时训练日志\n", "# WandB Token 可在 https://wandb.ai/authorize 中获取\n", "WANDB_TOKEN = \"\" # WandB Token\n", "\n", "##############################################################################\n", "\n", "# 路径设置, 通常保持默认即可\n", "INPUT_DATASET_PATH = \"/kaggle/dataset\" # 训练集保存的路径\n", "OUTPUT_PATH = \"/kaggle/working/model\" # 训练时模型保存的路径\n", "HDM_MODEL_PATH = \"/kaggle/hdm-models\" # 模型下载到的路径\n", "KAGGLE_INPUT_PATH = \"/kaggle/input\" # Kaggle Input 的路径\n", "\n", "##############################################################################\n", "\n", "# 训练模型设置, 在安装时将会下载选择的模型\n", "# 下面举个例子:\n", "# HDM_MODEL = [\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", 1, \"Illustrious.safetensors\"]\n", "# ]\n", "# \n", "# 在这个例子中, 第一个参数指定了模型的下载链接, 第二个参数设置了是否要下载这个模型, 当这个值为 1 时则下载该模型\n", "# 第三个参数是可选参数, 用于指定下载到本地后的文件名称\n", "# \n", "# 则上面的例子中\n", "# https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors 和 \n", "# https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors 下载链接所指的文件将被下载\n", "# https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors 的文件下载到本地后名称为 animefull-final-pruned.safetensors\n", "# 并且 https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors 所指的文件将被重命名为 Illustrious.safetensors\n", "\n", "HDM_MODEL = [\n", " [\"https://huggingface.co/KBlueLeaf/HDM-xut-340M-anime/resolve/main/hdm-xut-340M-512px-note.safetensors\", 1],\n", " [\"https://huggingface.co/KBlueLeaf/HDM-xut-340M-anime/resolve/main/hdm-xut-340M-768px-note.safetensors\", 1],\n", " [\"https://huggingface.co/KBlueLeaf/HDM-xut-340M-anime/resolve/main/hdm-xut-340M-1024px-note.safetensors\", 1],\n", "]\n", "\n", "##############################################################################\n", "# 下面为初始化参数部分, 不需要修改\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": TORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"model_path\": HDM_MODEL_PATH or None,\n", " \"model_list\": HDM_MODEL,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " # Kaggle 的环境暂不需要以下镜像源\n", " # \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"hdm_repo\": HDM_REPO or None,\n", " \"retry\": RETRY,\n", " \"huggingface_token\": HF_TOKEN or None,\n", " \"modelscope_token\": MS_TOKEN or None,\n", " \"wandb_token\": WANDB_TOKEN or None,\n", " \"git_username\": GIT_USER_NAME or None,\n", " \"git_email\": GIT_USER_EMAIL or None,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "HF_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"huggingface\",\n", " \"repo_id\": HF_REPO_ID,\n", " \"repo_type\": HF_REPO_TYPE,\n", " \"visibility\": HF_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "MS_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"modelscope\",\n", " \"repo_id\": MS_REPO_ID,\n", " \"repo_type\": MS_REPO_TYPE,\n", " \"visibility\": MS_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "os.makedirs(WORKSPACE, exist_ok=True) # 创建工作路径\n", "os.makedirs(OUTPUT_PATH, exist_ok=True) # 创建模型输出路径\n", "os.makedirs(INPUT_DATASET_PATH, exist_ok=True) # 创建训练集路径\n", "os.makedirs(HDM_MODEL_PATH, exist_ok=True) # 创建模型下载路径\n", "HDM_PATH = os.path.join(WORKSPACE, WORKFOLDER) # HDM 路径\n", "logger.info(\"参数设置完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 安装环境\n", "安装环境和下载模型和训练集, 根据注释的说明进行修改 \n", "3. [[← 上一个单元](#参数配置)|[下一个单元 →](#模型训练)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 初始化部分参数并执行安装命令, 这一小部分不需要修改\n", "logger.info(\"开始安装 HDM\")\n", "hdm_manager = HDMTrainManager(WORKSPACE, WORKFOLDER)\n", "hdm_manager.install(**INSTALL_PARAMS)\n", "hdm_manager.import_kaggle_input(KAGGLE_INPUT_PATH, INPUT_DATASET_PATH)\n", "##########################################################################################\n", "# 下方可自行编写命令\n", "# 下方的命令示例可以根据自己的需求进行修改\n", "\n", "\n", "##### 1. 关于运行环境 #####\n", "\n", "# 如果需要安装某个软件包, 可以使用 %pip 命令\n", "# 下面是几个使用例子:\n", "# 1.\n", "# %pip install lycoris-lora==2.1.0.post3 dadaptation==3.1\n", "# \n", "# 这将安装 lycoris-lora==2.1.0.post3 和 dadaptation==3.1\n", "# \n", "# 2.\n", "# %pip uninstall tensorboard\n", "# \n", "# 这将卸载 tensorboard\n", "\n", "\n", "##########################################################################################\n", "\n", "\n", "##### 2. 关于模型导入 #####\n", "\n", "# 该 Kaggle 训练脚本支持 4 种方式导入模型, 如下:\n", "# 1. 使用 Kaggle Input 导入\n", "# 2. 使用模型下载链接导入\n", "# 3. 从 HuggingFace 仓库导入\n", "# 4. 从 ModelScope 仓库导入\n", "\n", "\n", "### 2.1. 使用 Kaggle Input 导入 ###\n", "# 在 Kaggle 右侧面板中, 点击 Notebook -> Input -> Upload -> New Model, 从此处导入模型\n", "\n", "\n", "### 2.2 使用模型下载链接导入 ###\n", "# 如果需要通过链接下载额外的模型, 可以使用 hdm_manager.get_model()\n", "# 使用参数:\n", "# hdm_manager.get_model(\n", "# url=\"model_url\", # 模型下载链接\n", "# path=HDM_MODEL_PATH, # 模型下载到本地的路径\n", "# filename=\"filename.safetensors\", # 模型的名称\n", "# retry=RETRY, # 重试下载的次数\n", "# )\n", "# \n", "# 下面是几个使用例子:\n", "# 1.\n", "# hdm_manager.get_model(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors\",\n", "# path=HDM_MODEL_PATH,\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors 下载模型并保存到 HDM_MODEL_PATH 中\n", "# \n", "# hdm_manager.get_model(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors\",\n", "# path=HDM_MODEL_PATH,\n", "# filename=\"rename_model.safetensors\",\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors 下载模型并保存到 HDM_MODEL_PATH 中, 并且重命名为 rename_model.safetensors\n", "\n", "\n", "### 2.3. 从 HuggingFace 仓库导入 ###\n", "# 如果需要从 HuggingFace 仓库下载模型, 可以使用 hdm_manager.repo.download_files_from_repo()\n", "# 使用参数:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\", # 指定为 HuggingFace 的仓库\n", "# local_dir=HDM_MODEL_PATH, # 模型下载到本地的路径\n", "# repo_id=\"usename/repo_id\", # HuggingFace 仓库 ID\n", "# repo_type=\"model\", # (可选参数) HuggingFace 仓库种类 (model / dataset / space)\n", "# folder=\"path/in/repo/file.safetensors\", # (可选参数) 文件在 HuggingFace 仓库中的路径\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 例如要从 stabilityai/stable-diffusion-xl-base-1.0 (类型为 model) 下载 sd_xl_base_1.0_0.9vae.safetensors\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=HDM_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 则上述的命令将会从 stabilityai/stable-diffusion-xl-base-1.0 下载 sd_xl_base_1.0_0.9vae.safetensors 模型\n", "# 并将模型保存到 HDM_MODEL_PATH 中\n", "# 注意 folder 填的是文件在 HuggingFace 仓库中的路径, 如果上述例子中的文件在仓库的 checkpoint/sd_xl_base_1.0_0.9vae.safetensors 路径\n", "# 则 folder 填的内容为 checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "#\n", "# 模型保存的路径与 local_dir 和 folder 参数有关\n", "# 对于上面的例子 local_dir 为 /kaggle/sd-models, folder 为 sd_xl_base_1.0_0.9vae.safetensors\n", "# 则最终保存的路径为 /kaggle/sd-models/sd_xl_base_1.0_0.9vae.safetensors\n", "# \n", "# 如果 folder 为 checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "# 则最终保存的路径为 /kaggle/sd-models/checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "# \n", "# folder 参数为可选参数, 即该参数可不指定, 在不指定的情况下将下载整个仓库中的文件\n", "# 比如将上面的例子改成:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# local_dir=HDM_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 这时候将下载 stabilityai/stable-diffusion-xl-base-1.0 仓库中的所有文件\n", "# 对于可选参数, 可以进行省略, 此时将使用该参数的默认值进行运行, 上面的例子就可以简化成下面的:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=HDM_MODEL_PATH,\n", "# )\n", "# 省略后仍然可以正常执行, 但对于一些重要的可选参数, 不推荐省略, 如 repo_type 参数\n", "# 该参数用于指定仓库类型, 不指定时则默认认为仓库为 model 类型\n", "# 若要下载的仓库为 dataset 类型, 不指定 repo_type 参数时默认就把仓库类型当做 model, 最终导致找不到要下载的仓库\n", "\n", "\n", "### 2.4. 从 ModelScope 仓库导入 ###\n", "# 如果需要从 ModelScope 仓库下载模型, 可以使用 hdm_manager.repo.download_files_from_repo()\n", "# 使用方法和 **2.3. 从 HuggingFace 仓库导入** 部分的类似, 只需要指定 api_type=\"modelscope\" 来指定使用 ModelScope 的仓库\n", "# 使用参数:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"modelscope\", # 指定为 ModelScope 的仓库\n", "# local_dir=HDM_MODEL_PATH, # 模型下载到本地的路径\n", "# repo_id=\"usename/repo_id\", # ModelScope 仓库 ID\n", "# repo_type=\"model\", # (可选参数) ModelScope 仓库种类 (model / dataset / space)\n", "# folder=\"path/in/repo/file.safetensors\", # (可选参数) 文件在 ModelScope 仓库中的路径\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 例如要从 stabilityai/stable-diffusion-xl-base-1.0 (类型为 model) 下载 sd_xl_base_1.0_0.9vae.safetensors\n", "# hdm_manager.dataset.get_single_file_from_ms(\n", "# api_type=\"modelscope\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=HDM_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 则上述的命令将会从 stabilityai/stable-diffusion-xl-base-1.0 下载 sd_xl_base_1.0_0.9vae.safetensors 模型\n", "# 并将模型保存到 HDM_MODEL_PATH 中\n", "\n", "\n", "\n", "##########################################################################################\n", "\n", "\n", "##### 3. 关于训练集导入 #####\n", "\n", "# 该 Kaggle 训练脚本支持 4 种方式导入训练集, 如下:\n", "# 1. 使用 Kaggle Input 导入\n", "# 2. 使用训练集下载链接导入\n", "# 3. 从 HuggingFace 仓库导入\n", "# 4. 从 ModelScope 仓库导入\n", "\n", "\n", "### 3.1. 使用 Kaggle Input 导入 ###\n", "# 在 Kaggle 右侧面板中, 点击 Notebook -> Input -> Upload -> New Dataset, 从此处导入模型\n", "\n", "\n", "### 3.2. 使用训练集下载链接导入 ###\n", "# 如果将训练集压缩后保存在某个平台, 如 HuggingFace, ModelScope, 并且有下载链接\n", "# 可以使用 hdm_manager.utils.download_archive_and_unpack() 函数下载训练集\n", "# 使用参数:\n", "# hdm_manager.utils.download_archive_and_unpack(\n", "# url=\"download_url\", # 训练集压缩包的下载链接\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到本地的路径\n", "# name=\"filename.zip\", # (可选参数) 将数据集压缩包进行重命名\n", "# retry=RETRY, # (可选参数) 重试下载的次数\n", "# )\n", "# \n", "# 该函数在下载训练集压缩包完成后将解压到指定的本地路径\n", "# 压缩包格式仅支持 7z, zip, tar\n", "# \n", "# 下面是几个使用的例子:\n", "# 1.\n", "# hdm_manager.utils.download_archive_and_unpack(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/data_1.7z\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/data_1.7z 下载训练集压缩包并解压到 INPUT_DATASET_PATH 中\n", "# \n", "# 2.\n", "# hdm_manager.utils.download_archive_and_unpack(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/data_1.7z\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# name=\"training_dataset.7z\",\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/data_1.7z 下载训练集压缩包并重命名成 training_dataset.7z\n", "# 再将 training_dataset.7z 中的文件解压到 INPUT_DATASET_PATH 中\n", "# \n", "# \n", "# 训练集的要求:\n", "# 需要将图片进行打标, 并调整训练集为指定的目结构, 例如:\n", "# Nachoneko\n", "# └── 1_nachoneko\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 0(8).txt\n", "# ├── 0(8).webp\n", "# ├── 001_2.png\n", "# ├── 001_2.txt\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# \n", "# 在 Nachoneko 文件夹新建一个文件夹, 格式为 <数字>_<名称>, 如 1_nachoneko, 前面的数字代表这部分的训练集的重复次数, 1_nachoneko 文件夹内则放图片和打标文件\n", "# \n", "# 训练集也可以分成多个部分组成, 例如:\n", "# Nachoneko\n", "# ├── 1_nachoneko\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 2_nachoneko\n", "# │ ├── 0(8).txt\n", "# │ ├── 0(8).webp\n", "# │ ├── 001_2.png\n", "# │ └── 001_2.txt\n", "# └── 4_nachoneko\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# \n", "# 处理好训练集并调整好目录结构后可以将 Nachoneko 文件夹进行压缩了, 使用 zip / 7z / tar 格式进行压缩\n", "# 例如将上述的训练集压缩成 Nachoneko.7z, 此时需要检查一下压缩后在压缩包的目录结果是否和原来的一致(有些压缩软件在部分情况下会破坏原来的目录结构)\n", "# 确认没有问题后将该训练集上传到网盘, 推荐使用 HuggingFace / ModelScope\n", "\n", "\n", "### 3.3. 从 HuggingFace 仓库导入 ###\n", "# 如果训练集保存在 HuggingFace, 可以使用 hdm_manager.repo.download_files_from_repo() 函数从 HuggingFace 下载数据集\n", "# 使用方法和 **2.3. 从 HuggingFace 仓库导入** 部分类似, 部分说明可参考那部分的内容\n", "# 使用格式:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\", # 指定为 HuggingFace 的仓库\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到哪个路径\n", "# repo_id=\"username/train_data\", # HuggingFace 仓库 ID\n", "# repo_type=\"dataset\", # (可选参数) HuggingFace 仓库的类型 (model / dataset / space)\n", "# folder=\"folder_in_repo\", # (可选参数) 指定要从 HuggingFace 仓库里下载哪个文件夹的内容\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 比如在 HuggingFace 的仓库为 username/train_data, 仓库类型为 dataset\n", "# 仓库的文件结构如下:\n", "# ├── Nachoneko\n", "# │ ├── 1_nachoneko\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# │ ├── 2_nachoneko\n", "# │ │ ├── 0(8).txt\n", "# │ │ ├── 0(8).webp\n", "# │ │ ├── 001_2.png\n", "# │ │ └── 001_2.txt\n", "# │ └── 4_nachoneko\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# │ ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# │ └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# └ aaaki\n", "# ├── 1_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 11.png\n", "# │   ├── 11.txt\n", "# │   ├── 12.png\n", "# │   └── 12.txt\n", "# └── 3_aaaki\n", "# ├── 14.png\n", "# ├── 14.txt\n", "# ├── 16.png\n", "# └── 16.txt\n", "#\n", "# 此时想要下载这个仓库中的 Nachoneko 文件夹的内容, 则下载命令为\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# folder=\"Nachoneko\",\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# \n", "# 如果想下载整个仓库, 则移除 folder 参数, 命令修改为\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "\n", "\n", "\n", "# 4. 从 ModelScope 仓库导入\n", "# 如果训练集保存在 ModelScope, 可以使用 hdm_manager.repo.download_files_from_repo() 函数从 ModelScope 下载数据集\n", "# 使用方法可参考 **3.2. 使用训练集下载链接导入** 部分的说明\n", "# 使用格式:\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"modelscope\", # 指定为 ModelScope 的仓库\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到哪个路径\n", "# repo_id=\"usename/repo_id\", # ModelScope 仓库 ID\n", "# repo_type=\"dataset\", # (可选参数) ModelScope 仓库的类型 (model / dataset / space)\n", "# folder=\"folder_in_repo\", # (可选参数) 指定要从 ModelScope 仓库里下载哪个文件夹的内容\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 比如在 ModelScope 的仓库为 username/train_data, 仓库类型为 dataset\n", "# 仓库的文件结构如下:\n", "# ├── Nachoneko\n", "# │ ├── 1_nachoneko\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# │ ├── 2_nachoneko\n", "# │ │ ├── 0(8).txt\n", "# │ │ ├── 0(8).webp\n", "# │ │ ├── 001_2.png\n", "# │ │ └── 001_2.txt\n", "# │ └── 4_nachoneko\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# │ ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# │ └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# └ aaaki\n", "# ├── 1_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 11.png\n", "# │   ├── 11.txt\n", "# │   ├── 12.png\n", "# │   └── 12.txt\n", "# └── 3_aaaki\n", "# ├── 14.png\n", "# ├── 14.txt\n", "# ├── 16.png\n", "# └── 16.txt\n", "#\n", "# 此时想要下载这个仓库中的 Nachoneko 文件夹的内容, 则下载命令为\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"modelscope\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# folder=\"Nachoneko\",\n", "# )\n", "# \n", "# 如果想下载整个仓库, 则移除 folder 参数, 命令修改为\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"modelscope\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# )\n", "\n", "\n", "\n", "# 下载训练集的技巧\n", "# 如果有个 character_aaaki 训练集上传到 HuggingFace 上时结构如下:\n", "# \n", "#\n", "# HuggingFace_Repo (licyk/sd_training_dataset)\n", "# ├── character_aaaki\n", "# │   ├── 1_aaaki\n", "# │   │   ├── 1.png\n", "# │   │   ├── 1.txt\n", "# │   │   ├── 3.png\n", "# │   │   └── 3.txt\n", "# │   └── 2_aaaki\n", "# │   ├── 4.png\n", "# │   └── 4.txt\n", "# ├── character_robin\n", "# │   └── 1_xxx\n", "# │   ├── 11.png\n", "# │   └── 11.txt\n", "# └── style_pvc\n", "# └── 5_aaa\n", "# ├── test.png\n", "# └── test.txt\n", "#\n", "# \n", "# 可能有时候不想为训练集中每个子训练集设置不同的重复次数,又不想上传的时候再多套一层文件夹,就把训练集结构调整成了下面的:\n", "# \n", "#\n", "# HuggingFace_Repo (licyk/sd_training_dataset)\n", "# ├── character_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 3.png\n", "# │   ├── 3.txt\n", "# │   ├── 4.png\n", "# │   └── 4.txt\n", "# ├── character_robin\n", "# │   └── 1_xxx\n", "# │   ├── 11.png\n", "# │   └── 11.txt\n", "# └── style_pvc\n", "# └── 5_aaa\n", "# ├── test.png\n", "# └── test.txt\n", "#\n", "# \n", "# 此时这个状态的训练集是缺少子训练集和重复次数的,如果直接使用 hdm_manager.repo.download_files_from_repo() 去下载训练集并用于训练将会导致报错\n", "# 不过可以自己再编写一个函数对 hdm_manager.repo.download_files_from_repo() 函数再次封装,自动加上子训练集并设置重复次数\n", "# \n", "#\n", "# def make_dataset(\n", "# local_dir: str | Path,\n", "# repo_id: str,\n", "# repo_type: str,\n", "# repeat: int,\n", "# folder: str,\n", "# ) -> None:\n", "# import os\n", "# import shutil\n", "# origin_dataset_path = os.path.join(local_dir, folder)\n", "# tmp_dataset_path = os.path.join(local_dir, f\"{repeat}_{folder}\")\n", "# new_dataset_path = os.path.join(origin_dataset_path, f\"{repeat}_{folder}\")\n", "# hdm_manager.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=local_dir,\n", "# repo_id=repo_id,\n", "# repo_type=repo_type,\n", "# folder=folder,\n", "# )\n", "# if os.path.exists(origin_dataset_path):\n", "# logger.info(\"设置 %s 训练集的重复次数为 %s\", folder, repeat)\n", "# shutil.move(origin_dataset_path, tmp_dataset_path)\n", "# shutil.move(tmp_dataset_path, new_dataset_path)\n", "# else:\n", "# logger.error(\"从 %s 下载 %s 失败\", repo_id, folder)\n", "#\n", "# \n", "# 编写好后,可以去调用这个函数\n", "# \n", "#\n", "# make_dataset(\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"licyk/sd_training_dataset\",\n", "# repo_type=\"dataset\",\n", "# repeat=3,\n", "# folder=\"character_aaaki\",\n", "# )\n", "#\n", "# \n", "# 该函数将会把 character_aaaki 训练集下载到 {INPUT_DATASET_PATH} 中,即 /kaggle/dataset\n", "# 文件夹名称为 character_aaaki,并且 character_aaaki 文件夹内继续创建了一个子文件夹作为子训练集,根据 repeat=3 将子训练集的重复次数设置为 3\n", "\n", "\n", "##########################################################################################\n", "logger.info(\"HDM 安装完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 模型训练\n", "需自行编写命令,下方有可参考的例子 \n", "4. [[← 上一个单元](#安装环境)|[下一个单元 →](#模型上传)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "logger.info(\"进入 HDM 目录\")\n", "os.chdir(HDM_PATH)\n", "hdm_manager.display_model_and_dataset_dir(HDM_MODEL_PATH, INPUT_DATASET_PATH, recursive=False)\n", "logger.info(\"使用 HDM 进行模型训练\")\n", "##########################################################################################\n", "# 1.\n", "# 运行前需要根据自己的需求更改参数\n", "# \n", "# 训练参数的设置可参考:\n", "# https://github.com/KohakuBlueleaf/HDM/blob/main/config/train/hdm-xut-340M-ft.toml\n", "# \n", "# \n", "# 2.\n", "# 下方被注释的代码选择后使用 Ctrl + / 取消注释\n", "# \n", "# \n", "# 3.\n", "# 训练使用的底模会被下载到 HDM_MODEL_PATH, 即 /kaggle/sd-models\n", "# 填写底模路径时一般可以通过 --pretrained_model_name_or_path=\"{HDM_MODEL_PATH}/base_model.safetensors\" 指定\n", "# 如果需要外挂 VAE 模型可以通过 --vae=\"{HDM_MODEL_PATH}/vae.safetensors\" 指定\n", "# \n", "# 通过 Kaggle Inout 导入的训练集保存在 KAGGLE_INPUT_PATH, 即 /kaggle/input, 运行该笔记时将会把训练集复制进 INPUT_DATASET_PATH, 即 /kaggle/dataset\n", "# 该路径可通过 INPUT_DATASET_PATH 调整\n", "# 如果使用 hdm_manager.dataset.get_dataset() 函数下载训练集, 数据集一般会解压到 INPUT_DATASET_PATH, 这取决于函数第一个参数传入的路径\n", "# 训练集的路径通常要这种结构\n", "# $ tree /kaggle\n", "# kaggle\n", "# └── dataset\n", "# └── Nachoneko\n", "# └── 1_gan_cheng\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 0(8).txt\n", "# ├── 0(8).webp\n", "# ├── 001_2.png\n", "# ├── 001_2.txt\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# 4 directories, 12 files\n", "# 在填写训练集路径时, 应使用 --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\"\n", "# \n", "# 模型保存的路径通常用 --output_dir=\"{OUTPUT_PATH}\" 指定, 如 --output_dir=\"{OUTPUT_PATH}/Nachoneko\", OUTPUT_PATH 默认设置为 /kaggle/working/model\n", "# 在 Kaggle 的 Output 中可以看到保存的模型, 前提是使用 Kaggle 的 Save Version 运行 Kaggle\n", "# OUTPUT_PATH 也指定了保存模型到 HuggingFace / ModelScope 的功能的上传路径\n", "# \n", "# --output_name 用于指定保存的模型名字, 如 --output_name=\"Nachoneko\"\n", "# \n", "# \n", "# 4.\n", "# Kaggle 的实例最长可运行 12 h, 要注意训练时长不要超过 12 h, 否则将导致训练被意外中断, 并且最后的模型保存功能将不会得到运行\n", "# 如果需要在模型被保存后立即上传到 HuggingFace 进行保存, 可使用启动参数为 sd-scripts 设置自动保存, 具体可阅读 sd-scripts 的帮助信息\n", "# 使用 python train_network.py -h 命令可查询可使用的启动参数, 命令中的 train_network.py 可替换成 sdxl_train_network.py 等\n", "# \n", "# \n", "# 5.\n", "# 训练命令的开头为英文的感叹号, 也就是 !, 后面就是 Shell Script 风格的命令\n", "# 每行的最后为反斜杠用于换行, 也就是用 \\ 来换行, 并且反斜杠的后面不允许有其他符号, 比如空格等\n", "# 训练命令的每一行之间不能有任何换行空出来, 最后一行不需要反斜杠, 因为最后一行的下一行已经没有训练参数\n", "# \n", "# \n", "# 6.\n", "# 如果训练参数是 toml 格式的, 比如从 Akegarasu/lora-scripts 训练器复制来的训练参数\n", "# 可以转换成对应的训练命令中的参数\n", "# 下面列举几种转换例子:\n", "# \n", "# (1)\n", "# toml 格式:\n", "# pretrained_model_name_or_path = \"{HDM_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# 训练命令格式:\n", "# --pretrained_model_name_or_path=\"{HDM_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# \n", "# (2)\n", "# toml 格式:\n", "# unet_lr = 0.0001\n", "# 训练命令格式:\n", "# --unet_lr=0.0001\n", "# \n", "# (3)\n", "# toml 格式:\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# 训练命令格式:\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=full \\\n", "# \n", "# (4)\n", "# toml 格式:\n", "# enable_bucket = true\n", "# 训练命令格式:\n", "# --enable_bucket\n", "# \n", "# (5)\n", "# toml 格式:\n", "# lowram = false\n", "# 训练命令格式:\n", "# 无对应的训练命令, 也就是不需要填, 因为这个参数的值为 false, 也就是无对应的参数, 如果值为 true, 则对应训练命令中的 --lowram\n", "# \n", "# 可以根据这个例子去转换 toml 格式的训练参数成训练命令的格式\n", "# \n", "# \n", "# 7.\n", "# 如果需要 toml 格式的配置文件来配置训练参数可以使用下面的代码来保存 toml 格式的训练参数\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# 这里使用 toml 格式编写训练参数, \n", "# 还可以结合 Python F-Strings 的用法使用前面配置好的变量\n", "# Python F-Strings 的说明: https://docs.python.org/zh-cn/3.13/reference/lexical_analysis.html#f-strings\n", "# toml 的语法可参考: https://toml.io/cn/v1.0.0\n", "# 下面展示训练命令里参数对应的 toml 格式转换\n", "# \n", "# \n", "# pretrained_model_name_or_path = \"{HDM_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# 对应训练命令中的 --pretrained_model_name_or_path=\"{HDM_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# \n", "# unet_lr = 0.0001\n", "# 对应训练命令中的 --unet_lr=0.0001\n", "# \n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# 对应下面训练命令中的\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=full \\\n", "# \n", "# enable_bucket = true\n", "# 对应训练命令中的 --enable_bucket\n", "# \n", "# lowram = false\n", "# 这个参数的值为 false, 也就是无对应的参数, 如果值为 true, 则对应训练命令中的 --lowram\n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# \n", "# 使用上面的代码将会把训练参数的 toml 配置文件保存在 toml_file_path 路径中, 也就是 {WORKSPACE}/train_config.toml, 即 /kaggle/train_config.toml\n", "# 而原来的训练命令无需再写上训练参数, 只需指定该训练配置文件的路径即可\n", "# 使用 --config_file=\"{WORKSPACE}/train_config.toml\" 来指定\n", "# \n", "# \n", "# 8. \n", "# 如果要查看 sd-script 的命令行参数, 可以加上 -h 后再运行, 此时 sd-script 将显示所有可用的参数\n", "# \n", "# \n", "# 9.\n", "# 下方提供了一些训练参数, 可以直接使用, 使用时取消注释后根据需求修改部分参数即可\n", "# \n", "# .,@@@@@@@@@]. ./@[`....`[\\\\. \n", "# //\\`.. . ...,\\@]. .,]]]/O@@@@@@@@\\]... .,]//............\\@` \n", "# .O`........ .......\\\\.]]@@@@@@@@[..........,[@@@@\\`.*/....=^............/@@` \n", "# .O........ .......@@/@@@/`..... . ,\\@\\....\\`............O@`@ \n", "# =^...`.... .O@@`......... .........\\@`...[`.,@`....,@^/.@^ \n", "# .OO`..\\.... =/..... ...... ..[@]....,\\@@]]]].@@]`..//..@=\\^ \n", "# @O/@`,............=O/...... ... .... ...\\\\.....,@@@`=\\@\\@@[...=O`/^. \n", "# @@\\.,@]..]]//[,/@^O=@............. .\\@^...........,@`.....\\@@/*\\o*O@\\.=/.@` \n", "# ,@/O`...[OOO`.,@O,\\/....././\\^.... ..@O` ..\\`.......=\\.....=\\\\@@@@@/\\@@// \n", "# ,@`\\].......O^o,/.....@`/=^.....,\\...,@^ ...=\\... =\\.....,@,@@@@[/@@@/ \n", "# ..,\\@\\]]]]O/@.*@.....=^/\\^......=@....\\O..^..@@`.. ..\\@.....,@.\\@@\\[[O` \n", "# .*=@@\\@@^.O^...../o^O.......O=^...=@..@..\\.\\\\. . @@`....,@.\\@@@@` \n", "# . ..=@O^=@`,@ .....@@=`......=^.O....@..@^.=^.=@.....=@@.....,\\.\\@@@@. \n", "# .,@@`,O@./^.....=@O/......./^.O... \\`.=^.=^..=@... O=\\.....=^.\\@@@@`. \n", "# ./@`.=^@=@......=@O`....@,/@@.=^...=^.=^.=^.[[\\@....=^\\^.....@@.\\@@@@` \n", "# .,@^. @^O/@......=@O.]O`OO.=`\\^.....,^.=@.=^....=@...=\\.O.....@^\\`@@/` \n", "# =@ .=@..@^ .....=@/.../@^,/.=@......* =@.=^.....=\\..=@`=^....=^ \\/\\ \n", "# /^..=@.,@^ /`...=@.../O@.O...@........O=^=` ,`...@^.=@\\=^..] =@..@O`. \n", "# ,@...@/.=@. @^...=@../@\\@/OOO.=^......=^,O@[.]]@\\]/@ =^@`O..O.=@^ =@^ \n", "# =^...@@.=@..O\\....@ //.O@O@@]..@....../^.OO@@@[[@@@@\\/^@^O .O.=@@ .@^ \n", "# @^..=@@.,@.=^@....@@\\@@@[[[[[[[\\^@^..,/..O..,@@@\\..=@@//OO..O./^@. =@ \n", "# @...=^@^.@.=^=^...=@@`/@@@@@`...*O\\..@...[.=@`,@@@`.@`=^@=`.O.@.@. =@. \n", "# @^..O.@^ \\^=@,\\..=@@ @\\,@@/@@`..=^..@`.....@@\\@@/@@...O.@=^,O=^.@^./@ \n", "# @@..O.=@.,\\=@^O..=`\\/@^/@@OO@^..,`,O`.. .. @@/@@\\@@..=`=@../^O..@^/O^ \n", "# .=@^ @..@`=@o@@=^..,.O@@/@@oO@........... ...@^.\\/@..=^=@/ =@O. .@\\@`. \n", "# .@@.@^.@^@^\\@@O^..=^,O@@*................. .......=^/@@^=@@^ .=@`. \n", "# .=O@O^,@^=^.\\@^o..=/\\,\\ ..... .... ..... ...]@O`=@O/@@^ =@ \n", "# .=O@O/^==@@`O@O^.=@.\\`\\`.... . ........ ......//@.@`. =^ \n", "# ,O@@^.O..\\@@@^.=@...[O@`.. . ........ .....//.@@,\\ .@^ \n", "# .@/@@@]../@@^..@@\\........ ..,/`=@/@`.....,@^..=^ =` .=@. \n", "# =/..O... @^=\\. O@@@@\\....... ...//.,@..@O].,/@`=\\..=@..@..@^ \n", "# ,/..O....=/=/@ .=@@@@@@@@].....//.,O@`.//.@@@@@..@^..@`.=\\/O`. \n", "# ,@../`....O=/.@...@@@@@@@@@@@@@/../\\@..//.=@@@@\\. @@..=\\..@^/. \n", "# ,@`.=`....=@/..@...\\@@@@@@@@.. O..,@/..=@ .O=@@@^. @/@..@^..@`. \n", "# ,@`.=^....,@/..=O^..,@@.[@@@@,@]@../^..=@../^=@@@...@.,\\.=@`..@` \n", "# ,@..=/. .@/...O=@...@@....,@@...,[@\\.,@`..@..@@/..,@..,\\.@@...@.. \n", "# @`.,/.....@/...=`O@^..,@...../`.......,\\@]..@..O@\\]]/\\`..,\\,@^..,@` \n", "# =^..@...../@...,^/O@@...=@`...@............\\@` /`,\\,@`.=\\.,\\@=@`..,@. \n", "# ,@../`....@\\`/@``,`]/@^...O,\\/\\@]..............\\\\..=@`\\\\ ,@@@@@@@....@`. \n", "# O`.=^....@^O@^.@@@@@@@\\....\\@^=@@@@@\\] ..........,@`\\@\\.@`=@@@@@@\\....@`.. \n", "# =/..O...,@O/@^.@@@@@@@@@`...=/.@@@@@@@@@@@].........,@@/@`,@/@@@@O\\^....@`.. \n", "# /^.O.../@O^@^./@@@@@@@@@\\...@`=@@@@@@@@@@@@@\\.......@`=\\//@`,@@@@@.@`....\\`... \n", "# .,@.=^../`@@\\@.=@@@@@@@@@@@^.=@.@@@@@@@@@@@@@@@@@`...@` =\\\\==`@`\\@@@^.@.....\\^... \n", "# ../\\^,@.,/.=@/=/,@@@@@@@@@@@@\\ @^=@@@@@@@@@@@@@@@@@@@]@@@@@@@@@o\\@`.@@\\.,@.....\\\\... \n", "# =/.@^@`/`..@@^@^=@@@@@@@@@@@@@\\@.@@@@@@@@@@@@@@@@@@@@@@@@O@@@@@\\/.,/.@@\\.,@.....,@`.. \n", "# ,O`.,@=@/...=@@.@^O@@@@@@@@@@@@@@^=@@@@@@@@@@@@@@@@@@@@@@@@@@O@@@^ /@@.,@/@`.@`.....\\\\... \n", "# ..=^...=^@^....@OO,@^/@@@@@@@@@@@@\\@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\@@@@@`=\\.\\^.\\`.....,@`.. \n", "# \n", "# 炼丹就不存在什么万能参数的, 可能下面给的参数里有的参数训练出来的效果很好, 有的效果就一般\n", "# 训练参数还看训练集呢, 同一套参数在不同训练集上效果都不一样, 可能好可能坏 (唉, 被这训练参数折磨过好多次)\n", "# 虽然说一直用同个效果不错的参数可能不会出现特别坏的结果吧\n", "# 还有好的训练集远比好的训练参数更重要\n", "# 好的训练集真的, 真的, 真的非常重要\n", "# 再好的参数, 训练集烂也救不回来\n", "# \n", "# \n", "# 10.\n", "# 建议先改改训练集路径的参数就开始训练, 跑通训练了再试着改其他参数\n", "# 还有我编写的训练参数不一定是最好的, 所以需要自己去摸索这些训练参数是什么作用的, 再去修改\n", "# 其实有些参数我自己也调不明白, 但是很多时候跑出来效果还不错\n", "# 为什么效果好, 分からない, 这东西像个黑盒, 有时候就觉得神奇呢\n", "##########################################################################################\n", "\n", "\n", "# 根据 https://github.com/KohakuBlueleaf/HDM/blob/main/config/train/hdm-xut-340M-ft.toml 修改的训练参数\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# [lightning]\n", "# seed=20090220\n", "# epochs=10\n", "# batch_size=8\n", "# dataloader_workers=4\n", "# persistent_workers=true\n", "# grad_acc=4\n", "# devices=1\n", "# precision=\"16-mixed\"\n", "# grad_clip=1.0\n", "# grad_ckpt=true\n", "# \n", "# [lightning.imggencallback]\n", "# id=\"HDM-xut-340M-finetune\"\n", "# size=1024\n", "# num=32\n", "# preview_num=8\n", "# batch_size=4\n", "# steps=32\n", "# period=128\n", "# [lightning.logger]\n", "# name=\"HDM-xut-340M-finetune\"\n", "# project=\"HDM\"\n", "# offline=true\n", "# \n", "# \n", "# [trainer]\n", "# name=\"test\"\n", "# lr=0.1 # We have muP scale, need higher LR here\n", "# optimizer=\"torch.optim.AdamW\"\n", "# opt_configs = {{\"weight_decay\"= 0.01, \"betas\"= [0.9, 0.95]}}\n", "# lr_sch_configs = {{\"end\"= -1, \"mode\"= \"cosine\", \"warmup\"= 1000, \"min_value\"= 0.01}}\n", "# te_use_normed_ctx=false\n", "# \n", "# \n", "# [dataset]\n", "# [[dataset.datasets]]\n", "# class = \"hdm.data.kohya.KohyaDataset\"\n", "# [dataset.datasets.kwargs]\n", "# size=1024\n", "# dataset_folder = \"{INPUT_DATASET_PATH}/test_dataset\"\n", "# keep_token_seperator=\"|||\"\n", "# tag_seperator=\", \"\n", "# seperator=\", \"\n", "# group_seperator=\"%%\"\n", "# tag_shuffle=true\n", "# group_shuffle=false\n", "# tag_dropout_rate=0.0\n", "# group_dropout_rate=0.0\n", "# use_cached_meta=true\n", "# # For example:\n", "# # \"xxx, zzz ||| aa $$ bb %% cc $$ dd\" -> \"xxx, zzz, aa, bb, dd, cc\"\n", "# \n", "# \n", "# [model]\n", "# config=\"{HDM_PATH}/config/model/xut-qwen3-sm-tread.yaml\"\n", "# model_path=\"{HDM_MODEL_PATH}/hdm-xut-340M-1024px-note.safetensors\"\n", "# inference_dtype = \"torch.float16\"\n", "# [model.lycoris]\n", "# algo = \"lokr\"\n", "# factor = 4\n", "# full_matrix = true\n", "# train_norm = true\n", "# \n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# !python \"{HDM_PATH}/scripts/train.py\" \"{toml_file_path}\"\n", "\n", "\n", "# 上面那个官方示例参数会报错, 不懂为什么, 这个是随便改过的, 倒是能跑\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# [lightning]\n", "# seed=20090220\n", "# epochs=10\n", "# batch_size=8\n", "# dataloader_workers=4\n", "# persistent_workers=true\n", "# grad_acc=4\n", "# devices=1\n", "# precision=\"16-mixed\"\n", "# grad_clip=1.0\n", "# grad_ckpt=true\n", "# \n", "# [lightning.imggencallback]\n", "# id=\"HDM-xut-340M-finetune\"\n", "# size=1024\n", "# num=32\n", "# preview_num=8\n", "# batch_size=4\n", "# steps=32\n", "# period=128\n", "# [lightning.logger]\n", "# name=\"HDM-xut-340M-finetune\"\n", "# project=\"HDM\"\n", "# offline=true\n", "# \n", "# \n", "# [trainer]\n", "# name=\"test\"\n", "# lr=0.1 # We have muP scale, need higher LR here\n", "# optimizer=\"torch.optim.AdamW\"\n", "# opt_configs = {{\"weight_decay\"= 0.01, \"betas\"= [0.9, 0.95]}}\n", "# lr_sch_configs = {{\"mode\"= \"cosine\", \"warmup\"= 1000, \"min_value\"= 0.01}}\n", "# te_use_normed_ctx=false\n", "# \n", "# \n", "# [dataset]\n", "# [[dataset.datasets]]\n", "# class = \"hdm.data.kohya.KohyaDataset\"\n", "# [dataset.datasets.kwargs]\n", "# size=1024\n", "# dataset_folder = \"{INPUT_DATASET_PATH}/test_dataset\"\n", "# keep_token_seperator=\"|||\"\n", "# tag_seperator=\", \"\n", "# seperator=\", \"\n", "# group_seperator=\"%%\"\n", "# tag_shuffle=true\n", "# group_shuffle=false\n", "# tag_dropout_rate=0.0\n", "# group_dropout_rate=0.0\n", "# use_cached_meta=true\n", "# # For example:\n", "# # \"xxx, zzz ||| aa $$ bb %% cc $$ dd\" -> \"xxx, zzz, aa, bb, dd, cc\"\n", "# \n", "# \n", "# [model]\n", "# config=\"{HDM_PATH}/config/model/xut-qwen3-sm-tread.yaml\"\n", "# model_path=\"{HDM_MODEL_PATH}/hdm-xut-340M-1024px-note.safetensors\"\n", "# inference_dtype = \"torch.float16\"\n", "# [model.lycoris]\n", "# algo = \"lokr\"\n", "# factor = 4\n", "# full_matrix = true\n", "# train_norm = true\n", "# \n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# !python \"{HDM_PATH}/scripts/train.py\" \"{toml_file_path}\"\n", "\n", "\n", "##########################################################################################\n", "os.chdir(WORKSPACE)\n", "logger.info(\"离开 HDM 目录\")\n", "logger.info(\"模型训练结束\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 模型上传\n", "通常不需要修改该单元内容,如果需要修改参数,建议通过上方的参数配置单元进行修改 \n", "5. [← 上一个单元](#模型训练)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 模型上传到 HuggingFace / ModelScope, 通常不需要修改, 修改参数建议通过上方的参数配置单元进行修改\n", "\n", "# 使用 HuggingFace 上传模型\n", "if USE_HF_TO_SAVE_MODEL:\n", " logger.info(\"使用 HuggingFace 保存模型\")\n", " hdm_manager.repo.upload_files_to_repo(**HF_REPO_UPLOADER_PARAMS)\n", "\n", "# 使用 ModelScope 上传模型\n", "if USE_MS_TO_SAVE_MODEL:\n", " logger.info(\"使用 ModelScope 保存模型\")\n", " hdm_manager.repo.upload_files_to_repo(**MS_REPO_UPLOADER_PARAMS)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 2 }
2301_81996401/sd-webui-all-in-one
notebook/hdm_train_kaggle.ipynb
Jupyter Notebook
agpl-3.0
72,455
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xlyptNJ2ICnN" }, "source": [ "# InvokeAI Colab\n", "Colab NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Colab](https://colab.research.google.com) 部署 [InvokeAI](https://github.com/invoke-ai/InvokeAI) 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "Colab 链接:<a href=\"https://colab.research.google.com/github/licyk/sd-webui-all-in-one/blob/main/notebook/invokeai_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式,并安装 [InvokeAI](https://github.com/invoke-ai/InvokeAI),默认设置下已启用`配置环境完成后立即启动 InvokeAI`选项,则安装完成后将直接启动 InvokeAI,并显示访问地址。\n", "2. 下载模型:下载可选列表中的模型(可选)。\n", "3. 自定义模型下载:使用链接下载模型(可选)。\n", "4. 启动 InvokeAI:启动 InvokeAI,并显示访问地址。\n", "\n", "\n", "## 使用\n", "1. 在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择`GPU T4`或者其他 GPU。\n", "2. `环境配置`单元中的选项通常不需要修改,保持默认即可。\n", "3. 运行`环境配置`单元,默认设置下已启用`配置环境完成后立即启动 InvokeAI`选项,则环境配置完成后立即启动 InvokeAI,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 InvokeAI,InvokeAI 的访问地址可在日志中查看。\n", "4. 如果未启用`配置环境完成后立即启动 InvokeAI`选项,需要运行`启动 InvokeAI`单元,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 InvokeAI,InvokeAI 的访问地址可在日志中查看。\n", "5. 提示词查询工具:[SD 绘画提示词查询](https://licyk.github.io/t/tag)\n", "\n", "## 提示\n", "1. Colab 在关机后将会清除所有数据,所以每次重新启动时必须运行`环境配置`单元才能运行`启动 InvokeAI`单元。\n", "2. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "3. [Zrok](https://zrok.io) 内网穿透在使用前需要填写 Zrok Token, 可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取。\n", "4. 每次启动 Colab 后必须运行`环境配置`单元,才能运行`启动 InvokeAI`单元启动 InvokeAI。\n", "5. 其他功能有自定义模型下载等功能,根据自己的需求进行使用。\n", "6. 运行`启动 InvokeAI`时将弹出 Google Drive 访问授权提示,根据提示进行授权。授权后,使用 InvokeAI 生成的图片将保存在 Google Drive 的`invokeai_output`文件夹中。\n", "7. Colab 的内存可能不足以让 InvokeAI 进行图片生成,导致 InvokeAI 异常关闭。如果出现该问题,可在启动一次 InvokeAI 后,在 Google Drive 的`invokeai_output`文件夹中找到`invokeai.yaml`文件并编辑,在文件中添加一行`keep_ram_copy_of_weights: false`后保存,再重新启动 InvokeAI。\n", "8. InvokeAI 使用教程可阅读:[InvokeAI 部署与使用 ](https://sdnote.netlify.app/guide/invokeai)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "VjYy0F2gZIPR" }, "outputs": [], "source": [ "#@title 👇 环境配置\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, InvokeAIManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "\n", "#######################################################\n", "\n", "#@markdown ## PyTorch 组件版本选项:\n", "#@markdown - PyTorch:\n", "DEVICE_TYPE = \"cuda\" # @param [\"cuda\", \"rocm\", \"xpu\", \"cpu\"]\n", "#@markdown ---\n", "#@markdown ## 包管理器选项:\n", "#@markdown - 使用 uv 作为 Python 包管理器\n", "USE_UV = True #@param {type:\"boolean\"}\n", "#@markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" #@param {type:\"string\"}\n", "#@markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 内网穿透选项:\n", "#@markdown - 使用 remote.moe 内网穿透\n", "USE_REMOTE_MOE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 localhost.run 内网穿透\n", "USE_LOCALHOST_RUN = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 pinggy.io 内网穿透\n", "USE_PINGGY_IO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 CloudFlare 内网穿透\n", "USE_CLOUDFLARE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Gradio 内网穿透\n", "USE_GRADIO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Ngrok 内网穿透(需填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取)\n", "USE_NGROK = True #@param {type:\"boolean\"}\n", "#@markdown - Ngrok Token\n", "NGROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown - 使用 Zrok 内网穿透(需填写 Zrok Token,可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取)\n", "USE_ZROK = True #@param {type:\"boolean\"}\n", "#@markdown - Zrok Token\n", "ZROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 快速启动选项:\n", "#@markdown - 配置环境完成后立即启动 InvokeAI(并挂载 Google Drive)\n", "QUICK_LAUNCH = True #@param {type:\"boolean\"}\n", "#@markdown - 不重复配置环境(当重复运行环境配置时将不会再进行安装)\n", "NO_REPEAT_CONFIGURE_ENV = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "#@markdown ## 其他选项:\n", "#@markdown - 清理无用日志\n", "CLEAR_LOG = True #@param {type:\"boolean\"}\n", "#@markdown - 检查可用 GPU\n", "CHECK_AVALIABLE_GPU = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 自动导入模型到 InvokeAI 中\n", "AUTO_IMPORT_MODEL = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 模型设置, 在安装时将会下载选择的模型:\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = True # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = True # @param {type:\"boolean\"}\n", "\n", "\n", "v1_5_pruned_emaonly and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\")\n", "animefull_final_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\")\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\")\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\")\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\")\n", "animagine_xl_3_0_base and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\")\n", "animagine_xl_3_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\")\n", "animagine_xl_3_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\")\n", "animagine_xl_4_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\")\n", "animagine_xl_4_0_opt and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\")\n", "holodayo_xl_2_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\")\n", "kivotos_xl_2_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\")\n", "clandestine_xl_1_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\")\n", "UrangDiffusion_1_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\")\n", "RaeDiffusion_XL_v2 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\")\n", "kohaku_xl_delta_rev1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\")\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\")\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\")\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\")\n", "kohaku_xl_zeta and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\")\n", "starryXLV52_v52 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\")\n", "heartOfAppleXL_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\")\n", "heartOfAppleXL_v30 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\")\n", "sanaexlAnimeV10_v10 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\")\n", "sanaexlAnimeV10_v11 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\")\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\")\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\")\n", "Illustrious_XL_v0_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\")\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\")\n", "Illustrious_XL_v1_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\")\n", "Illustrious_XL_v1_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\")\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\")\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\")\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\")\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\")\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\")\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\")\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\")\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\")\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\")\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\")\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\")\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\")\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\")\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\")\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\")\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\")\n", "pdForAnime_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\")\n", "omegaPonyXLAnime_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\")\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\")\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\")\n", "sdxl_fp16_fix_vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\")\n", "\n", "##############################################################################\n", "\n", "INSTALL_PARAMS = {\n", " \"device_type\": DEVICE_TYPE,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Colab 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " # 使用 InvokeAI Manager 内置 PyTorch 镜像源字典\n", " # \"pytorch_mirror_dict\": PYTORCH_MIRROR_DICT or None,\n", " \"model_list\": SD_MODEL,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"huggingface_token\": None,\n", " \"modelscope_token\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "\n", "TUNNEL_PARAMS = {\n", " \"use_ngrok\": USE_NGROK,\n", " \"ngrok_token\": NGROK_TOKEN or None,\n", " \"use_cloudflare\": USE_CLOUDFLARE,\n", " \"use_remote_moe\": USE_REMOTE_MOE,\n", " \"use_localhost_run\": USE_LOCALHOST_RUN,\n", " \"use_gradio\": USE_GRADIO,\n", " \"use_pinggy_io\": USE_PINGGY_IO,\n", " \"use_zrok\": USE_ZROK,\n", " \"zrok_token\": ZROK_TOKEN or None,\n", " \"message\": \"##### InvokeAI 访问地址 #####\",\n", "}\n", "\n", "INVOKEAI_PATH = \"/content/InvokeAI\"\n", "try:\n", " _ = invokeai_manager_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " invokeai = InvokeAIManager(os.path.dirname(INVOKEAI_PATH), os.path.basename(INVOKEAI_PATH), port=9090)\n", " invokeai_manager_has_init = True\n", "\n", "try:\n", " _ = invokeai_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " invokeai_has_init = False\n", "\n", "if NO_REPEAT_CONFIGURE_ENV:\n", " if not invokeai_has_init:\n", " invokeai.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " invokeai_has_init = True\n", " CLEAR_LOG and invokeai.clear_up()\n", " logger.info(\"InvokeAI 运行环境配置完成\")\n", " else:\n", " logger.info(\"检测到不重复配置环境已启用, 并且在当前 Colab 实例中已配置 InvokeAI 运行环境, 不再重复配置 InvokeAI 运行环境\")\n", " logger.info(\"如需在当前 Colab 实例中重新配置 InvokeAI 运行环境, 请在快速启动选项中取消不重复配置环境功能\")\n", "else:\n", " invokeai.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " CLEAR_LOG and invokeai.clear_up()\n", " logger.info(\"InvokeAI 运行环境配置完成\")\n", "\n", "if QUICK_LAUNCH:\n", " logger.info(\"启动 InvokeAI 中\")\n", " os.chdir(INVOKEAI_PATH)\n", " invokeai.check_env(use_uv=USE_UV)\n", " invokeai.mount_drive()\n", " if AUTO_IMPORT_MODEL:\n", " invokeai.import_model()\n", " invokeai.tun.start_tunnel(**TUNNEL_PARAMS)\n", " !python -c \"from invokeai.app.run_app import run_app; run_app()\"\n", " os.chdir(JUPYTER_ROOT_PATH)\n", " CLEAR_LOG and invokeai.clear_up()\n", " logger.info(\"已关闭 InvokeAI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "ZWnei0cZwWzK" }, "outputs": [], "source": [ "#@title 👇 下载模型(可选)\n", "\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 InvokeAI\")\n", "\n", "#@markdown 选择下载的模型:\n", "##############################\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = False # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = False # @param {type:\"boolean\"}\n", "\n", "v1_5_pruned_emaonly and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\")\n", "animefull_final_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\")\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\")\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\")\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\")\n", "animagine_xl_3_0_base and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\")\n", "animagine_xl_3_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\")\n", "animagine_xl_3_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\")\n", "animagine_xl_4_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\")\n", "animagine_xl_4_0_opt and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\")\n", "holodayo_xl_2_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\")\n", "kivotos_xl_2_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\")\n", "clandestine_xl_1_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\")\n", "UrangDiffusion_1_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\")\n", "RaeDiffusion_XL_v2 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\")\n", "kohaku_xl_delta_rev1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\")\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\")\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\")\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\")\n", "kohaku_xl_zeta and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\")\n", "starryXLV52_v52 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\")\n", "heartOfAppleXL_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\")\n", "heartOfAppleXL_v30 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\")\n", "sanaexlAnimeV10_v10 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\")\n", "sanaexlAnimeV10_v11 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\")\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\")\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\")\n", "Illustrious_XL_v0_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\")\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\")\n", "Illustrious_XL_v1_0 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\")\n", "Illustrious_XL_v1_1 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\")\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\")\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\")\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\")\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\")\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\")\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\")\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\")\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\")\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\")\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\")\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\")\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\")\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\")\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\")\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\")\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\")\n", "pdForAnime_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\")\n", "omegaPonyXLAnime_v20 and SD_MODEL.append(\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\")\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\")\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\")\n", "sdxl_fp16_fix_vae and SD_MODEL.append(\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\")\n", "\n", "##############################\n", "logger.info(\"下载模型中\")\n", "invokeai.get_sd_model_from_list(SD_MODEL)\n", "CLEAR_LOG and invokeai.clear_up()\n", "logger.info(\"模型下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MbpZVvRMPIAC" }, "outputs": [], "source": [ "#@title 👇 自定义模型下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 InvokeAI\")\n", "\n", "#@markdown ### 填写模型的下载链接:\n", "model_url = \"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "#@markdown ### 填写模型的名称(包括后缀名):\n", "model_name = \"CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "\n", "invokeai.get_sd_model(\n", " url=model_url,\n", " filename=model_name or None\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "cLB6sKhErcG8" }, "outputs": [], "source": [ "#@title 👇 启动 InvokeAI\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 InvokeAI\")\n", "\n", "logger.info(\"启动 InvokeAI\")\n", "os.chdir(INVOKEAI_PATH)\n", "invokeai.check_env(use_uv=USE_UV)\n", "invokeai.mount_drive()\n", "if AUTO_IMPORT_MODEL:\n", " invokeai.import_model()\n", "invokeai.tun.start_tunnel(**TUNNEL_PARAMS)\n", "!python -c \"from invokeai.app.run_app import run_app; run_app()\"\n", "os.chdir(JUPYTER_ROOT_PATH)\n", "CLEAR_LOG and invokeai.clear_up()\n", "logger.info(\"已关闭 InvokeAI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "AJJwUPF3Xoij" }, "outputs": [], "source": [ "#@title 👇 文件下载工具\n", "\n", "#@markdown ### 填写文件的下载链接:\n", "url = \"\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存路径:\n", "file_path = \"/content\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存名称 (可选):\n", "filename = \"\" #@param {type:\"string\"}\n", "\n", "invokeai.download_file(\n", " url=url,\n", " path=file_path or None,\n", " save_name=filename or None,\n", ")\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/invokeai_colab.ipynb
Jupyter Notebook
agpl-3.0
41,160
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "Gho2N54s0dXx" }, "source": [ "# SD Scripts Colab\n", "Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "\n", "## 简介\n", "一个在 [Colab](https://colab.research.google.com/) 部署 [sd-scripts](https://github.com/kohya-ss/sd-scripts) 的 Jupyter Notebook,可用于 Stable Diffusion 模型的训练。\n", "\n", "这个 Colab 脚本只是写来玩的,还有用来开发和测试管理模块的功能。如果要用这个脚本进行训练就参考 [SD Scripts Kaggle Jupyter NoteBook](https://github.com/licyk/sd-webui-all-in-one?tab=readme-ov-file#sd-scripts-kaggle-jupyter-notebook),毕竟同款核心。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "3rM4x-g4BiIa" }, "outputs": [], "source": [ "# @title 👇 参数配置\n", "# @markdown ## SD WebUI All In One 核心配置\n", "# @markdown - 模块下载地址\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one/raw/main/sd_scripts_ipynb_core.py\" # @param {\"type\":\"string\",\"placeholder\":\"填写 SD Scripts Manager 核心下载地址\"}\n", "# @markdown - 强制下载核心模块即使已存在\n", "FORCE_DOWNLOAD_CORE = False # @param {\"type\":\"boolean\"}\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "import os\n", "from pathlib import Path\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, SDScriptsManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# @markdown ## 环境设置\n", "# @markdown - 工作路径, 通常不需要修改\n", "WORKSPACE = \"/content\" # @param {\"type\":\"string\",\"placeholder\":\"填写工作路径\"}\n", "# @markdown - 工作路径中文件夹名称, 通常不需要修改\n", "WORKFOLDER = \"sd-scripts\" # @param {\"type\":\"string\",\"placeholder\":\"填写工作文件夹\"}\n", "# @markdown - sd-scripts 仓库地址\n", "SD_SCRIPTS_REPO = \"https://github.com/kohya-ss/sd-scripts\" # @param {\"type\":\"string\",\"placeholder\":\"填写 sd-scripts 仓库的 Git 地址\"}\n", "# @markdown - sd-scripts 依赖文件名\n", "SD_SCRIPTS_REQUIREMENTS = \"requirements.txt\" # @param {\"type\":\"string\",\"placeholder\":\"填写 sd-scripts 依赖记录的文件名\"}\n", "# @markdown - PyTorch 版本\n", "TORCH_VER = \"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124\" # @param {\"type\":\"string\",\"placeholder\":\"填写 PyTorch 软件包名和版本\"}\n", "# @markdown - xFormers 版本\n", "XFORMERS_VER = \"xformers==0.0.28.post3\" # @param {\"type\":\"string\",\"placeholder\":\"填写 xFormers 软件包名和版本\"}\n", "# @markdown - 使用 uv 加速 Python 软件包安装, 修改为 True 为启用, False 为禁用\n", "USE_UV = True # @param {type:\"boolean\"}\n", "# @markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" # @param {\"type\":\"string\",\"placeholder\":\"填写 PyPI 镜像地址\"}\n", "# @markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu124\" # @param {\"type\":\"string\",\"placeholder\":\"填写 PyPI 镜像地址\"}\n", "# @markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"\" #@param {type:\"string\"}\n", "# @markdown - 用于下载 PyTorch 的镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu124\" # @param {\"type\":\"string\",\"placeholder\":\"填写 PyTorch 镜像地址\"}\n", "# PyPI 扩展镜像源\n", "PIP_FIND_LINKS_MIRROR = \"https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "HUGGINGFACE_MIRROR = \"https://hf-mirror.com\" # HuggingFace 镜像源\n", "GITHUB_MIRROR = [ # Github 镜像源\n", " \"https://ghfast.top/https://github.com\",\n", " \"https://mirror.ghproxy.com/https://github.com\",\n", " \"https://ghproxy.net/https://github.com\",\n", " \"https://gh.api.99988866.xyz/https://github.com\",\n", " \"https://gh-proxy.com/https://github.com\",\n", " \"https://ghps.cc/https://github.com\",\n", " \"https://gh.idayer.com/https://github.com\",\n", " \"https://ghproxy.1888866.xyz/github.com\",\n", " \"https://slink.ltd/https://github.com\",\n", " \"https://github.boki.moe/github.com\",\n", " \"https://github.moeyy.xyz/https://github.com\",\n", " \"https://gh-proxy.net/https://github.com\",\n", " \"https://gh-proxy.ygxz.in/https://github.com\",\n", " \"https://wget.la/https://github.com\",\n", " \"https://kkgithub.com\",\n", " \"https://gitclone.com/github.com\",\n", "]\n", "# @markdown - 检查可用的 GPU, 当 GPU 不可用时强制终止安装进程\n", "CHECK_AVALIABLE_GPU = False # @param {type:\"boolean\"}\n", "# @markdown - 重试下载次数\n", "RETRY = 3 # @param {type:\"slider\", min:1, max:128, step:1}\n", "# @markdown - 下载线程\n", "DOWNLOAD_THREAD = 16 # @param {type:\"slider\", min:1, max:128, step:1}\n", "# @markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True # @param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# @markdown ## sd-scripts 版本设置\n", "# @markdown - sd-scripts 分支, 可切换成 main / dev 或者其它分支, 留空则不进行切换\n", "SD_SCRIPTS_BRANCH = \"dev\" # @param {\"type\":\"string\",\"placeholder\":\"填写 sd-scripts 分支名\"}\n", "# @markdown - 切换 sd-scripts 的版本到某个 Git 提交记录上, 留空则不进行切换\n", "SD_SCRIPTS_COMMIT = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 sd-scripts 版本提交哈希值\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# @markdown ## 模型上传设置, 使用 HuggingFace / ModelScope 上传训练好的模型\n", "# @markdown HuggingFace: https://huggingface.co\n", "# @markdown ModelScope: https://modelscope.cn\n", "# @markdown - 使用 HuggingFace 保存训练好的模型\n", "USE_HF_TO_SAVE_MODEL = False # @param {type:\"boolean\"}\n", "# @markdown - 使用 ModelScope 保存训练好的模型\n", "USE_MS_TO_SAVE_MODEL = False # @param {type:\"boolean\"}\n", "\n", "# @markdown ## Token 配置, 用于上传 / 下载模型 (部分模型下载需要 Token 进行验证)\n", "# @markdown HuggingFace Token 在 Account -> Settings -> Access Tokens 中获取\n", "# @markdown - HuggingFace Token\n", "HF_TOKEN = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 HuggingFace Token\"}\n", "# @markdown ModelScope Token 在 首页 -> 访问令牌 -> SDK 令牌 中获取\n", "# @markdown - ModelScope Token\n", "MS_TOKEN = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 ModelScope SDK 令牌\"}\n", "\n", "# @markdown ## 用于上传模型的 HuggingFace 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "# @markdown - HuggingFace 仓库的 ID (格式: \"用户名/仓库名\")\n", "HF_REPO_ID = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 HuggingFace 仓库 ID\"}\n", "# @markdown - HuggingFace 仓库的种类\n", "HF_REPO_TYPE = \"model\" # @param [\"model\", \"dataset\", \"space\"]\n", "# @markdown HuggingFace 仓库类型和对应名称:</br>\n", "# @markdown model: 模型仓库</br>\n", "# @markdown dataset: 数据集仓库</br>\n", "# @markdown space: 在线运行空间仓库</br>\n", "\n", "# @markdown ## 用于上传模型的 ModelScope 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "# @markdown - ModelScope 仓库的 ID (格式: \"用户名/仓库名\")\n", "MS_REPO_ID = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 ModelScope 仓库 ID\"}\n", "# @markdown - ModelScope 仓库的种类\n", "MS_REPO_TYPE = \"model\" # @param [\"model\", \"dataset\", \"space\"]\n", "# @markdown ModelScope 仓库类型和对应名称:</br>\n", "# @markdown model: 模型仓库</br>\n", "# @markdown dataset: 数据集仓库</br>\n", "# @markdown space: 创空间仓库</br>\n", "\n", "# @markdown ## 设置自动创建仓库时仓库的可见性, 通常保持默认即可\n", "# @markdown - 设置新建的 HuggingFace 仓库可见性\n", "HF_REPO_VISIBILITY = False # @param {type:\"boolean\"}\n", "# @markdown - 设置新建的 ModelScope 仓库可见性\n", "MS_REPO_VISIBILITY = False # @param {type:\"boolean\"}\n", "\n", "# @markdown ## Git 信息设置, 可以使用默认值\n", "# @markdown - Git 的邮箱\n", "GIT_USER_EMAIL = \"username@example.com\" # @param {\"type\":\"string\",\"placeholder\":\"填写邮箱\"}\n", "# @markdown - Git 的用户名\n", "GIT_USER_NAME = \"username\" # @param {\"type\":\"string\",\"placeholder\":\"填写用户名\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# @markdown ## 训练日志设置, 可使用 TensorBoard / WandB 记录训练日志, 使用 WandB 可远程查看实时训练日志\n", "# @markdown 使用 WandB 需要填写 WANDB_TOKEN</br>\n", "# @markdown 如果 TensorBoard 和 WandB 同时使用, 可以改成 all</br>\n", "# @markdown - 使用的日志记录工具 (tensorboard / wandb / all)\n", "LOG_MODULE = \"tensorboard\" # @param [\"tensorboard\", \"wandb\", \"all\"]\n", "\n", "# @markdown ## WandB Token 设置\n", "# @markdown WandB Token 可在 https://wandb.ai/authorize 中获取\n", "# @markdown - WandB Token\n", "WANDB_TOKEN = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写 WandB Token\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# 路径设置, 通常保持默认即可\n", "# @markdown - 训练集保存的路径\n", "INPUT_DATASET_PATH = \"/content/dataset\" # @param {\"type\":\"string\",\"placeholder\":\"填写训练集保存路径\"}\n", "# @markdown - 训练时模型保存的路径\n", "OUTPUT_PATH = \"/content/working/model\" # @param {\"type\":\"string\",\"placeholder\":\"填写训练输出的模型保存路径\"}\n", "# @markdown - 模型下载到的路径\n", "SD_MODEL_PATH = \"/content/sd-models\" # @param {\"type\":\"string\",\"placeholder\":\"填写下载模型的路径\"}\n", "\n", "# @markdown ---\n", "##############################################################################\n", "\n", "# @markdown ## 训练模型设置, 在安装时将会下载选择的模型\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = True # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = False # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = True # @param {type:\"boolean\"}\n", "\n", "v1_5_pruned_emaonly and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 1])\n", "animefull_final_pruned and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1])\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", 1])\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", 1])\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", 1])\n", "animagine_xl_3_0_base and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", 1])\n", "animagine_xl_3_0 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", 1])\n", "animagine_xl_3_1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", 1])\n", "animagine_xl_4_0 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", 1])\n", "animagine_xl_4_0_opt and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", 1])\n", "holodayo_xl_2_1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", 1])\n", "kivotos_xl_2_0 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", 1])\n", "clandestine_xl_1_0 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", 1])\n", "UrangDiffusion_1_1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", 1])\n", "RaeDiffusion_XL_v2 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", 1])\n", "kohaku_xl_delta_rev1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", 1])\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", 1])\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", 1])\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", 1])\n", "kohaku_xl_zeta and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", 1])\n", "starryXLV52_v52 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", 1])\n", "heartOfAppleXL_v20 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", 1])\n", "heartOfAppleXL_v30 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", 1])\n", "sanaexlAnimeV10_v10 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", 1])\n", "sanaexlAnimeV10_v11 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", 1])\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", 1])\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", 1])\n", "Illustrious_XL_v0_1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", 1])\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", 1])\n", "Illustrious_XL_v1_0 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", 1])\n", "Illustrious_XL_v1_1 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", 1])\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", 1])\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", 1])\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", 1])\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", 1])\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", 1])\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", 1])\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", 1])\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", 1])\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", 1])\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", 1])\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", 1])\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", 1])\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", 1])\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", 1])\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", 1])\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", 1])\n", "pdForAnime_v20 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", 1])\n", "omegaPonyXLAnime_v20 and SD_MODEL.append([\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", 1])\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append([\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", 1])\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append([\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", 1])\n", "sdxl_fp16_fix_vae and SD_MODEL.append([\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", 1])\n", "\n", "##############################################################################\n", "# 下面为初始化参数部分, 不需要修改\n", "INSTALL_PARAMS = {\n", " \"torch_ver\":TORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"git_branch\": SD_SCRIPTS_BRANCH or None,\n", " \"git_commit\": SD_SCRIPTS_COMMIT or None,\n", " \"model_path\": SD_MODEL_PATH or None,\n", " \"model_list\": SD_MODEL,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Kaggle 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"sd_scripts_repo\": SD_SCRIPTS_REPO or None,\n", " \"sd_scripts_requirements\": SD_SCRIPTS_REQUIREMENTS or None,\n", " \"retry\": RETRY,\n", " \"huggingface_token\": HF_TOKEN or None,\n", " \"modelscope_token\": MS_TOKEN or None,\n", " \"wandb_token\": WANDB_TOKEN or None,\n", " \"git_username\": GIT_USER_NAME or None,\n", " \"git_email\": GIT_USER_EMAIL or None,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "HF_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"huggingface\",\n", " \"repo_id\": HF_REPO_ID,\n", " \"repo_type\": HF_REPO_TYPE,\n", " \"visibility\": HF_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "MS_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"modelscope\",\n", " \"repo_id\": MS_REPO_ID,\n", " \"repo_type\": MS_REPO_TYPE,\n", " \"visibility\": MS_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "os.makedirs(WORKSPACE, exist_ok=True)\n", "os.makedirs(OUTPUT_PATH, exist_ok=True)\n", "os.makedirs(SD_MODEL_PATH, exist_ok=True)\n", "os.makedirs(INPUT_DATASET_PATH, exist_ok=True)\n", "SD_SCRIPTS_PATH = os.path.join(WORKSPACE, WORKFOLDER)\n", "logger.info(\"参数设置完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "UFVKyZcklP_G" }, "outputs": [], "source": [ "# @title 👇 安装环境\n", "logger.info(\"开始安装 sd-scripts\")\n", "sd_scripts = SDScriptsManager(WORKSPACE, WORKFOLDER)\n", "sd_scripts.install(**INSTALL_PARAMS)\n", "logger.info(\"sd-scripts 安装完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "1F2_0hx2m5g8" }, "outputs": [], "source": [ "# @title 👇 模型下载工具: `sd_scripts.get_model()`\n", "# @markdown - 模型下载链接\n", "url = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写模型下载链接\"}\n", "# @markdown - 保存的文件名 (可选)\n", "filename = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写模型的名称\"}\n", "sd_scripts.get_model(\n", " url=url,\n", " path=SD_MODEL_PATH,\n", " filename=filename if filename else None,\n", " retry=RETRY,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "1cMde4KuoCCJ" }, "outputs": [], "source": [ "# @title 👇 模型 / 训练集下载工具: `sd_scripts.repo.download_files_from_repo()`\n", "# @markdown 可从 HuggingFace / ModelScope 仓库下载文件\n", "# @markdown - 仓库类型\n", "api_type = \"huggingface\" # @param [\"huggingface\", \"modelscope\"]\n", "# @markdown - 仓库 ID\n", "repo_id = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写仓库的 ID\"}\n", "# @markdown - 仓库类型\n", "repo_type = \"model\" # @param [\"model\", \"dataset\", \"space\"]\n", "# @markdown 文件在仓库中的路径, 不填写则下载整个仓库\n", "folder = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写文件在仓库中的路径\"}\n", "sd_scripts.repo.download_files_from_repo(\n", " api_type=api_type,\n", " local_dir=SD_MODEL_PATH,\n", " repo_id=repo_id,\n", " repo_type=repo_type,\n", " folder=folder,\n", " retry=RETRY,\n", " num_threads=DOWNLOAD_THREAD,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "clCiubeFpvO3" }, "outputs": [], "source": [ "# @title 👇 压缩包下载工具并解压: `sd_scripts.download_archive_and_unpack()`\n", "# @markdown 支持的压缩包格式为 `ZIP`, `7Z`, `TAR`\n", "# @markdown - 压缩包的下载链接\n", "url = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写压缩包的下载链接\"}\n", "# @markdown - 将压缩包进行重命名的名称\n", "name = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写压缩包进行重命名的名称\"}\n", "\n", "sd_scripts.download_archive_and_unpack(\n", " url=url,\n", " local_dir=INPUT_DATASET_PATH,\n", " name=name if name else None,\n", " retry=RETRY,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "Fw3iiY3wraCf" }, "outputs": [], "source": [ "# @title 👇 模型 / 训练集制作工具: `make_dataset()`\n", "# @markdown 基于`sd_scripts.repo.download_files_from_repo()`进行封装</br>\n", "# @markdown 可以自动为下载好的训练集添加重复次数\n", "def make_dataset(\n", " api_type: str,\n", " local_dir: str | Path,\n", " repo_id: str,\n", " repo_type: str,\n", " repeat: int,\n", " folder: str,\n", ") -> None:\n", " import os\n", " import shutil\n", " origin_dataset_path = os.path.join(local_dir, folder)\n", " tmp_dataset_path = os.path.join(local_dir, f\"{repeat}_{folder}\")\n", " new_dataset_path = os.path.join(origin_dataset_path, f\"{repeat}_{folder}\")\n", " sd_scripts.repo.download_files_from_repo(\n", " api_type=api_type,\n", " local_dir=local_dir,\n", " repo_id=repo_id,\n", " repo_type=repo_type,\n", " folder=folder,\n", " retry=RETRY,\n", " num_threads=DOWNLOAD_THREAD,\n", " )\n", " if os.path.exists(origin_dataset_path):\n", " logger.info(\"设置 %s 训练集的重复次数为 %s\", folder, repeat)\n", " shutil.move(origin_dataset_path, tmp_dataset_path)\n", " shutil.move(tmp_dataset_path, new_dataset_path)\n", " else:\n", " logger.error(\"从 %s 下载 %s 失败\", repo_id, folder)\n", "# @markdown - 仓库类型\n", "api_type = \"huggingface\" # @param [\"huggingface\", \"modelscope\"]\n", "# @markdown - 仓库 ID\n", "repo_id = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写仓库 ID\"}\n", "# @markdown - 仓库类型\n", "repo_type = \"model\" # @param [\"model\", \"dataset\", \"space\"]\n", "# @markdown - 训练集文件夹在仓库中的路径\n", "folder = \"\" # @param {\"type\":\"string\",\"placeholder\":\"填写训练集文件夹在仓库中的路径\"}\n", "# @markdown - 设置训练集的重复次数\n", "repeat = 1 # @param {type:\"slider\", min:1, max:128, step:1}\n", "\n", "make_dataset(\n", " api_type=api_type,\n", " local_dir=INPUT_DATASET_PATH,\n", " repo_id=repo_id,\n", " repo_type=repo_type,\n", " repeat=repeat,\n", " folder=folder,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "tLKy9x2mtp8A" }, "outputs": [], "source": [ "# @title 👇 模型训练 (可自行修改训练参数)\n", "\n", "pretrained_model_name_or_path = \"noobaiXLNAIXL_vPred10Version.safetensors\" # @param {type:\"string\"}\n", "vae = \"sdxl_fp16_fix_vae.safetensors\" # @param {type:\"string\"}\n", "train_data_dir = \"Nachoneko\" # @param {type:\"string\"}\n", "output_name = \"Nachoneko_2\" # @param {type:\"string\"}\n", "output_dir = \"Nachoneko\" # @param {type:\"string\"}\n", "wandb_run_name = \"Nachoneko\" # @param {type:\"string\"}\n", "log_tracker_name = \"lora-Nachoneko\" # @param {type:\"string\"}\n", "resolution = \"1024,1024\" # @param {type:\"string\"}\n", "save_every_n_epochs = \"1\" # @param {type:\"string\"}\n", "max_train_epochs = \"2\" # @param {type:\"string\"}\n", "train_batch_size = \"6\" # @param {type:\"string\"}\n", "learning_rate = \"0.0001\" # @param {type:\"string\"}\n", "unet_lr = \"0.0001\" # @param {type:\"string\"}\n", "text_encoder_lr = \"0.00001\" # @param {type:\"string\"}\n", "lr_scheduler = \"constant_with_warmup\" # @param {type:\"string\"}\n", "lr_warmup_steps = \"100\" # @param {type:\"string\"}\n", "optimizer_type = \"Lion8bit\" # @param {type:\"string\"}\n", "\n", "!python \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", " --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/{pretrained_model_name_or_path}\" \\\n", " --vae=\"{SD_MODEL_PATH}/{vae}\" \\\n", " --train_data_dir=\"{INPUT_DATASET_PATH}/{train_data_dir}\" \\\n", " --output_name=\"{output_name}\" \\\n", " --output_dir=\"{OUTPUT_PATH}/{output_dir}\" \\\n", " --wandb_run_name=\"{wandb_run_name}\" \\\n", " --log_tracker_name=\"{log_tracker_name}\" \\\n", " --prior_loss_weight=1 \\\n", " --resolution=\"{resolution}\" \\\n", " --enable_bucket \\\n", " --min_bucket_reso=256 \\\n", " --max_bucket_reso=4096 \\\n", " --bucket_reso_steps=64 \\\n", " --save_model_as=\"safetensors\" \\\n", " --save_precision=\"fp16\" \\\n", " --save_every_n_epochs=\"{save_every_n_epochs}\" \\\n", " --max_train_epochs=\"{max_train_epochs}\" \\\n", " --train_batch_size=\"{train_batch_size}\" \\\n", " --gradient_checkpointing \\\n", " --network_train_unet_only \\\n", " --learning_rate=\"{learning_rate}\" \\\n", " --unet_lr=\"{unet_lr}\" \\\n", " --text_encoder_lr=\"{text_encoder_lr}\" \\\n", " --lr_scheduler=\"{lr_scheduler}\" \\\n", " --lr_warmup_steps=\"{lr_warmup_steps}\" \\\n", " --optimizer_type=\"{optimizer_type}\" \\\n", " --network_module=\"lycoris.kohya\" \\\n", " --network_dim=100000 \\\n", " --network_alpha=100000 \\\n", " --network_args \\\n", " conv_dim=100000 \\\n", " conv_alpha=100000 \\\n", " algo=lokr \\\n", " dropout=0 \\\n", " factor=8 \\\n", " train_norm=True \\\n", " preset=\"full\" \\\n", " --optimizer_args \\\n", " weight_decay=0.05 \\\n", " betas=\"0.9,0.95\" \\\n", " --log_with=\"{LOG_MODULE}\" \\\n", " --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", " --caption_extension=\".txt\" \\\n", " --shuffle_caption \\\n", " --keep_tokens=0 \\\n", " --max_token_length=225 \\\n", " --seed=1337 \\\n", " --mixed_precision=\"fp16\" \\\n", " --xformers \\\n", " --cache_latents \\\n", " --cache_latents_to_disk \\\n", " --persistent_data_loader_workers \\\n", " --debiased_estimation_loss \\\n", " --vae_batch_size=4 \\\n", " --full_fp16" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "tpKPeMXN0C9X" }, "outputs": [], "source": [ "# @title 👇 上传模型到 HuggingFace / ModelScope\n", "# 使用 HuggingFace 上传模型\n", "if USE_HF_TO_SAVE_MODEL:\n", " logger.info(\"使用 HuggingFace 保存模型\")\n", " sd_scripts.repo.upload_files_to_repo(**HF_REPO_UPLOADER_PARAMS)\n", "\n", "# 使用 ModelScope 上传模型\n", "if USE_MS_TO_SAVE_MODEL:\n", " logger.info(\"使用 ModelScope 保存模型\")\n", " sd_scripts.repo.upload_files_to_repo(**MS_REPO_UPLOADER_PARAMS)" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "private_outputs": true, "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/sd_scripts_colab.ipynb
Jupyter Notebook
agpl-3.0
39,613
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SD Scripts Kaggle\n", "Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "\n", "## 简介\n", "一个在 [Kaggle](https://www.kaggle.com) 部署 [sd-scripts](https://github.com/kohya-ss/sd-scripts) 的 Jupyter Notebook,可用于 Stable Diffusion 模型的训练。\n", "\n", "<h2 style=\"color: red;\">切记,不要在 Kaggle 使用包含 NSFW 的训练集,这将导致 Kaggle 账号被封禁!!!</h2>\n", "\n", "## 不同运行单元的功能\n", "该 Notebook 分为以下几个单元:\n", "\n", "- [功能初始化](#功能初始化)\n", "- [参数配置](#参数配置)\n", "- [安装环境](#安装环境)\n", "- [模型训练](#模型训练)\n", "- [模型上传](#模型上传)\n", "\n", "使用时请按顺序运行笔记单元。\n", "\n", "通常情况下[功能初始化](#功能初始化)和[模型上传](#模型上传)单元的内容无需修改,其他单元包含不同功能的注释,可阅读注释获得帮助。\n", "\n", "[参数配置](#参数配置)单元用于修改安装,训练,上传模型时的配置。\n", "\n", "[安装](#安装)单元执行安装训练环境的命令和下载模型 / 训练集的命令,可根据需求进行修改。\n", "\n", "[模型训练](#模型训练)执行训练模型的命令,需要根据自己的需求进行修改,该单元也提供一些训练参数的例子,可在例子的基础上进行修改。\n", "\n", "如果需要快速取消注释,可以选中代码,按下`Ctrl + /`取消注释。\n", "\n", "\n", "## 提示\n", "1. 不同单元中包含注释, 可阅读注释获得帮助。\n", "2. 训练代码的部分需要根据自己的需求进行更改。\n", "3. 推荐使用 Kaggle 的 `Save Version` 的功能运行笔记,可让 Kaggle 笔记在无人值守下保持运行,直至所有单元运行完成。\n", "4. 如果有 [HuggingFace](https://huggingface.co) 账号或者 [ModelScope](https://modelscope.cn) 账号,可通过填写 Token 和仓库名后实现自动上传训练好的模型,仓库需要手动创建。\n", "5. 进入 Kaggle 笔记后,在 Kaggle 的右侧栏可以调整 kaggle 笔记的设置,也可以上传训练集等。注意,在 Kaggle 笔记的`Session options`->`ACCELERATOR`中,需要选择`GPU T4 x 2`,才能使用 GPU 进行模型训练。\n", "6. 使用 Kaggle 进行模型训练时,训练集中最好没有 NSFW 内容,否则可能会导致 Kaggle 账号被封禁。\n", "7. 不同单元的标题下方包含快捷跳转链接,可使用跳转链接翻阅 Notebook。\n", "8. 该 Notebook 的使用方法可阅读:</br>[使用 HuggingFace / ModelScope 保存和下载文件 - licyk的小窝](https://licyk.netlify.app/2025/01/16/use-huggingface-or-modelscope-to-save-file/)</br>[使用 Kaggle 进行模型训练 - licyk的小窝](https://licyk.netlify.app/2025/01/16/use-kaggle-to-training-sd-model)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 功能初始化\n", "通常不需要修改该单元的内容 \n", "1. [[下一个单元 →](#参数配置)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "os.environ[\"SD_WEBUI_ALL_IN_ONE_LOGGER_COLOR\"] = \"0\"\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, SDScriptsManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 参数配置\n", "设置必要的参数, 根据注释说明进行修改 \n", "2. [[← 上一个单元](#功能初始化)|[下一个单元 →](#安装环境)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 环境设置\n", "WORKSPACE = \"/kaggle\" # 工作路径, 通常不需要修改\n", "WORKFOLDER = \"sd-scripts\" # 工作路径中文件夹名称, 通常不需要修改\n", "SD_SCRIPTS_REPO = \"https://github.com/kohya-ss/sd-scripts\" # sd-scripts 仓库地址\n", "SD_SCRIPTS_REQUIREMENTS = \"requirements.txt\" # sd-scripts 依赖文件名\n", "TORCH_VER = \"torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124\" # PyTorch 版本\n", "XFORMERS_VER = \"xformers==0.0.28.post3\" # xFormers 版本\n", "USE_UV = True # 使用 uv 加速 Python 软件包安装, 修改为 True 为启用, False 为禁用\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" # PyPI 主镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu124\" # PyPI 扩展镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu124\" # 用于下载 PyTorch 的镜像源\n", "PIP_FIND_LINKS_MIRROR = \"https://download.pytorch.org/whl/cu121/torch_stable.html\" # PyPI 扩展镜像源\n", "HUGGINGFACE_MIRROR = \"https://hf-mirror.com\" # HuggingFace 镜像源\n", "GITHUB_MIRROR = [ # Github 镜像源\n", " \"https://ghfast.top/https://github.com\",\n", " \"https://mirror.ghproxy.com/https://github.com\",\n", " \"https://ghproxy.net/https://github.com\",\n", " \"https://gh.api.99988866.xyz/https://github.com\",\n", " \"https://gh-proxy.com/https://github.com\",\n", " \"https://ghps.cc/https://github.com\",\n", " \"https://gh.idayer.com/https://github.com\",\n", " \"https://ghproxy.1888866.xyz/github.com\",\n", " \"https://slink.ltd/https://github.com\",\n", " \"https://github.boki.moe/github.com\",\n", " \"https://github.moeyy.xyz/https://github.com\",\n", " \"https://gh-proxy.net/https://github.com\",\n", " \"https://gh-proxy.ygxz.in/https://github.com\",\n", " \"https://wget.la/https://github.com\",\n", " \"https://kkgithub.com\",\n", " \"https://gitclone.com/github.com\",\n", "]\n", "CHECK_AVALIABLE_GPU = False # 检查可用的 GPU, 当 GPU 不可用时强制终止安装进程\n", "RETRY = 3 # 重试下载次数\n", "DOWNLOAD_THREAD = 16 # 下载线程\n", "ENABLE_TCMALLOC = True # 启用 TCMalloc 内存优化\n", "ENABLE_CUDA_MALLOC = True # 启用 CUDA Malloc 显存优化\n", "UPDATE_CORE = True # 更新内核\n", "\n", "##############################################################################\n", "\n", "# sd-scripts 版本设置\n", "SD_SCRIPTS_BRANCH = \"sd3\" # sd-scripts 分支, 可切换成 main / dev / sd3 或者其它分支, 留空则不进行切换\n", "SD_SCRIPTS_COMMIT = \"\" # 切换 sd-scripts 的版本到某个 Git 提交记录上, 留空则不进行切换\n", "\n", "##############################################################################\n", "\n", "# 模型上传设置, 使用 HuggingFace / ModelScope 上传训练好的模型\n", "# HuggingFace: https://huggingface.co\n", "# ModelScope: https://modelscope.cn\n", "USE_HF_TO_SAVE_MODEL = False # 使用 HuggingFace 保存训练好的模型, 修改为 True 为启用, False 为禁用 (True / False)\n", "USE_MS_TO_SAVE_MODEL = False # 使用 ModelScope 保存训练好的模型, 修改为 True 为启用, False 为禁用 (True / False)\n", "\n", "# Token 配置, 用于上传 / 下载模型 (部分模型下载需要 Token 进行验证)\n", "# HuggingFace Token 在 Account -> Settings -> Access Tokens 中获取\n", "HF_TOKEN = \"\" # HuggingFace Token, 可在 https://huggingface.co/settings/tokens 获取\n", "# ModelScope Token 在 首页 -> 访问令牌 -> SDK 令牌 中获取\n", "MS_TOKEN = \"\" # ModelScope Token, 可在 https://modelscope.cn/my/myaccesstoken 获取\n", "\n", "# 用于上传模型的 HuggingFace 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "HF_REPO_ID = \"username/reponame\" # HuggingFace 仓库的 ID (格式: \"用户名/仓库名\")\n", "HF_REPO_TYPE = \"model\" # HuggingFace 仓库的种类 (可选的类型为: model / dataset / space), 如果在 HuggingFace 新建的仓库为模型仓库则不需要修改\n", "# HuggingFace 仓库类型和对应名称:\n", "# model: 模型仓库\n", "# dataset: 数据集仓库\n", "# space: 在线运行空间仓库\n", "\n", "# 用于上传模型的 ModelScope 模型仓库的 ID, 当仓库不存在时则尝试新建一个\n", "MS_REPO_ID = \"username/reponame\" # ModelScope 仓库的 ID (格式: \"用户名/仓库名\")\n", "MS_REPO_TYPE = \"model\" # ModelScope 仓库的种类 (model / dataset / space), 如果在 ModelScope 新建的仓库为模型仓库则不需要修改\n", "# ModelScope 仓库类型和对应名称:\n", "# model: 模型仓库\n", "# dataset: 数据集仓库\n", "# space: 创空间仓库\n", "\n", "# 设置自动创建仓库时仓库的可见性, False 为私有仓库(不可见), True 为公有仓库(可见), 通常保持默认即可\n", "HF_REPO_VISIBILITY = False # 设置新建的 HuggingFace 仓库可见性 (True / False)\n", "MS_REPO_VISIBILITY = False # 设置新建的 ModelScope 仓库可见性 (True / False)\n", "\n", "# Git 信息设置, 可以使用默认值\n", "GIT_USER_EMAIL = \"username@example.com\" # Git 的邮箱\n", "GIT_USER_NAME = \"username\" # Git 的用户名\n", "\n", "##############################################################################\n", "\n", "# 训练日志设置, 可使用 TensorBoard / WandB 记录训练日志, 使用 WandB 可远程查看实时训练日志\n", "# 使用 WandB 需要填写 WANDB_TOKEN\n", "# 如果 TensorBoard 和 WandB 同时使用, 可以改成 all\n", "LOG_MODULE = \"tensorboard\" # 使用的日志记录工具 (tensorboard / wandb / all)\n", "\n", "# WandB Token 设置\n", "# WandB Token 可在 https://wandb.ai/authorize 中获取\n", "WANDB_TOKEN = \"\" # WandB Token\n", "\n", "##############################################################################\n", "\n", "# 路径设置, 通常保持默认即可\n", "INPUT_DATASET_PATH = \"/kaggle/dataset\" # 训练集保存的路径\n", "OUTPUT_PATH = \"/kaggle/working/model\" # 训练时模型保存的路径\n", "SD_MODEL_PATH = \"/kaggle/sd-models\" # 模型下载到的路径\n", "KAGGLE_INPUT_PATH = \"/kaggle/input\" # Kaggle Input 的路径\n", "\n", "##############################################################################\n", "\n", "# 训练模型设置, 在安装时将会下载选择的模型\n", "# 下面举个例子:\n", "# SD_MODEL = [\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", "# [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", 1, \"Illustrious.safetensors\"]\n", "# ]\n", "# \n", "# 在这个例子中, 第一个参数指定了模型的下载链接, 第二个参数设置了是否要下载这个模型, 当这个值为 1 时则下载该模型\n", "# 第三个参数是可选参数, 用于指定下载到本地后的文件名称\n", "# \n", "# 则上面的例子中\n", "# https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors 和 \n", "# https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors 下载链接所指的文件将被下载\n", "# https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors 的文件下载到本地后名称为 animefull-final-pruned.safetensors\n", "# 并且 https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors 所指的文件将被重命名为 Illustrious.safetensors\n", "\n", "SD_MODEL = [\n", " # Stable Diffusion 模型\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cetusMix_Whalefall2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ex2K_sse2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/kohakuV5_rev2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinamix_meinaV11.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/oukaStar_10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/rabbit_v6.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/sweetSugarSyndrome_rev15.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/AnythingV5Ink_ink.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinapastel_v6Pastel.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/qteamixQ_omegaFp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_anime_V52.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBlueArchiveFlatCelluloidStyle_xlv3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/PVCStyleModelMovable_illustriousxl10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/miaomiaoHarem_v15a.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/waiNSFWIllustrious_v80.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/tIllunai3_v4.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/PVCStyleModelMovable_nbxl12.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/PVCStyleModelMovable_nbxlVPredV10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/tPonynai3_v51WeightOptimized.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animeIllustDiffusion_v061.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/artiwaifuDiffusion_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/artiwaifu-diffusion-v2.safetensors\", 0],\n", "\n", " # VAE 模型\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", 1],\n", "]\n", "\n", "##############################################################################\n", "# 下面为初始化参数部分, 不需要修改\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": TORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"git_branch\": SD_SCRIPTS_BRANCH or None,\n", " \"git_commit\": SD_SCRIPTS_COMMIT or None,\n", " \"model_path\": SD_MODEL_PATH or None,\n", " \"model_list\": SD_MODEL,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " # Kaggle 的环境暂不需要以下镜像源\n", " # \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"sd_scripts_repo\": SD_SCRIPTS_REPO or None,\n", " \"sd_scripts_requirements\": SD_SCRIPTS_REQUIREMENTS or None,\n", " \"retry\": RETRY,\n", " \"huggingface_token\": HF_TOKEN or None,\n", " \"modelscope_token\": MS_TOKEN or None,\n", " \"wandb_token\": WANDB_TOKEN or None,\n", " \"git_username\": GIT_USER_NAME or None,\n", " \"git_email\": GIT_USER_EMAIL or None,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "HF_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"huggingface\",\n", " \"repo_id\": HF_REPO_ID,\n", " \"repo_type\": HF_REPO_TYPE,\n", " \"visibility\": HF_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "MS_REPO_UPLOADER_PARAMS = {\n", " \"api_type\": \"modelscope\",\n", " \"repo_id\": MS_REPO_ID,\n", " \"repo_type\": MS_REPO_TYPE,\n", " \"visibility\": MS_REPO_VISIBILITY,\n", " \"upload_path\": OUTPUT_PATH,\n", " \"retry\": RETRY,\n", "}\n", "os.makedirs(WORKSPACE, exist_ok=True) # 创建工作路径\n", "os.makedirs(OUTPUT_PATH, exist_ok=True) # 创建模型输出路径\n", "os.makedirs(INPUT_DATASET_PATH, exist_ok=True) # 创建训练集路径\n", "os.makedirs(SD_MODEL_PATH, exist_ok=True) # 创建模型下载路径\n", "SD_SCRIPTS_PATH = os.path.join(WORKSPACE, WORKFOLDER) # sd-scripts 路径\n", "logger.info(\"参数设置完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 安装环境\n", "安装环境和下载模型和训练集, 根据注释的说明进行修改 \n", "3. [[← 上一个单元](#参数配置)|[下一个单元 →](#模型训练)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 初始化部分参数并执行安装命令, 这一小部分不需要修改\n", "logger.info(\"开始安装 sd-scripts\")\n", "sd_scripts = SDScriptsManager(WORKSPACE, WORKFOLDER)\n", "sd_scripts.install(**INSTALL_PARAMS)\n", "sd_scripts.import_kaggle_input(KAGGLE_INPUT_PATH, INPUT_DATASET_PATH)\n", "##########################################################################################\n", "# 下方可自行编写命令\n", "# 下方的命令示例可以根据自己的需求进行修改\n", "\n", "\n", "##### 1. 关于运行环境 #####\n", "\n", "# 如果需要安装某个软件包, 可以使用 %pip 命令\n", "# 下面是几个使用例子:\n", "# 1.\n", "# %pip install lycoris-lora==2.1.0.post3 dadaptation==3.1\n", "# \n", "# 这将安装 lycoris-lora==2.1.0.post3 和 dadaptation==3.1\n", "# \n", "# 2.\n", "# %pip uninstall tensorboard\n", "# \n", "# 这将卸载 tensorboard\n", "\n", "\n", "##########################################################################################\n", "\n", "\n", "##### 2. 关于模型导入 #####\n", "\n", "# 该 Kaggle 训练脚本支持 4 种方式导入模型, 如下:\n", "# 1. 使用 Kaggle Input 导入\n", "# 2. 使用模型下载链接导入\n", "# 3. 从 HuggingFace 仓库导入\n", "# 4. 从 ModelScope 仓库导入\n", "\n", "\n", "### 2.1. 使用 Kaggle Input 导入 ###\n", "# 在 Kaggle 右侧面板中, 点击 Notebook -> Input -> Upload -> New Model, 从此处导入模型\n", "# 这将 KAGGLE_INPUT_PATH 内的文件复制到 INPUT_DATASET_PATH 指定的路径\n", "# 即将 /kaggle/input 中的所有文件复制到 /kaggle/dataset 中\n", "\n", "\n", "### 2.2 使用模型下载链接导入 ###\n", "# 如果需要通过链接下载额外的模型, 可以使用 sd_scripts.get_model()\n", "# 使用参数:\n", "# sd_scripts.get_model(\n", "# url=\"model_url\", # 模型下载链接\n", "# path=SD_MODEL_PATH, # 模型下载到本地的路径\n", "# filename=\"filename.safetensors\", # 模型的名称\n", "# retry=RETRY, # 重试下载的次数\n", "# )\n", "# \n", "# 下面是几个使用例子:\n", "# 1.\n", "# sd_scripts.get_model(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors\",\n", "# path=SD_MODEL_PATH,\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors 下载模型并保存到 SD_MODEL_PATH 中\n", "# \n", "# sd_scripts.get_model(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors\",\n", "# path=SD_MODEL_PATH,\n", "# filename=\"rename_model.safetensors\",\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/your_model.safetensors 下载模型并保存到 SD_MODEL_PATH 中, 并且重命名为 rename_model.safetensors\n", "\n", "\n", "### 2.3. 从 HuggingFace 仓库导入 ###\n", "# 如果需要从 HuggingFace 仓库下载模型, 可以使用 sd_scripts.repo.download_files_from_repo()\n", "# 使用参数:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\", # 指定为 HuggingFace 的仓库\n", "# local_dir=SD_MODEL_PATH, # 模型下载到本地的路径\n", "# repo_id=\"usename/repo_id\", # HuggingFace 仓库 ID\n", "# repo_type=\"model\", # (可选参数) HuggingFace 仓库种类 (model / dataset / space)\n", "# folder=\"path/in/repo/file.safetensors\", # (可选参数) 文件在 HuggingFace 仓库中的路径\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 例如要从 stabilityai/stable-diffusion-xl-base-1.0 (类型为 model) 下载 sd_xl_base_1.0_0.9vae.safetensors\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=SD_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 则上述的命令将会从 stabilityai/stable-diffusion-xl-base-1.0 下载 sd_xl_base_1.0_0.9vae.safetensors 模型\n", "# 并将模型保存到 SD_MODEL_PATH 中\n", "# 注意 folder 填的是文件在 HuggingFace 仓库中的路径, 如果上述例子中的文件在仓库的 checkpoint/sd_xl_base_1.0_0.9vae.safetensors 路径\n", "# 则 folder 填的内容为 checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "#\n", "# 模型保存的路径与 local_dir 和 folder 参数有关\n", "# 对于上面的例子 local_dir 为 /kaggle/sd-models, folder 为 sd_xl_base_1.0_0.9vae.safetensors\n", "# 则最终保存的路径为 /kaggle/sd-models/sd_xl_base_1.0_0.9vae.safetensors\n", "# \n", "# 如果 folder 为 checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "# 则最终保存的路径为 /kaggle/sd-models/checkpoint/sd_xl_base_1.0_0.9vae.safetensors\n", "# \n", "# folder 参数为可选参数, 即该参数可不指定, 在不指定的情况下将下载整个仓库中的文件\n", "# 比如将上面的例子改成:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# local_dir=SD_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 这时候将下载 stabilityai/stable-diffusion-xl-base-1.0 仓库中的所有文件\n", "# 对于可选参数, 可以进行省略, 此时将使用该参数的默认值进行运行, 上面的例子就可以简化成下面的:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=SD_MODEL_PATH,\n", "# )\n", "# 省略后仍然可以正常执行, 但对于一些重要的可选参数, 不推荐省略, 如 repo_type 参数\n", "# 该参数用于指定仓库类型, 不指定时则默认认为仓库为 model 类型\n", "# 若要下载的仓库为 dataset 类型, 不指定 repo_type 参数时默认就把仓库类型当做 model, 最终导致找不到要下载的仓库\n", "\n", "\n", "### 2.4. 从 ModelScope 仓库导入 ###\n", "# 如果需要从 ModelScope 仓库下载模型, 可以使用 sd_scripts.repo.download_files_from_repo()\n", "# 使用方法和 **2.3. 从 HuggingFace 仓库导入** 部分的类似, 只需要指定 api_type=\"modelscope\" 来指定使用 ModelScope 的仓库\n", "# 使用参数:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"modelscope\", # 指定为 ModelScope 的仓库\n", "# local_dir=SD_MODEL_PATH, # 模型下载到本地的路径\n", "# repo_id=\"usename/repo_id\", # ModelScope 仓库 ID\n", "# repo_type=\"model\", # (可选参数) ModelScope 仓库种类 (model / dataset / space)\n", "# folder=\"path/in/repo/file.safetensors\", # (可选参数) 文件在 ModelScope 仓库中的路径\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 例如要从 stabilityai/stable-diffusion-xl-base-1.0 (类型为 model) 下载 sd_xl_base_1.0_0.9vae.safetensors\n", "# sd_scripts.dataset.download_files_from_repo(\n", "# api_type=\"modelscope\",\n", "# repo_id=\"stabilityai/stable-diffusion-xl-base-1.0\",\n", "# repo_type=\"model\",\n", "# folder=\"sd_xl_base_1.0_0.9vae.safetensors\",\n", "# local_dir=SD_MODEL_PATH,\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# 则上述的命令将会从 stabilityai/stable-diffusion-xl-base-1.0 下载 sd_xl_base_1.0_0.9vae.safetensors 模型\n", "# 并将模型保存到 SD_MODEL_PATH 中\n", "\n", "\n", "\n", "##########################################################################################\n", "\n", "\n", "##### 3. 关于训练集导入 #####\n", "\n", "# 该 Kaggle 训练脚本支持 4 种方式导入训练集, 如下:\n", "# 1. 使用 Kaggle Input 导入\n", "# 2. 使用训练集下载链接导入\n", "# 3. 从 HuggingFace 仓库导入\n", "# 4. 从 ModelScope 仓库导入\n", "\n", "\n", "### 3.1. 使用 Kaggle Input 导入 ###\n", "# 在 Kaggle 右侧面板中, 点击 Notebook -> Input -> Upload -> New Dataset, 从此处导入模型\n", "# 这将 KAGGLE_INPUT_PATH 内的文件复制到 INPUT_DATASET_PATH 指定的路径\n", "# 即将 /kaggle/input 中的所有文件复制到 /kaggle/dataset 中\n", "\n", "\n", "### 3.2. 使用训练集下载链接导入 ###\n", "# 如果将训练集压缩后保存在某个平台, 如 HuggingFace, ModelScope, 并且有下载链接\n", "# 可以使用 sd_scripts.download_archive_and_unpack() 函数下载训练集\n", "# 使用参数:\n", "# sd_scripts.download_archive_and_unpack(\n", "# url=\"download_url\", # 训练集压缩包的下载链接\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到本地的路径\n", "# name=\"filename.zip\", # (可选参数) 将数据集压缩包进行重命名\n", "# retry=RETRY, # (可选参数) 重试下载的次数\n", "# )\n", "# \n", "# 该函数在下载训练集压缩包完成后将解压到指定的本地路径\n", "# 压缩包格式仅支持 7z, zip, tar\n", "# \n", "# 下面是几个使用的例子:\n", "# 1.\n", "# sd_scripts.download_archive_and_unpack(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/data_1.7z\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/data_1.7z 下载训练集压缩包并解压到 INPUT_DATASET_PATH 中\n", "# \n", "# 2.\n", "# sd_scripts.download_archive_and_unpack(\n", "# url=\"https://modelscope.cn/models/user/repo/resolve/master/data_1.7z\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# name=\"training_dataset.7z\",\n", "# retry=RETRY,\n", "# )\n", "# 这将从 https://modelscope.cn/models/user/repo/resolve/master/data_1.7z 下载训练集压缩包并重命名成 training_dataset.7z\n", "# 再将 training_dataset.7z 中的文件解压到 INPUT_DATASET_PATH 中\n", "# \n", "# \n", "# 训练集的要求:\n", "# 需要将图片进行打标, 并调整训练集为指定的目结构, 例如:\n", "# Nachoneko\n", "# └── 1_nachoneko\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 0(8).txt\n", "# ├── 0(8).webp\n", "# ├── 001_2.png\n", "# ├── 001_2.txt\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# \n", "# 在 Nachoneko 文件夹新建一个文件夹, 格式为 <数字>_<名称>, 如 1_nachoneko, 前面的数字代表这部分的训练集的重复次数, 1_nachoneko 文件夹内则放图片和打标文件\n", "# \n", "# 训练集也可以分成多个部分组成, 例如:\n", "# Nachoneko\n", "# ├── 1_nachoneko\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 2_nachoneko\n", "# │ ├── 0(8).txt\n", "# │ ├── 0(8).webp\n", "# │ ├── 001_2.png\n", "# │ └── 001_2.txt\n", "# └── 4_nachoneko\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# \n", "# 处理好训练集并调整好目录结构后可以将 Nachoneko 文件夹进行压缩了, 使用 zip / 7z / tar 格式进行压缩\n", "# 例如将上述的训练集压缩成 Nachoneko.7z, 此时需要检查一下压缩后在压缩包的目录结果是否和原来的一致(有些压缩软件在部分情况下会破坏原来的目录结构)\n", "# 确认没有问题后将该训练集上传到网盘, 推荐使用 HuggingFace / ModelScope\n", "\n", "\n", "### 3.3. 从 HuggingFace 仓库导入 ###\n", "# 如果训练集保存在 HuggingFace, 可以使用 sd_scripts.repo.download_files_from_repo() 函数从 HuggingFace 下载数据集\n", "# 使用方法和 **2.3. 从 HuggingFace 仓库导入** 部分类似, 部分说明可参考那部分的内容\n", "# 使用格式:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\", # 指定为 HuggingFace 的仓库\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到哪个路径\n", "# repo_id=\"username/train_data\", # HuggingFace 仓库 ID\n", "# repo_type=\"dataset\", # (可选参数) HuggingFace 仓库的类型 (model / dataset / space)\n", "# folder=\"folder_in_repo\", # (可选参数) 指定要从 HuggingFace 仓库里下载哪个文件夹的内容\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 比如在 HuggingFace 的仓库为 username/train_data, 仓库类型为 dataset\n", "# 仓库的文件结构如下:\n", "# ├── Nachoneko\n", "# │ ├── 1_nachoneko\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# │ ├── 2_nachoneko\n", "# │ │ ├── 0(8).txt\n", "# │ │ ├── 0(8).webp\n", "# │ │ ├── 001_2.png\n", "# │ │ └── 001_2.txt\n", "# │ └── 4_nachoneko\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# │ ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# │ └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# └ aaaki\n", "# ├── 1_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 11.png\n", "# │   ├── 11.txt\n", "# │   ├── 12.png\n", "# │   └── 12.txt\n", "# └── 3_aaaki\n", "# ├── 14.png\n", "# ├── 14.txt\n", "# ├── 16.png\n", "# └── 16.txt\n", "#\n", "# 此时想要下载这个仓库中的 Nachoneko 文件夹的内容, 则下载命令为\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# folder=\"Nachoneko\",\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "# \n", "# 如果想下载整个仓库, 则移除 folder 参数, 命令修改为\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# retry=RETRY,\n", "# num_threads=DOWNLOAD_THREAD,\n", "# )\n", "\n", "\n", "\n", "# 4. 从 ModelScope 仓库导入\n", "# 如果训练集保存在 ModelScope, 可以使用 sd_scripts.repo.download_files_from_repo() 函数从 ModelScope 下载数据集\n", "# 使用方法可参考 **3.2. 使用训练集下载链接导入** 部分的说明\n", "# 使用格式:\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"modelscope\", # 指定为 ModelScope 的仓库\n", "# local_dir=INPUT_DATASET_PATH, # 下载数据集到哪个路径\n", "# repo_id=\"usename/repo_id\", # ModelScope 仓库 ID\n", "# repo_type=\"dataset\", # (可选参数) ModelScope 仓库的类型 (model / dataset / space)\n", "# folder=\"folder_in_repo\", # (可选参数) 指定要从 ModelScope 仓库里下载哪个文件夹的内容\n", "# retry=RETRY, # (可选参数) 重试下载的次数, 默认为 3\n", "# num_threads=DOWNLOAD_THREAD, # (可选参数) 下载线程\n", "# )\n", "# \n", "# 比如在 ModelScope 的仓库为 username/train_data, 仓库类型为 dataset\n", "# 仓库的文件结构如下:\n", "# ├── Nachoneko\n", "# │ ├── 1_nachoneko\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# │ │ ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# │ │ └── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# │ ├── 2_nachoneko\n", "# │ │ ├── 0(8).txt\n", "# │ │ ├── 0(8).webp\n", "# │ │ ├── 001_2.png\n", "# │ │ └── 001_2.txt\n", "# │ └── 4_nachoneko\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# │ ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# │ ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# │ └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# └ aaaki\n", "# ├── 1_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 11.png\n", "# │   ├── 11.txt\n", "# │   ├── 12.png\n", "# │   └── 12.txt\n", "# └── 3_aaaki\n", "# ├── 14.png\n", "# ├── 14.txt\n", "# ├── 16.png\n", "# └── 16.txt\n", "#\n", "# 此时想要下载这个仓库中的 Nachoneko 文件夹的内容, 则下载命令为\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"modelscope\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# folder=\"Nachoneko\",\n", "# )\n", "# \n", "# 如果想下载整个仓库, 则移除 folder 参数, 命令修改为\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"modelscope\",\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"username/train_data\",\n", "# repo_type=\"dataset\",\n", "# )\n", "\n", "\n", "\n", "# 下载训练集的技巧\n", "# 如果有个 character_aaaki 训练集上传到 HuggingFace 上时结构如下:\n", "# \n", "#\n", "# HuggingFace_Repo (licyk/sd_training_dataset)\n", "# ├── character_aaaki\n", "# │   ├── 1_aaaki\n", "# │   │   ├── 1.png\n", "# │   │   ├── 1.txt\n", "# │   │   ├── 3.png\n", "# │   │   └── 3.txt\n", "# │   └── 2_aaaki\n", "# │   ├── 4.png\n", "# │   └── 4.txt\n", "# ├── character_robin\n", "# │   └── 1_xxx\n", "# │   ├── 11.png\n", "# │   └── 11.txt\n", "# └── style_pvc\n", "# └── 5_aaa\n", "# ├── test.png\n", "# └── test.txt\n", "#\n", "# \n", "# 可能有时候不想为训练集中每个子训练集设置不同的重复次数,又不想上传的时候再多套一层文件夹,就把训练集结构调整成了下面的:\n", "# \n", "#\n", "# HuggingFace_Repo (licyk/sd_training_dataset)\n", "# ├── character_aaaki\n", "# │   ├── 1.png\n", "# │   ├── 1.txt\n", "# │   ├── 3.png\n", "# │   ├── 3.txt\n", "# │   ├── 4.png\n", "# │   └── 4.txt\n", "# ├── character_robin\n", "# │   └── 1_xxx\n", "# │   ├── 11.png\n", "# │   └── 11.txt\n", "# └── style_pvc\n", "# └── 5_aaa\n", "# ├── test.png\n", "# └── test.txt\n", "#\n", "# \n", "# 此时这个状态的训练集是缺少子训练集和重复次数的,如果直接使用 sd_scripts.repo.download_files_from_repo() 去下载训练集并用于训练将会导致报错\n", "# 不过可以自己再编写一个函数对 sd_scripts.repo.download_files_from_repo() 函数再次封装,自动加上子训练集并设置重复次数\n", "# \n", "#\n", "# def make_dataset(\n", "# local_dir: str | Path,\n", "# repo_id: str,\n", "# repo_type: str,\n", "# repeat: int,\n", "# folder: str,\n", "# ) -> None:\n", "# import os\n", "# import shutil\n", "# origin_dataset_path = os.path.join(local_dir, folder)\n", "# tmp_dataset_path = os.path.join(local_dir, f\"{repeat}_{folder}\")\n", "# new_dataset_path = os.path.join(origin_dataset_path, f\"{repeat}_{folder}\")\n", "# sd_scripts.repo.download_files_from_repo(\n", "# api_type=\"huggingface\",\n", "# local_dir=local_dir,\n", "# repo_id=repo_id,\n", "# repo_type=repo_type,\n", "# folder=folder,\n", "# )\n", "# if os.path.exists(origin_dataset_path):\n", "# logger.info(\"设置 %s 训练集的重复次数为 %s\", folder, repeat)\n", "# shutil.move(origin_dataset_path, tmp_dataset_path)\n", "# shutil.move(tmp_dataset_path, new_dataset_path)\n", "# else:\n", "# logger.error(\"从 %s 下载 %s 失败\", repo_id, folder)\n", "#\n", "# \n", "# 编写好后,可以去调用这个函数\n", "# \n", "#\n", "# make_dataset(\n", "# local_dir=INPUT_DATASET_PATH,\n", "# repo_id=\"licyk/sd_training_dataset\",\n", "# repo_type=\"dataset\",\n", "# repeat=3,\n", "# folder=\"character_aaaki\",\n", "# )\n", "#\n", "# \n", "# 该函数将会把 character_aaaki 训练集下载到 {INPUT_DATASET_PATH} 中,即 /kaggle/dataset\n", "# 文件夹名称为 character_aaaki,并且 character_aaaki 文件夹内继续创建了一个子文件夹作为子训练集,根据 repeat=3 将子训练集的重复次数设置为 3\n", "\n", "\n", "##########################################################################################\n", "logger.info(\"sd-scripts 安装完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 模型训练\n", "需自行编写命令,下方有可参考的例子 \n", "4. [[← 上一个单元](#安装环境)|[下一个单元 →](#模型上传)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "logger.info(\"进入 sd-scripts 目录\")\n", "os.chdir(SD_SCRIPTS_PATH)\n", "sd_scripts.display_model_and_dataset_dir(SD_MODEL_PATH, INPUT_DATASET_PATH, recursive=False)\n", "logger.info(\"使用 sd-scripts 进行模型训练\")\n", "##########################################################################################\n", "# 1.\n", "# 运行前需要根据自己的需求更改参数\n", "# \n", "# 训练参数的设置可参考:\n", "# https://rentry.org/59xed3\n", "# https://github.com/kohya-ss/sd-scripts?tab=readme-ov-file#links-to-usage-documentation\n", "# https://github.com/bmaltais/kohya_ss/wiki/LoRA-training-parameters\n", "# https://sd-moadel-doc.maozi.io\n", "# \n", "# \n", "# 2.\n", "# 下方被注释的代码选择后使用 Ctrl + / 取消注释\n", "# \n", "# \n", "# 3.\n", "# 训练使用的底模会被下载到 SD_MODEL_PATH, 即 /kaggle/sd-models\n", "# 填写底模路径时一般可以通过 --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/base_model.safetensors\" 指定\n", "# 如果需要外挂 VAE 模型可以通过 --vae=\"{SD_MODEL_PATH}/vae.safetensors\" 指定\n", "# \n", "# 通过 Kaggle Inout 导入的训练集保存在 KAGGLE_INPUT_PATH, 即 /kaggle/input, 运行该笔记时将会把训练集复制进 INPUT_DATASET_PATH, 即 /kaggle/dataset\n", "# 该路径可通过 INPUT_DATASET_PATH 调整\n", "# 如果使用 sd_scripts.dataset.get_dataset() 函数下载训练集, 数据集一般会解压到 INPUT_DATASET_PATH, 这取决于函数第一个参数传入的路径\n", "# 训练集的路径通常要这种结构\n", "# $ tree /kaggle\n", "# kaggle\n", "# └── dataset\n", "# └── Nachoneko\n", "# └── 1_gan_cheng\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2019 winter 麗.txt\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).png\n", "# ├── [メロンブックス (よろず)]Melonbooks Girls Collection 2020 spring 彩 (オリジナル).txt\n", "# ├── 0(8).txt\n", "# ├── 0(8).webp\n", "# ├── 001_2.png\n", "# ├── 001_2.txt\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.png\n", "# ├── 0b1c8893-c9aa-49e5-8769-f90c4b6866f5.txt\n", "# ├── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.png\n", "# └── 0d5149dd-3bc1-484f-8c1e-a1b94bab3be5.txt\n", "# 4 directories, 12 files\n", "# 在填写训练集路径时, 应使用 --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\"\n", "# \n", "# 模型保存的路径通常用 --output_dir=\"{OUTPUT_PATH}\" 指定, 如 --output_dir=\"{OUTPUT_PATH}/Nachoneko\", OUTPUT_PATH 默认设置为 /kaggle/working/model\n", "# 在 Kaggle 的 Output 中可以看到保存的模型, 前提是使用 Kaggle 的 Save Version 运行 Kaggle\n", "# OUTPUT_PATH 也指定了保存模型到 HuggingFace / ModelScope 的功能的上传路径\n", "# \n", "# --output_name 用于指定保存的模型名字, 如 --output_name=\"Nachoneko\"\n", "# \n", "# \n", "# 4.\n", "# Kaggle 的实例最长可运行 12 h, 要注意训练时长不要超过 12 h, 否则将导致训练被意外中断, 并且最后的模型保存功能将不会得到运行\n", "# 如果需要在模型被保存后立即上传到 HuggingFace 进行保存, 可使用启动参数为 sd-scripts 设置自动保存, 具体可阅读 sd-scripts 的帮助信息\n", "# 使用 python train_network.py -h 命令可查询可使用的启动参数, 命令中的 train_network.py 可替换成 sdxl_train_network.py 等\n", "# \n", "# \n", "# 5.\n", "# 训练命令的开头为英文的感叹号, 也就是 !, 后面就是 Shell Script 风格的命令\n", "# 每行的最后为反斜杠用于换行, 也就是用 \\ 来换行, 并且反斜杠的后面不允许有其他符号, 比如空格等\n", "# 训练命令的每一行之间不能有任何换行空出来, 最后一行不需要反斜杠, 因为最后一行的下一行已经没有训练参数\n", "# \n", "# \n", "# 6.\n", "# 如果训练参数是 toml 格式的, 比如从 Akegarasu/lora-scripts 训练器复制来的训练参数\n", "# 可以转换成对应的训练命令中的参数\n", "# 下面列举几种转换例子:\n", "# \n", "# (1)\n", "# toml 格式:\n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# 训练命令格式:\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# \n", "# (2)\n", "# toml 格式:\n", "# unet_lr = 0.0001\n", "# 训练命令格式:\n", "# --unet_lr=0.0001\n", "# \n", "# (3)\n", "# toml 格式:\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# 训练命令格式:\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=full \\\n", "# \n", "# (4)\n", "# toml 格式:\n", "# enable_bucket = true\n", "# 训练命令格式:\n", "# --enable_bucket\n", "# \n", "# (5)\n", "# toml 格式:\n", "# lowram = false\n", "# 训练命令格式:\n", "# 无对应的训练命令, 也就是不需要填, 因为这个参数的值为 false, 也就是无对应的参数, 如果值为 true, 则对应训练命令中的 --lowram\n", "# \n", "# 可以根据这个例子去转换 toml 格式的训练参数成训练命令的格式\n", "# \n", "# \n", "# 7.\n", "# 如果需要 toml 格式的配置文件来配置训练参数可以使用下面的代码来保存 toml 格式的训练参数\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# 这里使用 toml 格式编写训练参数, \n", "# 还可以结合 Python F-Strings 的用法使用前面配置好的变量\n", "# Python F-Strings 的说明: https://docs.python.org/zh-cn/3.13/reference/lexical_analysis.html#f-strings\n", "# toml 的语法可参考: https://toml.io/cn/v1.0.0\n", "# 下面展示训练命令里参数对应的 toml 格式转换\n", "# \n", "# \n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# 对应训练命令中的 --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# \n", "# unet_lr = 0.0001\n", "# 对应训练命令中的 --unet_lr=0.0001\n", "# \n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# 对应下面训练命令中的\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=full \\\n", "# \n", "# enable_bucket = true\n", "# 对应训练命令中的 --enable_bucket\n", "# \n", "# lowram = false\n", "# 这个参数的值为 false, 也就是无对应的参数, 如果值为 true, 则对应训练命令中的 --lowram\n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# \n", "# 使用上面的代码将会把训练参数的 toml 配置文件保存在 toml_file_path 路径中, 也就是 {WORKSPACE}/train_config.toml, 即 /kaggle/train_config.toml\n", "# 而原来的训练命令无需再写上训练参数, 只需指定该训练配置文件的路径即可\n", "# 使用 --config_file=\"{WORKSPACE}/train_config.toml\" 来指定\n", "# \n", "# \n", "# 8. \n", "# 如果要查看 sd-script 的命令行参数, 可以加上 -h 后再运行, 此时 sd-script 将显示所有可用的参数\n", "# \n", "# \n", "# 9.\n", "# 下方提供了一些训练参数, 可以直接使用, 使用时取消注释后根据需求修改部分参数即可\n", "# \n", "# .,@@@@@@@@@]. ./@[`....`[\\\\. \n", "# //\\`.. . ...,\\@]. .,]]]/O@@@@@@@@\\]... .,]//............\\@` \n", "# .O`........ .......\\\\.]]@@@@@@@@[..........,[@@@@\\`.*/....=^............/@@` \n", "# .O........ .......@@/@@@/`..... . ,\\@\\....\\`............O@`@ \n", "# =^...`.... .O@@`......... .........\\@`...[`.,@`....,@^/.@^ \n", "# .OO`..\\.... =/..... ...... ..[@]....,\\@@]]]].@@]`..//..@=\\^ \n", "# @O/@`,............=O/...... ... .... ...\\\\.....,@@@`=\\@\\@@[...=O`/^. \n", "# @@\\.,@]..]]//[,/@^O=@............. .\\@^...........,@`.....\\@@/*\\o*O@\\.=/.@` \n", "# ,@/O`...[OOO`.,@O,\\/....././\\^.... ..@O` ..\\`.......=\\.....=\\\\@@@@@/\\@@// \n", "# ,@`\\].......O^o,/.....@`/=^.....,\\...,@^ ...=\\... =\\.....,@,@@@@[/@@@/ \n", "# ..,\\@\\]]]]O/@.*@.....=^/\\^......=@....\\O..^..@@`.. ..\\@.....,@.\\@@\\[[O` \n", "# .*=@@\\@@^.O^...../o^O.......O=^...=@..@..\\.\\\\. . @@`....,@.\\@@@@` \n", "# . ..=@O^=@`,@ .....@@=`......=^.O....@..@^.=^.=@.....=@@.....,\\.\\@@@@. \n", "# .,@@`,O@./^.....=@O/......./^.O... \\`.=^.=^..=@... O=\\.....=^.\\@@@@`. \n", "# ./@`.=^@=@......=@O`....@,/@@.=^...=^.=^.=^.[[\\@....=^\\^.....@@.\\@@@@` \n", "# .,@^. @^O/@......=@O.]O`OO.=`\\^.....,^.=@.=^....=@...=\\.O.....@^\\`@@/` \n", "# =@ .=@..@^ .....=@/.../@^,/.=@......* =@.=^.....=\\..=@`=^....=^ \\/\\ \n", "# /^..=@.,@^ /`...=@.../O@.O...@........O=^=` ,`...@^.=@\\=^..] =@..@O`. \n", "# ,@...@/.=@. @^...=@../@\\@/OOO.=^......=^,O@[.]]@\\]/@ =^@`O..O.=@^ =@^ \n", "# =^...@@.=@..O\\....@ //.O@O@@]..@....../^.OO@@@[[@@@@\\/^@^O .O.=@@ .@^ \n", "# @^..=@@.,@.=^@....@@\\@@@[[[[[[[\\^@^..,/..O..,@@@\\..=@@//OO..O./^@. =@ \n", "# @...=^@^.@.=^=^...=@@`/@@@@@`...*O\\..@...[.=@`,@@@`.@`=^@=`.O.@.@. =@. \n", "# @^..O.@^ \\^=@,\\..=@@ @\\,@@/@@`..=^..@`.....@@\\@@/@@...O.@=^,O=^.@^./@ \n", "# @@..O.=@.,\\=@^O..=`\\/@^/@@OO@^..,`,O`.. .. @@/@@\\@@..=`=@../^O..@^/O^ \n", "# .=@^ @..@`=@o@@=^..,.O@@/@@oO@........... ...@^.\\/@..=^=@/ =@O. .@\\@`. \n", "# .@@.@^.@^@^\\@@O^..=^,O@@*................. .......=^/@@^=@@^ .=@`. \n", "# .=O@O^,@^=^.\\@^o..=/\\,\\ ..... .... ..... ...]@O`=@O/@@^ =@ \n", "# .=O@O/^==@@`O@O^.=@.\\`\\`.... . ........ ......//@.@`. =^ \n", "# ,O@@^.O..\\@@@^.=@...[O@`.. . ........ .....//.@@,\\ .@^ \n", "# .@/@@@]../@@^..@@\\........ ..,/`=@/@`.....,@^..=^ =` .=@. \n", "# =/..O... @^=\\. O@@@@\\....... ...//.,@..@O].,/@`=\\..=@..@..@^ \n", "# ,/..O....=/=/@ .=@@@@@@@@].....//.,O@`.//.@@@@@..@^..@`.=\\/O`. \n", "# ,@../`....O=/.@...@@@@@@@@@@@@@/../\\@..//.=@@@@\\. @@..=\\..@^/. \n", "# ,@`.=`....=@/..@...\\@@@@@@@@.. O..,@/..=@ .O=@@@^. @/@..@^..@`. \n", "# ,@`.=^....,@/..=O^..,@@.[@@@@,@]@../^..=@../^=@@@...@.,\\.=@`..@` \n", "# ,@..=/. .@/...O=@...@@....,@@...,[@\\.,@`..@..@@/..,@..,\\.@@...@.. \n", "# @`.,/.....@/...=`O@^..,@...../`.......,\\@]..@..O@\\]]/\\`..,\\,@^..,@` \n", "# =^..@...../@...,^/O@@...=@`...@............\\@` /`,\\,@`.=\\.,\\@=@`..,@. \n", "# ,@../`....@\\`/@``,`]/@^...O,\\/\\@]..............\\\\..=@`\\\\ ,@@@@@@@....@`. \n", "# O`.=^....@^O@^.@@@@@@@\\....\\@^=@@@@@\\] ..........,@`\\@\\.@`=@@@@@@\\....@`.. \n", "# =/..O...,@O/@^.@@@@@@@@@`...=/.@@@@@@@@@@@].........,@@/@`,@/@@@@O\\^....@`.. \n", "# /^.O.../@O^@^./@@@@@@@@@\\...@`=@@@@@@@@@@@@@\\.......@`=\\//@`,@@@@@.@`....\\`... \n", "# .,@.=^../`@@\\@.=@@@@@@@@@@@^.=@.@@@@@@@@@@@@@@@@@`...@` =\\\\==`@`\\@@@^.@.....\\^... \n", "# ../\\^,@.,/.=@/=/,@@@@@@@@@@@@\\ @^=@@@@@@@@@@@@@@@@@@@]@@@@@@@@@o\\@`.@@\\.,@.....\\\\... \n", "# =/.@^@`/`..@@^@^=@@@@@@@@@@@@@\\@.@@@@@@@@@@@@@@@@@@@@@@@@O@@@@@\\/.,/.@@\\.,@.....,@`.. \n", "# ,O`.,@=@/...=@@.@^O@@@@@@@@@@@@@@^=@@@@@@@@@@@@@@@@@@@@@@@@@@O@@@^ /@@.,@/@`.@`.....\\\\... \n", "# ..=^...=^@^....@OO,@^/@@@@@@@@@@@@\\@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\@@@@@`=\\.\\^.\\`.....,@`.. \n", "# \n", "# 炼丹就不存在什么万能参数的, 可能下面给的参数里有的参数训练出来的效果很好, 有的效果就一般\n", "# 训练参数还看训练集呢, 同一套参数在不同训练集上效果都不一样, 可能好可能坏 (唉, 被这训练参数折磨过好多次)\n", "# 虽然说一直用同个效果不错的参数可能不会出现特别坏的结果吧\n", "# 还有好的训练集远比好的训练参数更重要\n", "# 好的训练集真的, 真的, 真的非常重要\n", "# 再好的参数, 训练集烂也救不回来\n", "# \n", "# \n", "# 10.\n", "# 建议先改改训练集路径的参数就开始训练, 跑通训练了再试着改其他参数\n", "# 还有我编写的训练参数不一定是最好的, 所以需要自己去摸索这些训练参数是什么作用的, 再去修改\n", "# 其实有些参数我自己也调不明白, 但是很多时候跑出来效果还不错\n", "# 为什么效果好, 分からない, 这东西像个黑盒, 有时候就觉得神奇呢\n", "##########################################################################################\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数在 animagine-xl-3.1.safetensors 测试, 大概在 30 ~ 40 Epoch 有比较好的效果 (在 36 Epoch 出好效果的概率比较高)\n", "#\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animagine-xl-3.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=50 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"cosine_with_restarts\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --lr_scheduler_num_cycles=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "#\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"cosine_with_restarts\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --lr_scheduler_num_cycles=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset,可以调整训练网络的大小\n", "# 该值默认为 full,而使用 attn-mlp 可以得到更小的 LoRA 但几乎不影响 LoRA 效果\n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"attn-mlp\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset,可以调整训练网络的大小\n", "# 该值默认为 full,而使用 attn-mlp 可以得到更小的 LoRA 但几乎不影响 LoRA 效果\n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 当 weight_decay 设置为 0.05 时, 大概在 38 Epoch 有比较好的效果\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"attn-mlp\" \\\n", "# --optimizer_args \\\n", "# weight_decay=0.1 \\\n", "# betas=\"0.9,0.95\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# (自己在用的)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"full\" \\\n", "# --optimizer_args \\\n", "# weight_decay=0.05 \\\n", "# betas=\"0.9,0.95\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# (自己在用的)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好 (最好还是 full 吧, 其他的预设效果不是很好)\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# 测试的时候发现 --debiased_estimation_loss 对于训练效果的有些改善\n", "# 这里有个对比: https://licyk.netlify.app/2025/02/10/debiased_estimation_loss_in_stable_diffusion_model_training\n", "# 启用后能提高拟合速度和颜色表现吧, 画风的学习能学得更好\n", "# 但, 肢体崩坏率可能会有点提高, 不过有另一套参数去优化了一下这个问题, 貌似会好一点\n", "# 可能画风会弱化, 所以不是很确定哪个比较好用, 只能自己试了\n", "# debiased estimation loss 有个相关的论文可以看看: https://arxiv.org/abs/2310.08442\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"full\" \\\n", "# --optimizer_args \\\n", "# weight_decay=0.05 \\\n", "# betas=\"0.9,0.95\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --debiased_estimation_loss \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# (自己在用的)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好 (最好还是 full 吧, 其他的预设效果不是很好)\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# 测试的时候发现 --debiased_estimation_loss 对于训练效果的有些改善\n", "# 这里有个对比: https://licyk.netlify.app/2025/02/10/debiased_estimation_loss_in_stable_diffusion_model_training\n", "# 启用后能提高拟合速度和颜色表现吧, 画风的学习能学得更好\n", "# 但, 肢体崩坏率可能会有点提高, 不过有另一套参数去优化了一下这个问题, 貌似会好一点\n", "# 可能画风会弱化, 所以不是很确定哪个比较好用, 只能自己试了\n", "# debiased estimation loss 有个相关的论文可以看看: https://arxiv.org/abs/2310.08442\n", "# \n", "# 加上 v 预测参数进行训练, 提高模型对暗处和亮处的表现效果, 并且能让模型能够直出纯黑色背景, 画面也更干净\n", "# 相关的论文可以看看: https://arxiv.org/abs/2305.08891\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/noobaiXLNAIXL_vPred10Version.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"full\" \\\n", "# --optimizer_args \\\n", "# weight_decay=0.05 \\\n", "# betas=\"0.9,0.95\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --debiased_estimation_loss \\\n", "# --vae_batch_size=4 \\\n", "# --zero_terminal_snr \\\n", "# --v_parameterization \\\n", "# --scale_v_pred_loss_like_noise_pred \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好 (最好还是 full 吧, 其他的预设效果不是很好)\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# 测试的时候发现 --debiased_estimation_loss 对于训练效果的有些改善\n", "# 这里有个对比: https://licyk.netlify.app/2025/02/10/debiased_estimation_loss_in_stable_diffusion_model_training\n", "# 启用后能提高拟合速度和颜色表现吧, 画风的学习能学得更好\n", "# 把学习率调度器 constant_with_warmup 换成了cosine, 稍微缓解了一下拟合速度过快导致肢体崩坏率增大的问题\n", "# 如果学的效果不够好, 拟合度不够高, 可以适当增加 --max_train_epochs 的值或者提高训练集的重复次数\n", "# debiased estimation loss 有个相关的论文可以看看: https://arxiv.org/abs/2310.08442\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"cosine\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=\"full\" \\\n", "# --optimizer_args \\\n", "# weight_decay=0.05 \\\n", "# betas=\"0.9,0.95\" \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --debiased_estimation_loss \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 人物 LoRA, 使用多卡进行训练\n", "# 适合极少图或者单图训练集进行人物 LoRA 训练\n", "# 训练集使用打标器进行打标后, 要保留的人物的哪些特征, 就把对应的 Tag 删去, 触发词可加可不加\n", "# \n", "# 该参数使用 scale_weight_norms 降低过拟合程度, 进行训练时, 可在控制台输出看到 Average key norm 这个值\n", "# 通常测试 LoRA 时就测试 Average key norm 值在 0.5 ~ 0.9 之间的保存的 LoRA 模型\n", "# max_train_epochs 设置为 200, save_every_n_epochs 设置为 1 以为了更好的挑选最好的结果\n", "# \n", "# 可使用该方法训练一个人物 LoRA 模型用于生成人物的图片, 并将这些图片重新制作成训练集\n", "# 再使用不带 scale_weight_norms 的训练参数进行训练, 通过这种方式, 可以在图片极少的情况下得到比较好的 LoRA 模型\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=200 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --scale_weight_norms=1 \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用 rtx 4060 8g laptop 进行训练, 通过 fp8 降低显存占用\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# !python \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=3 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.0002 \\\n", "# --unet_lr=0.0002 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"AdamW8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --fp8_base\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "#\n", "# 这个参数是在 Illustrious-XL-v0.1.safetensors 模型上测出来的, 大概在 32 Epoch 左右有比较好的效果\n", "# 用 animagine-xl-3.1.safetensors 那套参数也有不错的效果, 只是学习率比这套低了点, 学得慢一点\n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 参数加上了 noise_offset, 可以提高暗处和亮处的表现, 一般使用设置成 0.05 ~ 0.1\n", "# 但 noise_offset 可能会导致画面泛白, 光影效果变差\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/Nachoneko\" \\\n", "# --output_name=\"Nachoneko_2\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/Nachoneko\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00012 \\\n", "# --unet_lr=0.00012 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --noise_offset=0.1 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 人物 LoRA, 使用多卡进行训练\n", "# 参数中使用了 --scale_weight_norms, 用于提高泛化性, 但可能会造成拟合度降低\n", "# 如果当训练人物 LoRA 的图片较多时, 可考虑删去该参数\n", "# 当训练人物 LoRA 的图片较少, 为了避免过拟合, 就可以考虑使用 --scale_weight_norms 降低过拟合概率\n", "#\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animagine-xl-3.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/robin\" \\\n", "# --output_name=\"robin_1\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/robin_1\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=50 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"cosine_with_restarts\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --lr_scheduler_num_cycles=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --scale_weight_norms=1 \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 人物 LoRA, 使用多卡进行训练\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animagine-xl-3.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/murasame_(senren)_3\" \\\n", "# --output_name=\"murasame_(senren)_10\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/murasame_(senren)_10\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=50 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --learning_rate=0.0001 \\\n", "# --unet_lr=0.0001 \\\n", "# --text_encoder_lr=0.00004 \\\n", "# --lr_scheduler=\"cosine_with_restarts\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --lr_scheduler_num_cycles=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --scale_weight_norms=1 \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用单卡进行训练 (Kaggle 的单 Tesla P100 性能不如双 Tesla T4, 建议使用双卡训练)\n", "# !python \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animagine-xl-3.1.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/rafa\" \\\n", "# --output_name=\"rafa_1\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/rafa\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"1024,1024\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=4096 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=50 \\\n", "# --train_batch_size=6 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00007 \\\n", "# --unet_lr=0.00007 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"cosine_with_restarts\" \\\n", "# --lr_warmup_steps=0 \\\n", "# --lr_scheduler_num_cycles=1 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 SD1.5 画风 LoRA, 使用双卡进行训练\n", "# 使用 NovelAI 1 模型进行训练\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animefull-final-pruned.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/vae-ft-mse-840000-ema-pruned.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/sunfish\" \\\n", "# --output_name=\"nai1-sunfish_5\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/nai1-sunfish_5\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"768,768\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=1024 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=12 \\\n", "# --gradient_checkpointing \\\n", "# --network_train_unet_only \\\n", "# --learning_rate=0.00024 \\\n", "# --unet_lr=0.00024 \\\n", "# --text_encoder_lr=0.00001 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "# 使用 lokr 算法训练 SD1.5 多画风(多概念) LoRA, 使用双卡进行训练\n", "# 使用 NovelAI 1 模型进行训练\n", "# \n", "# 在 SD1.5 中训练 Text Encoder 可以帮助模型更好的区分不同的画风(概念)\n", "# \n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/train_network.py\" \\\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/animefull-final-pruned.safetensors\" \\\n", "# --vae=\"{SD_MODEL_PATH}/vae-ft-mse-840000-ema-pruned.safetensors\" \\\n", "# --train_data_dir=\"{INPUT_DATASET_PATH}/sunfish\" \\\n", "# --output_name=\"nai1-sunfish_5\" \\\n", "# --output_dir=\"{OUTPUT_PATH}/nai1-sunfish_5\" \\\n", "# --wandb_run_name=\"Nachoneko\" \\\n", "# --log_tracker_name=\"lora-Nachoneko\" \\\n", "# --prior_loss_weight=1 \\\n", "# --resolution=\"768,768\" \\\n", "# --enable_bucket \\\n", "# --min_bucket_reso=256 \\\n", "# --max_bucket_reso=1024 \\\n", "# --bucket_reso_steps=64 \\\n", "# --save_model_as=\"safetensors\" \\\n", "# --save_precision=\"fp16\" \\\n", "# --save_every_n_epochs=1 \\\n", "# --max_train_epochs=40 \\\n", "# --train_batch_size=12 \\\n", "# --gradient_checkpointing \\\n", "# --learning_rate=0.00028 \\\n", "# --unet_lr=0.00028 \\\n", "# --text_encoder_lr=0.000015 \\\n", "# --lr_scheduler=\"constant_with_warmup\" \\\n", "# --lr_warmup_steps=100 \\\n", "# --optimizer_type=\"Lion8bit\" \\\n", "# --network_module=\"lycoris.kohya\" \\\n", "# --network_dim=100000 \\\n", "# --network_alpha=100000 \\\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# --log_with=\"{LOG_MODULE}\" \\\n", "# --logging_dir=\"{OUTPUT_PATH}/logs\" \\\n", "# --caption_extension=\".txt\" \\\n", "# --shuffle_caption \\\n", "# --keep_tokens=0 \\\n", "# --max_token_length=225 \\\n", "# --seed=1337 \\\n", "# --mixed_precision=\"fp16\" \\\n", "# --xformers \\\n", "# --cache_latents \\\n", "# --cache_latents_to_disk \\\n", "# --persistent_data_loader_workers \\\n", "# --vae_batch_size=4 \\\n", "# --full_fp16\n", "\n", "\n", "##########################################################################################\n", "# 下面是 toml 格式的训练命令, 根据上面的训练命令做了格式转换\n", "# 只弄了自己常用的训练参数, 其他的参照下面的例子来改吧\n", "# \n", "# toml 转换格式如下 (在最前面已经写过一次了, 再写一遍方便对照):\n", "# (1)\n", "# toml 格式:\n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# 训练命令格式:\n", "# --pretrained_model_name_or_path=\"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# \n", "# (2)\n", "# toml 格式:\n", "# unet_lr = 0.0001\n", "# 训练命令格式:\n", "# --unet_lr=0.0001\n", "# \n", "# (3)\n", "# toml 格式:\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# 训练命令格式:\n", "# --network_args \\\n", "# conv_dim=100000 \\\n", "# conv_alpha=100000 \\\n", "# algo=lokr \\\n", "# dropout=0 \\\n", "# factor=8 \\\n", "# train_norm=True \\\n", "# preset=full \\\n", "# \n", "# (4)\n", "# toml 格式:\n", "# enable_bucket = true\n", "# 训练命令格式:\n", "# --enable_bucket\n", "# \n", "# (5)\n", "# toml 格式:\n", "# lowram = false\n", "# 训练命令格式:\n", "# 无对应的训练命令, 也就是不需要填, 因为这个参数的值为 false, 也就是无对应的参数, 如果值为 true, 则对应训练命令中的 --lowram\n", "##########################################################################################\n", "\n", "\n", "\n", "# (自己在用的, toml 格式的版本)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# vae = \"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\"\n", "# train_data_dir = \"{INPUT_DATASET_PATH}/Nachoneko\"\n", "# output_name = \"Nachoneko_2\"\n", "# output_dir = \"{OUTPUT_PATH}/Nachoneko\"\n", "# wandb_run_name = \"Nachoneko\"\n", "# log_tracker_name = \"lora-Nachoneko\"\n", "# prior_loss_weight = 1\n", "# resolution = \"1024,1024\"\n", "# enable_bucket = true\n", "# min_bucket_reso = 256\n", "# max_bucket_reso = 4096\n", "# bucket_reso_steps = 64\n", "# save_model_as = \"safetensors\"\n", "# save_precision = \"fp16\"\n", "# save_every_n_epochs = 1\n", "# max_train_epochs = 40\n", "# train_batch_size = 6\n", "# gradient_checkpointing = true\n", "# network_train_unet_only = true\n", "# learning_rate = 0.0001\n", "# unet_lr = 0.0001\n", "# text_encoder_lr = 0.00001\n", "# lr_scheduler = \"constant_with_warmup\"\n", "# lr_warmup_steps = 100\n", "# optimizer_type = \"Lion8bit\"\n", "# network_module = \"lycoris.kohya\"\n", "# network_dim = 100000\n", "# network_alpha = 100000\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# optimizer_args = [\n", "# \"weight_decay=0.05\",\n", "# \"betas=0.9,0.95\",\n", "# ]\n", "# log_with = \"{LOG_MODULE}\"\n", "# logging_dir = \"{OUTPUT_PATH}/logs\"\n", "# caption_extension = \".txt\"\n", "# shuffle_caption = true\n", "# keep_tokens = 0\n", "# max_token_length = 225\n", "# seed = 1337\n", "# mixed_precision = \"fp16\"\n", "# xformers = true\n", "# cache_latents = true\n", "# cache_latents_to_disk = true\n", "# persistent_data_loader_workers = true\n", "# vae_batch_size = 4\n", "# full_fp16 = true\n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --config_file=\"{toml_file_path}\"\n", "\n", "\n", "# (自己在用的, toml 格式的版本)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好 (最好还是 full 吧, 其他的预设效果不是很好)\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# 测试的时候发现 --debiased_estimation_loss 对于训练效果的有些改善\n", "# 这里有个对比: https://licyk.netlify.app/2025/02/10/debiased_estimation_loss_in_stable_diffusion_model_training\n", "# 启用后能提高拟合速度和颜色表现吧, 画风的学习能学得更好\n", "# 但, 肢体崩坏率可能会有点提高, 不过有另一套参数去优化了一下这个问题, 貌似会好一点\n", "# 可能画风会弱化, 所以不是很确定哪个比较好用, 只能自己试了\n", "# debiased estimation loss 有个相关的论文可以看看: https://arxiv.org/abs/2310.08442\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/Illustrious-XL-v0.1.safetensors\"\n", "# vae = \"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\"\n", "# train_data_dir = \"{INPUT_DATASET_PATH}/Nachoneko\"\n", "# output_name = \"Nachoneko_2\"\n", "# output_dir = \"{OUTPUT_PATH}/Nachoneko\"\n", "# wandb_run_name = \"Nachoneko\"\n", "# log_tracker_name = \"lora-Nachoneko\"\n", "# prior_loss_weight = 1\n", "# resolution = \"1024,1024\"\n", "# enable_bucket = true\n", "# min_bucket_reso = 256\n", "# max_bucket_reso = 4096\n", "# bucket_reso_steps = 64\n", "# save_model_as = \"safetensors\"\n", "# save_precision = \"fp16\"\n", "# save_every_n_epochs = 1\n", "# max_train_epochs = 40\n", "# train_batch_size = 6\n", "# gradient_checkpointing = true\n", "# network_train_unet_only = true\n", "# learning_rate = 0.0001\n", "# unet_lr = 0.0001\n", "# text_encoder_lr = 0.00001\n", "# lr_scheduler = \"constant_with_warmup\"\n", "# lr_warmup_steps = 100\n", "# optimizer_type = \"Lion8bit\"\n", "# network_module = \"lycoris.kohya\"\n", "# network_dim = 100000\n", "# network_alpha = 100000\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# optimizer_args = [\n", "# \"weight_decay=0.05\",\n", "# \"betas=0.9,0.95\",\n", "# ]\n", "# log_with = \"{LOG_MODULE}\"\n", "# logging_dir = \"{OUTPUT_PATH}/logs\"\n", "# caption_extension = \".txt\"\n", "# shuffle_caption = true\n", "# keep_tokens = 0\n", "# max_token_length = 225\n", "# seed = 1337\n", "# mixed_precision = \"fp16\"\n", "# xformers = true\n", "# cache_latents = true\n", "# cache_latents_to_disk = true\n", "# persistent_data_loader_workers = true\n", "# debiased_estimation_loss = true\n", "# vae_batch_size = 4\n", "# full_fp16 = true\n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --config_file=\"{toml_file_path}\"\n", "\n", "\n", "# (自己在用的, toml 格式的版本)\n", "# 使用 lokr 算法训练 XL 画风 LoRA, 使用多卡进行训练\n", "# 该参数也可以用于人物 LoRA 训练\n", "# \n", "# 在训练多画风 LoRA 或者人物 LoRA 时, 通常会打上触发词\n", "# 当使用了 --network_train_unet_only 后, Text Encoder 虽然不会训练, 但并不影响将触发词训练进 LoRA 模型中\n", "# 并且不训练 Text Encoder 避免 Text Encoder 被炼烂(Text Encoder 比较容易被炼烂)\n", "# \n", "# 学习率调度器从 cosine_with_restarts 换成 constant_with_warmup, 此时学习率靠优化器(Lion8bit)进行调度\n", "# 拟合速度会更快\n", "# constant_with_warmup 用在大规模的训练上比较好, 但用在小规模训练也有不错的效果\n", "# 如果训练集的图比较少, 重复的图较多, 重复次数较高, 可能容易造成过拟合\n", "# \n", "# 在 --network_args 设置了 preset, 可以调整训练网络的大小\n", "# 该值默认为 full, 如果使用 attn-mlp 可以得到更小的 LoRA, 但对于难学的概念使用 full 效果会更好 (最好还是 full 吧, 其他的预设效果不是很好)\n", "# \n", "# 可用的预设可阅读文档: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Preset.md\n", "# 该预设也可以自行编写并指定, 编写例子可查看: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/example_configs/preset_configs/example.toml\n", "# \n", "# 使用 --optimizer_args 设置 weight_decay 和 betas, 更高的 weight_decay 可以降低拟合程度, 减少过拟合\n", "# 如果拟合程度不够高, 可以提高 --max_train_epochs 的值, 或者适当降低 weight_decay 的值, 可自行测试\n", "# 较小的训练集适合使用较小的值, 如 0.05, 较大的训练集适合用 0.1\n", "# 大概 34 Epoch 会有比较好的效果吧, 不过不好说, 看训练集\n", "# 自己测的时候大概在 26~40 Epoch 之间会出现好结果, 测试了很多炉基本都在这个区间里, 但也不排除意外情况 (训练参数这东西好麻烦啊, 苦い)\n", "# \n", "# 测试的时候发现 --debiased_estimation_loss 对于训练效果的有些改善\n", "# 这里有个对比: https://licyk.netlify.app/2025/02/10/debiased_estimation_loss_in_stable_diffusion_model_training\n", "# 启用后能提高拟合速度和颜色表现吧, 画风的学习能学得更好\n", "# 但, 肢体崩坏率可能会有点提高, 不过有另一套参数去优化了一下这个问题, 貌似会好一点\n", "# 可能画风会弱化, 所以不是很确定哪个比较好用, 只能自己试了\n", "# debiased estimation loss 有个相关的论文可以看看: https://arxiv.org/abs/2310.08442\n", "# \n", "# 加上 v 预测参数进行训练, 提高模型对暗处和亮处的表现效果, 并且能让模型能够直出纯黑色背景, 画面也更干净\n", "# 相关的论文可以看看: https://arxiv.org/abs/2305.08891\n", "# \n", "# toml_file_path = os.path.join(WORKSPACE, \"train_config.toml\")\n", "# toml_content = f\"\"\"\n", "# pretrained_model_name_or_path = \"{SD_MODEL_PATH}/noobaiXLNAIXL_vPred10Version.safetensors\"\n", "# vae = \"{SD_MODEL_PATH}/sdxl_fp16_fix_vae.safetensors\"\n", "# train_data_dir = \"{INPUT_DATASET_PATH}/Nachoneko\"\n", "# output_name = \"Nachoneko_2\"\n", "# output_dir = \"{OUTPUT_PATH}/Nachoneko\"\n", "# wandb_run_name = \"Nachoneko\"\n", "# log_tracker_name = \"lora-Nachoneko\"\n", "# prior_loss_weight = 1\n", "# resolution = \"1024,1024\"\n", "# enable_bucket = true\n", "# min_bucket_reso = 256\n", "# max_bucket_reso = 4096\n", "# bucket_reso_steps = 64\n", "# save_model_as = \"safetensors\"\n", "# save_precision = \"fp16\"\n", "# save_every_n_epochs = 1\n", "# max_train_epochs = 40\n", "# train_batch_size = 6\n", "# gradient_checkpointing = true\n", "# network_train_unet_only = true\n", "# learning_rate = 0.0001\n", "# unet_lr = 0.0001\n", "# text_encoder_lr = 0.00001\n", "# lr_scheduler = \"constant_with_warmup\"\n", "# lr_warmup_steps = 100\n", "# optimizer_type = \"Lion8bit\"\n", "# network_module = \"lycoris.kohya\"\n", "# network_dim = 100000\n", "# network_alpha = 100000\n", "# network_args = [\n", "# \"conv_dim=100000\",\n", "# \"conv_alpha=100000\",\n", "# \"algo=lokr\",\n", "# \"dropout=0\",\n", "# \"factor=8\",\n", "# \"train_norm=True\",\n", "# \"preset=full\",\n", "# ]\n", "# optimizer_args = [\n", "# \"weight_decay=0.05\",\n", "# \"betas=0.9,0.95\",\n", "# ]\n", "# log_with = \"{LOG_MODULE}\"\n", "# logging_dir = \"{OUTPUT_PATH}/logs\"\n", "# caption_extension = \".txt\"\n", "# shuffle_caption = true\n", "# keep_tokens = 0\n", "# max_token_length = 225\n", "# seed = 1337\n", "# mixed_precision = \"fp16\"\n", "# xformers = true\n", "# cache_latents = true\n", "# cache_latents_to_disk = true\n", "# persistent_data_loader_workers = true\n", "# debiased_estimation_loss = true\n", "# vae_batch_size = 4\n", "# zero_terminal_snr = true\n", "# v_parameterization = true\n", "# scale_v_pred_loss_like_noise_pred = true\n", "# full_fp16 = true\n", "# \"\"\".strip()\n", "# if not os.path.exists(os.path.dirname(toml_file_path)):\n", "# os.makedirs(toml_file_path, exist_ok=True)\n", "# with open(toml_file_path, \"w\", encoding=\"utf8\") as file:\n", "# file.write(toml_content)\n", "# !python -m accelerate.commands.launch \\\n", "# --num_cpu_threads_per_process=1 \\\n", "# --multi_gpu \\\n", "# --num_processes=2 \\\n", "# \"{SD_SCRIPTS_PATH}/sdxl_train_network.py\" \\\n", "# --config_file=\"{toml_file_path}\"\n", "\n", "\n", "\n", "##########################################################################################\n", "os.chdir(WORKSPACE)\n", "logger.info(\"离开 sd-scripts 目录\")\n", "logger.info(\"模型训练结束\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 模型上传\n", "通常不需要修改该单元内容,如果需要修改参数,建议通过上方的参数配置单元进行修改 \n", "5. [← 上一个单元](#模型训练)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 模型上传到 HuggingFace / ModelScope, 通常不需要修改, 修改参数建议通过上方的参数配置单元进行修改\n", "\n", "# 使用 HuggingFace 上传模型\n", "if USE_HF_TO_SAVE_MODEL:\n", " logger.info(\"使用 HuggingFace 保存模型\")\n", " sd_scripts.repo.upload_files_to_repo(**HF_REPO_UPLOADER_PARAMS)\n", "\n", "# 使用 ModelScope 上传模型\n", "if USE_MS_TO_SAVE_MODEL:\n", " logger.info(\"使用 ModelScope 保存模型\")\n", " sd_scripts.repo.upload_files_to_repo(**MS_REPO_UPLOADER_PARAMS)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 2 }
2301_81996401/sd-webui-all-in-one
notebook/sd_scripts_kaggle.ipynb
Jupyter Notebook
agpl-3.0
152,344
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xlyptNJ2ICnN" }, "source": [ "# SD Trainer Colab\n", "Colab NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Colab](https://colab.research.google.com) 部署 [SD-Trainer](https://github.com/Akegarasu/lora-scripts) / [Kohya GUI](https://github.com/bmaltais/kohya_ss) 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "Colab 链接:<a href=\"https://colab.research.google.com/github/licyk/sd-webui-all-in-one/blob/main/sd_trainer_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式,并安装 SD Trainer。默认设置下已启用`配置环境完成后立即启动 SD Trainer`选项,则安装完成后将直接启动 SD Trainer,并显示访问地址。\n", "2. 下载模型:下载可选列表中的模型(可选)。\n", "3. 自定义模型下载:使用链接下载模型(可选)。\n", "4. 扩展下载:使用链接下载扩展(可选)。\n", "5. 启动 SD Trainer:启动 SD Trainer,并显示访问地址。\n", "\n", "\n", "## 使用\n", "1. 在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择`GPU T4`或者其他 GPU。\n", "2. `环境配置`单元中的选项通常不需要修改,保持默认即可。如需切换其他 SD Trainer 分支,可修改`环境配置`单元中的`SD Trainer 分支预设`选项。\n", "3. 运行`环境配置`单元,默认设置下已启用`配置环境完成后立即启动 SD Trainer`选项,则环境配置完成后立即启动 SD Trainer,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 SD Trainer,SD Trainer 的访问地址可在日志中查看。\n", "4. 如果未启用`配置环境完成后立即启动 SD Trainer`选项,需要运行`启动 SD Trainer`单元,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 SD Trainer,SD Trainer 的访问地址可在日志中查看。\n", "5. 提示词查询工具:[SD 绘画提示词查询](https://licyk.github.io/t/tag)\n", "\n", "\n", "## 提示\n", "1. Colab 在关机后将会清除所有数据,所以每次重新启动时必须运行`环境配置`单元才能运行`启动 SD Trainer`单元。\n", "2. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "3. [Zrok](https://zrok.io) 内网穿透在使用前需要填写 Zrok Token, 可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取。\n", "4. 每次启动 Colab 后必须运行`环境配置`单元,才能运行`启动 SD Trainer`单元启动 SD Trainer。\n", "5. 其他功能有自定义模型下载等功能,根据自己的需求进行使用。\n", "6. 运行`启动 SD Trainer`时将弹出 Google Drive 访问授权提示,根据提示进行授权。授权后,使用 SD Trainer 生成的图片将保存在 Google Drive 的`sd_trainer_output`文件夹中。\n", "7. 在`额外挂载目录设置`中可以挂载一些额外目录,如 LoRA 模型目录,挂载后的目录可在 Google Drive 的`sd_trainer_output`文件夹中查看和修改。可通过该功能在 Google Drive 上传模型并在 SD Trainer 中使用。\n", "8. 默认挂载以下目录到 Google Drive,可在 Google Drive 的`sd_trainer_output`文件夹中上传和修改文件:`outputs`, `output`, `config`, `train`, `logs`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "VjYy0F2gZIPR" }, "outputs": [], "source": [ "#@title 👇 环境配置\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, SDTrainerManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "\n", "#######################################################\n", "\n", "# SD Trainer 分支预设\n", "SD_TRAINER_BRANCH_PRESET_DICT = {\n", " \"Akegarasu/SD-Trainer 分支\": {\n", " \"url\": \"https://github.com/Akegarasu/lora-scripts\",\n", " \"requirements\": \"requirements.txt\",\n", " \"launch_args\": \"--skip-prepare-onnxruntime\",\n", " \"webui_port\": 28000,\n", " },\n", " \"bmaltais/Kohya GUI 分支\": {\n", " \"url\": \"https://github.com/bmaltais/kohya_ss\",\n", " \"requirements\": \"requirements.txt\",\n", " \"launch_args\": \"--inbrowser --language zh-CN --noverify\",\n", " \"webui_port\": 7860,\n", " },\n", "}\n", "\n", "#@markdown ## SD Trainer 核心配置选项\n", "#@markdown - SD Trainer 分支预设:\n", "SD_TRAINER_BRANCH_PRESET = \"Akegarasu/SD-Trainer 分支\" # @param [\"Akegarasu/SD-Trainer 分支\", \"bmaltais/Kohya GUI 分支\"]\n", "#@markdown - SD Trainer 分支仓库地址(可选,不填则使用分支预设值):\n", "SD_TRAINER_REPO_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - SD Trainer 依赖表名(可选,不填则使用分支预设值):\n", "SD_TRAINER_REQUIREMENTS_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - SD Trainer 启动参数(可选,不填则使用分支预设值):\n", "SD_TRAINER_LAUNCH_ARGS_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - SD Trainer 访问端口(可选,不填则使用分支预设值):\n", "SD_TRAINER_WEBUI_PORT_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## PyTorch 组件版本选项:\n", "#@markdown - PyTorch:\n", "PYTORCH_VER = \"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126\" #@param {type:\"string\"}\n", "#@markdown - xFormers:\n", "XFORMERS_VER = \"xformers==0.0.32.post2\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 包管理器选项:\n", "#@markdown - 使用 uv 作为 Python 包管理器\n", "USE_UV = True #@param {type:\"boolean\"}\n", "#@markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" #@param {type:\"string\"}\n", "#@markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"\" #@param {type:\"string\"}\n", "#@markdown - PyTorch 镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 内网穿透选项:\n", "#@markdown - 使用 remote.moe 内网穿透\n", "USE_REMOTE_MOE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 localhost.run 内网穿透\n", "USE_LOCALHOST_RUN = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 pinggy.io 内网穿透\n", "USE_PINGGY_IO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 CloudFlare 内网穿透\n", "USE_CLOUDFLARE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Gradio 内网穿透\n", "USE_GRADIO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Ngrok 内网穿透(需填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取)\n", "USE_NGROK = True #@param {type:\"boolean\"}\n", "#@markdown - Ngrok Token\n", "NGROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown - 使用 Zrok 内网穿透(需填写 Zrok Token,可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取)\n", "USE_ZROK = True #@param {type:\"boolean\"}\n", "#@markdown - Zrok Token\n", "ZROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 快速启动选项:\n", "#@markdown - 配置环境完成后立即启动 SD Trainer(并挂载 Google Drive)\n", "QUICK_LAUNCH = True #@param {type:\"boolean\"}\n", "#@markdown - 不重复配置环境(当重复运行环境配置时将不会再进行安装)\n", "NO_REPEAT_CONFIGURE_ENV = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "#@markdown ## 其他选项:\n", "#@markdown - 清理无用日志\n", "CLEAR_LOG = True #@param {type:\"boolean\"}\n", "#@markdown - 检查可用 GPU\n", "CHECK_AVALIABLE_GPU = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# 预设参数处理\n", "SD_TRAINER_REPO = SD_TRAINER_REPO_OPT or SD_TRAINER_BRANCH_PRESET_DICT.get(SD_TRAINER_BRANCH_PRESET).get(\"url\")\n", "SD_TRAINER_REQUIREMENTS = SD_TRAINER_REQUIREMENTS_OPT or SD_TRAINER_BRANCH_PRESET_DICT.get(SD_TRAINER_BRANCH_PRESET).get(\"requirements\")\n", "SD_TRAINER_LAUNCH_ARGS = SD_TRAINER_LAUNCH_ARGS_OPT or SD_TRAINER_BRANCH_PRESET_DICT.get(SD_TRAINER_BRANCH_PRESET).get(\"launch_args\")\n", "SD_TRAINER_WEBUI_PORT = SD_TRAINER_WEBUI_PORT_OPT or SD_TRAINER_BRANCH_PRESET_DICT.get(SD_TRAINER_BRANCH_PRESET).get(\"webui_port\")\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 模型设置, 在安装时将会下载选择的模型:\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = True # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = True # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\"})\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 额外挂载目录设置, 在启动时挂载目录到 Google Drive:\n", "EXTRA_LINK_DIR = []\n", "\n", "#@markdown - config_files 目录\n", "link_config_files_dir = False # @param {type:\"boolean\"}\n", "#@markdown - dataset 目录\n", "link_dataset_dir = False # @param {type:\"boolean\"}\n", "#@markdown - localizations 目录\n", "link_localizations_dir = False # @param {type:\"boolean\"}\n", "#@markdown - presets 目录\n", "link_presets_dir = False # @param {type:\"boolean\"}\n", "\n", "\n", "link_config_files_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"config_files\"})\n", "link_dataset_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"dataset\"})\n", "link_localizations_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"localizations\"})\n", "link_presets_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"presets\"})\n", "\n", "##############################################################################\n", "\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": PYTORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Colab 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"sd_trainer_repo\": SD_TRAINER_REPO or None,\n", " \"sd_trainer_requirements\": SD_TRAINER_REQUIREMENTS or None,\n", " \"model_list\": SD_MODEL,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"huggingface_token\": None,\n", " \"modelscope_token\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "\n", "TUNNEL_PARAMS = {\n", " \"use_ngrok\": USE_NGROK,\n", " \"ngrok_token\": NGROK_TOKEN or None,\n", " \"use_cloudflare\": USE_CLOUDFLARE,\n", " \"use_remote_moe\": USE_REMOTE_MOE,\n", " \"use_localhost_run\": USE_LOCALHOST_RUN,\n", " \"use_gradio\": USE_GRADIO,\n", " \"use_pinggy_io\": USE_PINGGY_IO,\n", " \"use_zrok\": USE_ZROK,\n", " \"zrok_token\": ZROK_TOKEN or None,\n", " \"message\": \"##### SD Trainer 访问地址 #####\",\n", "}\n", "\n", "SD_TRAINER_PATH = \"/content/sd-trainer\"\n", "try:\n", " _ = sd_trainer_manager_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " sd_trainer = SDTrainerManager(os.path.dirname(SD_TRAINER_PATH), os.path.basename(SD_TRAINER_PATH), port=int(SD_TRAINER_WEBUI_PORT))\n", " sd_trainer_manager_has_init = True\n", "\n", "try:\n", " _ = sd_trainer_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " sd_trainer_has_init = False\n", "\n", "if NO_REPEAT_CONFIGURE_ENV:\n", " if not sd_trainer_has_init:\n", " sd_trainer.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " sd_trainer_has_init = True\n", " CLEAR_LOG and sd_trainer.clear_up()\n", " logger.info(\"SD Trainer 运行环境配置完成\")\n", " else:\n", " logger.info(\"检测到不重复配置环境已启用, 并且在当前 Colab 实例中已配置 SD Trainer 运行环境, 不再重复配置 SD Trainer 运行环境\")\n", " logger.info(\"如需在当前 Colab 实例中重新配置 SD Trainer 运行环境, 请在快速启动选项中取消不重复配置环境功能\")\n", "else:\n", " sd_trainer.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " CLEAR_LOG and sd_trainer.clear_up()\n", " logger.info(\"SD Trainer 运行环境配置完成\")\n", "\n", "LAUNCH_CMD = sd_trainer.get_launch_command(SD_TRAINER_LAUNCH_ARGS)\n", "\n", "if QUICK_LAUNCH:\n", " logger.info(\"启动 SD Trainer 中\")\n", " os.chdir(SD_TRAINER_PATH)\n", " sd_trainer.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=SD_TRAINER_REQUIREMENTS,\n", " )\n", " sd_trainer.mount_drive(EXTRA_LINK_DIR)\n", " sd_trainer.tun.start_tunnel(**TUNNEL_PARAMS)\n", " logger.info(\"SD Trainer 启动参数: %s\", SD_TRAINER_LAUNCH_ARGS)\n", " !{LAUNCH_CMD}\n", " os.chdir(JUPYTER_ROOT_PATH)\n", " CLEAR_LOG and sd_trainer.clear_up()\n", " logger.info(\"已关闭 SD Trainer\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "ZWnei0cZwWzK" }, "outputs": [], "source": [ "#@title 👇 下载模型(可选)\n", "\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 SD Trainer\")\n", "\n", "#@markdown 选择下载的模型:\n", "##############################\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = False # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = False # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\"})\n", "\n", "##############################\n", "logger.info(\"下载模型中\")\n", "sd_trainer.get_sd_model_from_list(SD_MODEL)\n", "CLEAR_LOG and sd_trainer.clear_up()\n", "logger.info(\"模型下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MbpZVvRMPIAC" }, "outputs": [], "source": [ "#@title 👇 自定义模型下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 SD Trainer\")\n", "\n", "#@markdown ### 填写模型的下载链接:\n", "model_url = \"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "#@markdown ### 填写模型的名称(包括后缀名):\n", "model_name = \"CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "\n", "sd_trainer.get_sd_model(\n", " url=model_url,\n", " filename=model_name or None,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "cLB6sKhErcG8" }, "outputs": [], "source": [ "#@title 👇 启动 SD Trainer\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 SD Trainer\")\n", "\n", "logger.info(\"启动 SD Trainer\")\n", "os.chdir(SD_TRAINER_PATH)\n", "sd_trainer.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=SD_TRAINER_REQUIREMENTS,\n", ")\n", "sd_trainer.mount_drive(EXTRA_LINK_DIR)\n", "sd_trainer.tun.start_tunnel(**TUNNEL_PARAMS)\n", "logger.info(\"SD Trainer 启动参数: %s\", SD_TRAINER_LAUNCH_ARGS)\n", "!{LAUNCH_CMD}\n", "os.chdir(JUPYTER_ROOT_PATH)\n", "CLEAR_LOG and sd_trainer.clear_up()\n", "logger.info(\"已关闭 SD Trainer\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "AVWoNIEhXy5o" }, "outputs": [], "source": [ "#@title 👇 文件下载工具\n", "\n", "#@markdown ### 填写文件的下载链接:\n", "url = \"\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存路径:\n", "file_path = \"/content\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存名称 (可选):\n", "filename = \"\" #@param {type:\"string\"}\n", "\n", "sd_trainer.download_file(\n", " url=url,\n", " path=file_path or None,\n", " save_name=filename or None,\n", ")\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/sd_trainer_colab.ipynb
Jupyter Notebook
agpl-3.0
46,797
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SD Trainer Kaggle\n", "#### Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "一个在 [Kaggle](https://www.kaggle.com) 部署 [SD Trainer](https://github.com/Akegarasu/lora-scripts) 的 Jupyter Notebook。\n", "\n", "使用时请按顺序运行笔记单元。\n", "\n", "## 提示:\n", "1. 可以将训练数据上传至`kaggle/input`文件夹,运行安装时将会把训练数据放置`/kaggle/data`文件夹中。\n", "2. 训练需要的模型将下载至`/kaggle/lora-scripts/sd-models`文件夹中。\n", "3. 推荐将训练输出的模型路径改为`kaggle/working`文件夹,方便下载。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 参数配置" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "INIT_CONFIG = 1\n", "\n", "# 消息格式输出\n", "def echo(*args):\n", " for i in args:\n", " print(f\":: {i}\")\n", "\n", "\n", "# 将/kaggle/input中的文件复制到/kaggle/data\n", "def cp_data():\n", " import os\n", " if not os.path.exists(\"/kaggle/data\"):\n", " !mkdir -p /kaggle/data\n", " data_list = os.listdir(\"/kaggle/input\")\n", " for i in data_list:\n", " file_path = os.path.join(\"/kaggle/input\", i)\n", " !cp -rf {file_path} /kaggle/data\n", "\n", "\n", "# ARIA2\n", "class ARIA2:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载器\n", " def aria2(self, url, path, filename):\n", " import os\n", " if not os.path.exists(path + \"/\" + filename):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " if os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " echo(f\"{filename} 文件已存在,路径: {path}/{filename}\")\n", "\n", "\n", " # 大模型下载\n", " def get_sd_model(self, url, filename):\n", " pass\n", "\n", "\n", " # vae模型下载\n", " def get_vae_model(self, url, filename):\n", " pass\n", "\n", "\n", "# GIT\n", "class GIT:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 检测要克隆的项目是否存在于指定路径\n", " def exists(self, addr=None, path=None, name=None):\n", " import os\n", " if addr is not None:\n", " if path is None and name is None:\n", " path = os.getcwd() + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " elif path is None and name is not None:\n", " path = os.getcwd() + \"/\" + name\n", " elif path is not None and name is None:\n", " path = os.path.normpath(path) + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", "\n", " if os.path.exists(path):\n", " return True\n", " else:\n", " return False\n", "\n", "\n", " # 克隆项目\n", " def clone(self, addr, path=None, name=None):\n", " import os\n", " repo = addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " if not self.exists(addr, path, name):\n", " echo(f\"开始下载 {repo}\")\n", " if path is None and name is None:\n", " path = os.getcwd()\n", " name = repo\n", " elif path is not None and name is None:\n", " name = repo\n", " elif path is None and name is not None:\n", " path = os.getcwd()\n", " !git clone {addr} \"{path}/{name}\" --recurse-submodules\n", " else:\n", " echo(f\"{repo} 已存在\")\n", "\n", "\n", "\n", "# TUNNEL\n", "class TUNNEL:\n", " LOCALHOST_RUN = \"localhost.run\"\n", " REMOTE_MOE = \"remote.moe\"\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", " PORT = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder, port) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", " self.PORT = port\n", "\n", "\n", " # ngrok内网穿透\n", " def ngrok(self, ngrok_token: str):\n", " from pyngrok import conf, ngrok\n", " conf.get_default().auth_token = ngrok_token\n", " conf.get_default().monitor_thread = False\n", " port = self.PORT\n", " ssh_tunnels = ngrok.get_tunnels(conf.get_default())\n", " if len(ssh_tunnels) == 0:\n", " ssh_tunnel = ngrok.connect(port, bind_tls=True)\n", " return ssh_tunnel.public_url\n", " else:\n", " return ssh_tunnels[0].public_url\n", "\n", "\n", " # cloudflare内网穿透\n", " def cloudflare(self):\n", " from pycloudflared import try_cloudflare\n", " port = self.PORT\n", " urls = try_cloudflare(port).tunnel\n", " return urls\n", "\n", "\n", " from typing import Union\n", " from pathlib import Path\n", "\n", " # 生成ssh密钥\n", " def gen_key(self, path: Union[str, Path]) -> None:\n", " import subprocess\n", " import shlex\n", " from pathlib import Path\n", " path = Path(path)\n", " arg_string = f'ssh-keygen -t rsa -b 4096 -N \"\" -q -f {path.as_posix()}'\n", " args = shlex.split(arg_string)\n", " subprocess.run(args, check=True)\n", " path.chmod(0o600)\n", "\n", "\n", " # ssh内网穿透\n", " def ssh_tunnel(self, host: str) -> None:\n", " import subprocess\n", " import atexit\n", " import shlex\n", " import re\n", " import os\n", " from pathlib import Path\n", " from tempfile import TemporaryDirectory\n", "\n", " ssh_name = \"id_rsa\"\n", " ssh_path = Path(self.WORKSPACE) / ssh_name\n", " port = self.PORT\n", "\n", " tmp = None\n", " if not ssh_path.exists():\n", " try:\n", " self.gen_key(ssh_path)\n", " # write permission error or etc\n", " except subprocess.CalledProcessError:\n", " tmp = TemporaryDirectory()\n", " ssh_path = Path(tmp.name) / ssh_name\n", " self.gen_key(ssh_path)\n", "\n", " arg_string = f\"ssh -R 80:127.0.0.1:{port} -o StrictHostKeyChecking=no -i {ssh_path.as_posix()} {host}\"\n", " args = shlex.split(arg_string)\n", "\n", " tunnel = subprocess.Popen(\n", " args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", " if tmp is not None:\n", " atexit.register(tmp.cleanup)\n", "\n", " tunnel_url = \"\"\n", " LOCALHOST_RUN = self.LOCALHOST_RUN\n", " lines = 27 if host == LOCALHOST_RUN else 5\n", " localhostrun_pattern = re.compile(r\"(?P<url>https?://\\S+\\.lhr\\.life)\")\n", " remotemoe_pattern = re.compile(r\"(?P<url>https?://\\S+\\.remote\\.moe)\")\n", " pattern = localhostrun_pattern if host == LOCALHOST_RUN else remotemoe_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", "\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " if lines == 27:\n", " os.environ['LOCALHOST_RUN'] = tunnel_url\n", " return tunnel_url\n", " else:\n", " os.environ['REMOTE_MOE'] = tunnel_url\n", " return tunnel_url\n", " # break\n", " else:\n", " echo(f\"启动 {host} 内网穿透失败\")\n", "\n", "\n", " # localhost.run穿透\n", " def localhost_run(self):\n", " urls = self.ssh_tunnel(self.LOCALHOST_RUN)\n", " return urls\n", "\n", "\n", " # remote.moe内网穿透\n", " def remote_moe(self):\n", " urls = self.ssh_tunnel(self.REMOTE_MOE)\n", " return urls\n", "\n", "\n", " # gradio内网穿透\n", " def gradio(self):\n", " import subprocess\n", " import shlex\n", " import atexit\n", " import re\n", " port = self.PORT\n", " cmd = f\"gradio-tunneling --port {port}\"\n", " cmd = shlex.split(cmd)\n", " tunnel = subprocess.Popen(\n", " cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", "\n", " tunnel_url = \"\"\n", " lines = 5\n", " gradio_pattern = re.compile(r\"(?P<url>https?://\\S+\\.gradio\\.live)\")\n", " pattern = gradio_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " return tunnel_url\n", " else:\n", " echo(f\"启动 Gradio 内网穿透失败\")\n", "\n", "\n", " # 启动内网穿透\n", " def start(self, ngrok=False, ngrok_token=None, cloudflare=False, remote_moe=False, localhost_run=False, gradio=False):\n", " if cloudflare is True or ngrok is True or ngrok_token is not None or remote_moe is True or localhost_run is True or gradio is True:\n", " echo(\"启动内网穿透\")\n", "\n", " if cloudflare is True:\n", " cloudflare_url = self.cloudflare()\n", " else:\n", " cloudflare_url = None\n", "\n", " if ngrok is True and ngrok_token is not None:\n", " ngrok_url = self.ngrok(ngrok_token)\n", " else:\n", " ngrok_url = None\n", "\n", " if remote_moe is True:\n", " remote_moe_url = self.remote_moe()\n", " else:\n", " remote_moe_url = None\n", "\n", " if localhost_run is True:\n", " localhost_run_url = self.localhost_run()\n", " else:\n", " localhost_run_url = None\n", "\n", " if gradio is True:\n", " gradio_url = self.gradio()\n", " else:\n", " gradio_url = None\n", "\n", " echo(\"下方为访问地址\")\n", " print(\"==================================================================================\")\n", " echo(f\"CloudFlare: {cloudflare_url}\")\n", " echo(f\"Ngrok: {ngrok_url}\")\n", " echo(f\"remote.moe: {remote_moe_url}\")\n", " echo(f\"localhost_run: {localhost_run_url}\")\n", " echo(f\"Gradio: {gradio_url}\")\n", " print(\"==================================================================================\")\n", "\n", "\n", "\n", "# ENV\n", "class ENV:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 准备ipynb笔记自身功能的依赖\n", " def prepare_env_depend(self, use_mirror=True):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " echo(\"安装自身组件依赖\")\n", " !pip install pyngrok pycloudflared gradio-tunneling {pip_mirror}\n", " !apt update\n", " !apt install aria2 ssh google-perftools -y\n", "\n", "\n", " # 安装pytorch和xformers\n", " def prepare_torch(self, torch_ver, xformers_ver, use_mirror=False):\n", " arg = \"--no-deps\"\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " \n", " if torch_ver != \"\":\n", " echo(\"安装 PyTorch\")\n", " !pip install {torch_ver} {pip_mirror}\n", " if xformers_ver != \"\":\n", " echo(\"安装 xFormers\")\n", " !pip install {xformers_ver} {pip_mirror} {arg}\n", " \n", "\n", " # 安装requirements.txt依赖\n", " def install_requirements(self, path, use_mirror=False):\n", " import os\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " if os.path.exists(path):\n", " echo(\"安装依赖\")\n", " !pip install -r \"{path}\" {pip_mirror}\n", " else:\n", " echo(\"依赖文件路径为空\")\n", "\n", "\n", " # python软件包安装\n", " # 可使用的操作:\n", " # 安装: install -> install\n", " # 仅安装: install_single -> install --no-deps\n", " # 强制重装: force_install -> install --force-reinstall\n", " # 仅强制重装: force_install_single -> install --force-reinstall --no-deps\n", " # 更新: update -> install --upgrade\n", " # 卸载: uninstall -y\n", " def py_pkg_manager(self, pkg, type=None, use_mirror=False):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " if type == \"install\":\n", " func = \"install\"\n", " args = \"\"\n", " elif type == \"install_single\":\n", " func = \"install\"\n", " args = \"--no-deps\"\n", " elif type == \"force_install\":\n", " func = \"install\"\n", " args = \"--force-reinstall\"\n", " elif type == \"force_install_single\":\n", " func = \"install\"\n", " args = \"install --force-reinstall --no-deps\"\n", " elif type == \"update\":\n", " func = \"install\"\n", " args = \"--upgrade\"\n", " elif type == \"uninstall\":\n", " func = \"uninstall\"\n", " args = \"-y\"\n", " pip_mirror = \"\"\n", " else:\n", " echo(f\"未知操作: {type}\")\n", " return\n", " echo(f\"执行操作: pip {func} {pkg} {args} {pip_mirror}\")\n", " !pip {func} {pkg} {args} {pip_mirror}\n", "\n", "\n", " # 配置内存优化\n", " def tcmalloc(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " os.environ[\"LD_PRELOAD\"] = \"/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4\"\n", "\n", "\n", "\n", "# MANAGER\n", "class MANAGER:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 清理ipynb笔记的输出\n", " def clear_up(self, opt):\n", " from IPython.display import clear_output\n", " clear_output(wait=opt)\n", "\n", "\n", " # 检查gpu是否可用\n", " def check_gpu(self):\n", " echo(\"检测 GPU 是否可用\")\n", " import tensorflow as tf\n", " echo(f\"TensorFlow 版本: {tf.__version__}\")\n", " if tf.test.gpu_device_name():\n", " echo(\"GPU 可用\")\n", " else:\n", " echo(\"GPU 不可用\")\n", " raise Exception(\"\\n没有使用GPU,请在代码执行程序-更改运行时类型-设置为GPU!\\n如果不能使用GPU,建议更换账号!\")\n", "\n", "\n", " def select_list(self, data, name):\n", " # https://stackoverflow.com/questions/57219796/ipywidgets-dynamic-creation-of-checkboxes-and-selection-of-data\n", " # https://gist.github.com/MattJBritton/9dc26109acb4dfe17820cf72d82f1e6f\n", " import ipywidgets as widgets\n", " names = [] # 可选择的列表\n", " checkbox_objects = [] # 按钮对象\n", " for key in data:\n", " value = key[1]\n", " key = key[0].split(\"/\").pop()\n", " if value == 1:\n", " select = True\n", " else:\n", " select = False\n", " checkbox_objects.append(widgets.Checkbox(value=select, description=key, )) # 扩展按钮列表\n", " names.append(key)\n", "\n", " arg_dict = {names[i]: checkbox for i, checkbox in enumerate(checkbox_objects)}\n", "\n", " ui = widgets.VBox(children=checkbox_objects) # 创建widget\n", "\n", " selected_data = []\n", " select_value = [] # 存储每个模型选择情况\n", " url_list = [] # 地址列表\n", " def select_data(**kwargs): # 每次点击按钮时都会执行\n", " selected_data.clear()\n", " select_value.clear()\n", " for key in kwargs:\n", " if kwargs[key] is True:\n", " selected_data.append(key)\n", " select_value.append(True)\n", " else:\n", " select_value.append(False)\n", "\n", " list = \"\"\n", " for i in selected_data: # 已选择的模型列表(模型名称)\n", " list = f\"{list}\\n- {i}\"\n", " print(f\"已选择列表: {list}\")\n", " j = 0\n", " url_list.clear()\n", " for i in select_value: # 返回的地址列表\n", " if i is True:\n", " url_list.append(data[j][0])\n", " j += 1\n", " \n", " out = widgets.interactive_output(select_data, arg_dict)\n", " ui.children = [*ui.children, out]\n", " ui = widgets.Accordion(children=[ui,], titles=(name,))\n", " #display(ui, out)\n", " display(ui)\n", " return url_list\n", "\n", "\n", "\n", "# SD_TRAINER\n", "class SD_TRAINER(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 28000)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install_kohya_requirements(self):\n", " import os\n", " os.chdir(WORKSPACE + \"/\" + WORKFOLDER + \"/sd-scripts\")\n", " self.install_requirements(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts/requirements.txt\")\n", " os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "\n", "\n", " def fix_lang(self):\n", " # ???\n", " import os\n", " os.environ[\"LANG\"] = \"zh_CN.UTF-8\"\n", "\n", "\n", " def fix_py_package(self, package, use_mirror):\n", " !rm -rf /opt/conda/lib/python3.10/site-packages/{package}\n", " !rm -rf /opt/conda/lib/python3.10/site-packages/{package}-*\n", " self.py_pkg_manager(package, \"uninstall\", use_mirror)\n", " self.py_pkg_manager(package, \"install\", use_mirror)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, vae, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/Akegarasu/lora-scripts\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " self.fix_py_package(\"aiohttp\", use_mirror)\n", " # self.install_kohya_requirements()\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"protobuf==3.20.0\", \"install\", use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.fix_lang()\n", " self.tcmalloc()\n", " self.get_sd_model_from_list(sd)\n", " self.get_vae_model_from_list(vae)\n", "\n", "#############################################################\n", "\n", "echo(\"初始化功能完成\")\n", "try:\n", " echo(\"尝试安装 ipywidgets 组件\")\n", " !pip install ipywidgets -qq\n", " from IPython.display import clear_output\n", " clear_output(wait=False)\n", " INIT_CONFIG = 1\n", "except:\n", " raise Exception(\"未初始化功能\")\n", "\n", "import ipywidgets as widgets\n", "\n", "\n", "WORKSPACE = \"/kaggle\"\n", "WORKFOLDER = \"lora-scripts\"\n", "USE_NGROK = False\n", "NGROK_TOKEN = \"\"\n", "USE_CLOUDFLARE = False\n", "USE_REMOTE_MOE = True\n", "USE_LOCALHOST_RUN = True\n", "USE_GRADIO_SHARE = False\n", "TORCH_VER = \"\"\n", "XFORMERS_VER = \"\"\n", "sd_model = [ # 前面为 Stable Diffusion 模型的下载链接, 后面为 1 时将会下载该模型\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cetusMix_Whalefall2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ex2K_sse2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/kohakuV5_rev2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinamix_meinaV11.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/oukaStar_10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/rabbit_v6.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/sweetSugarSyndrome_rev15.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/AnythingV5Ink_ink.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinapastel_v6Pastel.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/qteamixQ_omegaFp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/AnythingXL_xl.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/abyssorangeXLElse_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animaPencilXL_v200.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/nekorayxl_v06W3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/CounterfeitXL-V1.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", 0]\n", "]\n", "vae = [\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", 1]\n", "]\n", "\n", "manager = MANAGER(WORKSPACE, WORKFOLDER)\n", "\n", "torch_ver_state = widgets.Textarea(value=\"torch==2.3.0+cu121 torchvision==0.18.0+cu121 torchaudio==2.3.0+cu121\", placeholder=\"请填写 PyTorch 版本\", description=\"PyTorch 版本: \", disabled=False)\n", "xformers_ver_state = widgets.Textarea(value=\"xformers==0.0.26.post1\", placeholder=\"请填写 xFormers 版本\", description=\"xFormers 版本: \", disabled=False)\n", "use_ngrok_state = widgets.Checkbox(value=False, description=\"使用 Ngrok 内网穿透\", disabled=False)\n", "ngrok_token_state = widgets.Textarea(value=\"\", placeholder=\"请填写 Ngrok Token(可在 Ngrok 官网获取)\", description=\"Ngrok Token: \", disabled=False)\n", "use_cloudflare_state = widgets.Checkbox(value=False, description=\"使用 CloudFlare 内网穿透\", disabled=False)\n", "use_remote_moe_state = widgets.Checkbox(value=True, description=\"使用 remote.moe 内网穿透\", disabled=False)\n", "use_localhost_run_state = widgets.Checkbox(value=True, description=\"使用 localhost.run 内网穿透\", disabled=False)\n", "use_gradio_share_state = widgets.Checkbox(value=False, description=\"使用 Gradio 内网穿透\", disabled=False)\n", "# 自定义模型下载\n", "model_url = widgets.Textarea(value=\"\", placeholder=\"请填写模型下载链接\", description=\"模型链接: \", disabled=False) #@param {type:\"string\"}\n", "model_name = widgets.Textarea(value=\"\", placeholder=\"请填写模型名称,包括后缀名,例:kohaku-xl.safetensors\", description=\"模型名称: \", disabled=False) #@param {type:\"string\"}\n", "model_type = widgets.Dropdown(options=[(\"Stable Diffusion 模型(大模型)\", \"sd\"), (\"VAE 模型\", \"vae\")], value=\"sd\", description='模型种类: ')\n", "\n", "display(torch_ver_state, xformers_ver_state, use_ngrok_state, ngrok_token_state, use_cloudflare_state, use_remote_moe_state, use_localhost_run_state, use_gradio_share_state, model_name, model_url, model_type)\n", "\n", "\n", "sd_model_list = manager.select_list(sd_model,\"Stable Diffusion 模型\")\n", "vae_list = manager.select_list(vae, \"VAE 模型\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 安装" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG\n", " INIT_CONFIG_1 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数配置\\\"单元\")\n", "\n", "TORCH_VER = torch_ver_state.value\n", "XFORMERS_VER = xformers_ver_state.value\n", "USE_NGROK = use_ngrok_state.value\n", "NGROK_TOKEN = ngrok_token_state.value\n", "USE_CLOUDFLARE = use_cloudflare_state.value\n", "USE_REMOTE_MOE = use_remote_moe_state.value\n", "USE_LOCALHOST_RUN = use_localhost_run_state.value\n", "USE_GRADIO_SHARE = use_gradio_share_state.value\n", "USE_MIRROR = False\n", "\n", "sd_trainer = SD_TRAINER(WORKSPACE, WORKFOLDER)\n", "\n", "import os\n", "os.chdir(WORKSPACE)\n", "\n", "echo(f\"开始安装 SD Trainer\")\n", "sd_trainer.install(TORCH_VER, XFORMERS_VER, sd_model_list, vae_list, USE_MIRROR)\n", "if model_url.value != \"\" and model_name.value != \"\":\n", " if model_type.value == \"sd\":\n", " sd_trainer.get_sd_model(model_url.value, model_name.value)\n", " elif model_type.value == \"vae\":\n", " sd_trainer.get_vae_model(model_url.value, model_name.value)\n", "cp_data()\n", "sd_trainer.clear_up(False)\n", "echo(f\"SD Trainer 安装完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 启动" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG_1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "echo(\"启动 SD Trainer 中\")\n", "sd_trainer.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", "!python \"{WORKSPACE}\"/lora-scripts/gui.py\n", "sd_trainer.clear_up(False)\n", "echo(\"SD Trainer 已关闭\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 2 }
2301_81996401/sd-webui-all-in-one
notebook/sd_trainer_kaggle.ipynb
Jupyter Notebook
agpl-3.0
35,447
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SD WebUI All In One\n", "#### Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是一个支持部署多种 WebUI 的 Jupyter Notebook,支持部署以下 WebUI:\n", "- 1、[Stable-Diffusion-WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui)\n", "- 2、[ComfyUI](https://github.com/comfyanonymous/ComfyUI)\n", "- 3、[InvokeAI](https://github.com/invoke-ai/InvokeAI)\n", "- 4、[Fooocus](https://github.com/lllyasviel/Fooocus)\n", "- 5、[lora-scripts](https://github.com/Akegarasu/lora-scripts)\n", "- 6、[kohya_ss](https://github.com/bmaltais/kohya_ss)\n", "\n", "使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "## 主要功能\n", "1. [功能初始化](#功能初始化):导入 SD WebUI All In One 所使用的功能\n", "2. [参数配置](#参数配置):配置安装参数、远程访问方式、模型 / 扩展选择(有以下选项:Stable Diffusion 模型、LoRA 模型、Embedding 模型、VAE 模型、VAE-approx 模型、放大模型、ControlNet 模型、SD WebUI 扩展、ComfyUI 扩展)。\n", "3. [应用参数配置](#应用参数配置):应用已设置的参数\n", "4. [安装](#安装):根据配置安装对应的 WebUI\n", "5. [启动](#启动):根据配置启动对应的 WebUI\n", "\n", "## 其他功能\n", "1. [自定义模型 / 扩展下载配置](#自定义模型扩展下载配置):设置要下载的模型 / 扩展参数\n", "2. [自定义模型 / 扩展下载](#自定义模型扩展下载):根据配置进行下载模型 / 扩展\n", "3. [更新](#更新):将已安装的 WebUI 进行更新\n", "\n", "## 提示\n", "1. 在参数配置界面,请填写工作区路径(根据使用的平台进行填写,如Kaggle 平台填写`/kaggle`,Colab 平台填写`/content`),选择要使用的 WebUI,根据自己的需求选择内网穿透方式(用于访问 WebUI 界面),再根据自己的需求选择模型和扩展。\n", "2. 已知 CloudFlare、Gradio 内网穿透会导致 [Kaggle](https://www.kaggle.com) 平台强制关机,在使用 [Kaggle](https://www.kaggle.com) 平台时请勿勾选这两个选项。\n", "3. 若使用 [Colab](https://colab.research.google.com) 平台,请注意该 Jupyter Notebook 无法在免费版的 Colab 账号中使用,运行前将会收到 Colab 的警告提示,强行运行将会导致 Colab 强制关机(如果 Colab 账号已付费订阅可直接使用该 Jupyter Notebook),可选择仓库中其他的 Jupyter Notebook(将 Colab 中禁止的 WebUI 移除了)。\n", "4. [Ngrok](https://ngrok.com) 内网穿透的稳定性高,使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "5. 在启动时将启动内网穿透,可在控制台输出中看到内网穿透地址,用于访问 WebUI 界面。\n", "6. 云平台可能存在 ipywidgets 显示 Bug 导致一些提示无法显示出来,主要在参数配置单元的模型 / 扩展选择中出现这种问题。\n", "7. 调整参数配置后必须运行一次应用参数配置。\n", "8. 在 Kaggle / 国内的云平台时,请勿生成违禁图片,否则这将导致账号被封禁!" ] }, { "cell_type": "markdown", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "source": [ "### 功能初始化\n", "1. [[下一个单元 →](#参数配置)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "INIT_CONFIG = 1\n", "\n", "# 消息格式输出\n", "def echo(*args):\n", " for i in args:\n", " print(f\":: {i}\")\n", "\n", "\n", "\n", "# ARIA2\n", "class ARIA2:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载器\n", " def aria2(self, url, path, filename):\n", " import os\n", " if not os.path.exists(path + \"/\" + filename):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " if os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " echo(f\"{filename} 文件已存在,路径: {path}/{filename}\")\n", "\n", "\n", " # 大模型下载\n", " def get_sd_model(self, url, filename):\n", " pass\n", "\n", "\n", " # lora下载\n", " def get_lora_model(self, url, filename):\n", " pass\n", "\n", "\n", " # 放大模型下载\n", " def get_upscale_model(self, url, filename):\n", " pass\n", "\n", "\n", " # embedding模型下载\n", " def get_embedding_model(self, url, filename):\n", " pass\n", "\n", "\n", " # controlnet模型下载\n", " def get_controlnet_model(self, url, filename):\n", " pass\n", "\n", "\n", " # vae模型下载\n", " def get_vae_model(self, url, filename):\n", " pass\n", "\n", "\n", " # vae-approx模型下载\n", " def get_vae_approx_model(self, url, filename):\n", " pass\n", "\n", "\n", " # 获取modelscope下载链接\n", " def get_modelscope_link(self, origin):\n", " user = origin.split(\"/\")[0]\n", " repo = origin.split(\"/\")[1]\n", " branch = origin.split(\"/\")[2]\n", " tmp = f\"{user}/{repo}/{branch}/\"\n", " file = origin.split(tmp).pop().replace(\"/\", \"%2F\")\n", " link = f\"https://modelscope.cn/api/v1/models/{user}/{repo}/repo?Revision={branch}&FilePath={file}\"\n", " return link\n", "\n", "\n", "\n", "# GIT\n", "class GIT:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 检测要克隆的项目是否存在于指定路径\n", " def exists(self, addr=None, path=None, name=None):\n", " import os\n", " if addr is not None:\n", " if path is None and name is None:\n", " path = os.getcwd() + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " elif path is None and name is not None:\n", " path = os.getcwd() + \"/\" + name\n", " elif path is not None and name is None:\n", " path = os.path.normpath(path) + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", "\n", " if os.path.exists(path):\n", " return True\n", " else:\n", " return False\n", "\n", "\n", " # 克隆项目\n", " def clone(self, addr, path=None, name=None):\n", " import os\n", " repo = addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " if not self.exists(addr, path, name):\n", " echo(f\"开始下载 {repo}\")\n", " if path is None and name is None:\n", " path = os.getcwd()\n", " name = repo\n", " elif path is not None and name is None:\n", " name = repo\n", " elif path is None and name is not None:\n", " path = os.getcwd()\n", " !git clone {addr} \"{path}/{name}\" --recurse-submodules\n", " else:\n", " echo(f\"{repo} 已存在\")\n", "\n", "\n", " # 拉取更新\n", " def pull(self, path):\n", " import os\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " echo(f\"更新 {repo} 中\")\n", " if self.is_git_pointer_offset(path=path):\n", " self.fix_pointer(path=path)\n", " !git -C \"{path}\" pull --recurse-submodules\n", " else:\n", " echo(f\"路径不存在\")\n", "\n", "\n", " # 切换到指定版本\n", " def checkout(self, path, commit=None):\n", " import os\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " if commit is not None:\n", " echo(f\"切换 {repo} 版本中\")\n", " !git -C \"{path}\" reset --hard {commit} --recurse-submodules\n", " else:\n", " echo(f\"未指定 {repo} 版本\")\n", " else:\n", " echo(\"路径不存在\")\n", "\n", "\n", " # 修复分支漂移\n", " def fix_pointer(self, path):\n", " import os\n", " import subprocess\n", " if self.exists(path=path):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " echo(f\"修复 {repo} 分支游离中\")\n", " !git -C \"{path}\" remote prune origin\n", " !git -C \"{path}\" submodule init\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" branch -a | grep /HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout\n", " print(result)\n", " branch = result.split(\"/\").pop()\n", " !git -C \"{path}\" checkout {branch} # 切换到主分支\n", " !git -C \"{path}\" reset --recurse-submodules --hard origin/{branch}\n", " !git -C \"{path}\" reset --recurse-submodules --hard HEAD\n", " !git -C \"{path}\" restore --recurse-submodules --source=HEAD :/\n", " else:\n", " echo(\"路径不存在\")\n", "\n", "\n", " # 检测分支是否漂移\n", " def is_git_pointer_offset(self, path):\n", " if self.exists(path=path):\n", " import subprocess\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result != 0:\n", " echo(\"检测到出现分支游离\")\n", " return True\n", " else:\n", " return False\n", "\n", "\n", " # 输出版本信息\n", " def git_show_ver(self, path):\n", " import subprocess\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result == 0:\n", " cmd1 = f\"git -C \\\"{path}\\\" rev-parse --short HEAD\"\n", " cmd2 = f\"git -C \\\"{path}\\\" show -s --format=\\\"%cd\\\" --date=format:\\\"%Y-%m-%d %H:%M:%S\\\"\"\n", " commit = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"refs/heads/\", \"\").replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " else:\n", " cmd1 = f\"git -C \\\"{path}\\\" rev-parse --short HEAD\"\n", " cmd2 = f\"git -C \\\"{path}\\\" show -s --format=\\\"%cd\\\" --date=format:\\\"%Y-%m-%d %H:%M:%S\\\"\"\n", " commit = subprocess.run(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" (分支游离)\"\n", " return path.split(\"/\").pop() + \": \" + commit\n", " else:\n", " return \"(非 Git 安装)\"\n", "\n", "\n", " def log(self, path):\n", " import subprocess\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result == 0:\n", " cmd = f\"git -C \\\"{path}\\\" log --all --date=short --pretty=format:\\\"%h %cd\\\" --date=format:\\\"%Y-%m-%d | %H:%M:%S\\\"\"\n", " return path.split(\"/\").pop() + \" 版本信息: \\n\" + subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout\n", " else:\n", " return path.split(\"/\").pop() + \" 非 Git 安装\"\n", "\n", "\n", " def test_github_mirror(self, mirror):\n", " import os\n", " import subprocess\n", " path = self.WORKSPACE + \"/empty\"\n", " for i in mirror:\n", " test_repo = i.replace(\"term_sd_git_user/term_sd_git_repo\",\"licyk/empty\")\n", " avaliable_mirror = i.replace(\"/term_sd_git_user/term_sd_git_repo\",\"\")\n", " mirror_url = i.replace(\"term_sd_git_user/term_sd_git_repo\",\"\")\n", " echo(f\"测试 Github 镜像源: {mirror_url}\")\n", " if os.path.exists(path):\n", " !rm -rf \"{path}\"\n", " result = subprocess.run(f\"git clone {test_repo} {path}\")\n", " if os.path.exists(path):\n", " !rm -rf \"{path}\"\n", " if result.returncode == 0:\n", " return avaliable_mirror\n", " return False\n", " \n", "\n", " def set_github_mirror(self, mirror):\n", " import os\n", " avaliable_mirror = self.test_github_mirror(mirror)\n", " git_config_path = self.WORKSPACE + \"/.gitconfig\"\n", " if avaliable_mirror is not False:\n", " echo(f\"设置 GIthub 镜像源: {avaliable_mirror}\")\n", " if os.path.exists(git_config_path):\n", " !rm -rf \"{git_config_path}\"\n", " os.environ[\"GIT_CONFIG_GLOBAL\"] = git_config_path\n", " !git config --global url.{avaliable_mirror}.insteadOf https://github.com\n", " else:\n", " echo(\"未找到可用 Github 镜像源, 取消设置 GIthub 镜像源\")\n", "\n", "\n", " def unset_github_mirror(self):\n", " import os\n", " if \"GIT_CONFIG_GLOBAL\" in os.environ:\n", " echo(\"删除 Github 镜像源配置\")\n", " os.unsetenv(\"GIT_CONFIG_GLOBAL\")\n", " else:\n", " echo(\"Github 镜像源未设置, 无需删除\")\n", "\n", "\n", "\n", "# TUNNEL\n", "class TUNNEL:\n", " LOCALHOST_RUN = \"localhost.run\"\n", " REMOTE_MOE = \"remote.moe\"\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", " PORT = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder, port) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", " self.PORT = port\n", "\n", "\n", " # ngrok内网穿透\n", " def ngrok(self, ngrok_token: str):\n", " from pyngrok import conf, ngrok\n", " conf.get_default().auth_token = ngrok_token\n", " conf.get_default().monitor_thread = False\n", " port = self.PORT\n", " ssh_tunnels = ngrok.get_tunnels(conf.get_default())\n", " if len(ssh_tunnels) == 0:\n", " ssh_tunnel = ngrok.connect(port, bind_tls=True)\n", " return ssh_tunnel.public_url\n", " else:\n", " return ssh_tunnels[0].public_url\n", "\n", "\n", " # cloudflare内网穿透\n", " def cloudflare(self):\n", " from pycloudflared import try_cloudflare\n", " port = self.PORT\n", " urls = try_cloudflare(port).tunnel\n", " return urls\n", "\n", "\n", " from typing import Union\n", " from pathlib import Path\n", "\n", " # 生成ssh密钥\n", " def gen_key(self, path: Union[str, Path]) -> None:\n", " import subprocess\n", " import shlex\n", " from pathlib import Path\n", " path = Path(path)\n", " arg_string = f'ssh-keygen -t rsa -b 4096 -N \"\" -q -f {path.as_posix()}'\n", " args = shlex.split(arg_string)\n", " subprocess.run(args, check=True)\n", " path.chmod(0o600)\n", "\n", "\n", " # ssh内网穿透\n", " def ssh_tunnel(self, host: str) -> None:\n", " import subprocess\n", " import atexit\n", " import shlex\n", " import re\n", " import os\n", " from pathlib import Path\n", " from tempfile import TemporaryDirectory\n", "\n", " ssh_name = \"id_rsa\"\n", " ssh_path = Path(self.WORKSPACE) / ssh_name\n", " port = self.PORT\n", "\n", " tmp = None\n", " if not ssh_path.exists():\n", " try:\n", " self.gen_key(ssh_path)\n", " # write permission error or etc\n", " except subprocess.CalledProcessError:\n", " tmp = TemporaryDirectory()\n", " ssh_path = Path(tmp.name) / ssh_name\n", " self.gen_key(ssh_path)\n", "\n", " arg_string = f\"ssh -R 80:127.0.0.1:{port} -o StrictHostKeyChecking=no -i {ssh_path.as_posix()} {host}\"\n", " args = shlex.split(arg_string)\n", "\n", " tunnel = subprocess.Popen(\n", " args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", " if tmp is not None:\n", " atexit.register(tmp.cleanup)\n", "\n", " tunnel_url = \"\"\n", " LOCALHOST_RUN = self.LOCALHOST_RUN\n", " lines = 27 if host == LOCALHOST_RUN else 5\n", " localhostrun_pattern = re.compile(r\"(?P<url>https?://\\S+\\.lhr\\.life)\")\n", " remotemoe_pattern = re.compile(r\"(?P<url>https?://\\S+\\.remote\\.moe)\")\n", " pattern = localhostrun_pattern if host == LOCALHOST_RUN else remotemoe_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", "\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " if lines == 27:\n", " os.environ['LOCALHOST_RUN'] = tunnel_url\n", " return tunnel_url\n", " else:\n", " os.environ['REMOTE_MOE'] = tunnel_url\n", " return tunnel_url\n", " # break\n", " else:\n", " echo(f\"启动 {host} 内网穿透失败\")\n", "\n", "\n", " # localhost.run穿透\n", " def localhost_run(self):\n", " urls = self.ssh_tunnel(self.LOCALHOST_RUN)\n", " return urls\n", "\n", "\n", " # remote.moe内网穿透\n", " def remote_moe(self):\n", " urls = self.ssh_tunnel(self.REMOTE_MOE)\n", " return urls\n", "\n", "\n", " # gradio内网穿透\n", " def gradio(self):\n", " import subprocess\n", " import shlex\n", " import atexit\n", " import re\n", " port = self.PORT\n", " cmd = f\"gradio-tunneling --port {port}\"\n", " cmd = shlex.split(cmd)\n", " tunnel = subprocess.Popen(\n", " cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", "\n", " tunnel_url = \"\"\n", " lines = 5\n", " gradio_pattern = re.compile(r\"(?P<url>https?://\\S+\\.gradio\\.live)\")\n", " pattern = gradio_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " return tunnel_url\n", " else:\n", " echo(f\"启动 Gradio 内网穿透失败\")\n", "\n", "\n", " # 启动内网穿透\n", " def start(self, ngrok=False, ngrok_token=None, cloudflare=False, remote_moe=False, localhost_run=False, gradio=False):\n", " if cloudflare is True or ngrok is True or ngrok_token is not None or remote_moe is True or localhost_run is True or gradio is True:\n", " echo(\"启动内网穿透\")\n", "\n", " if cloudflare is True:\n", " cloudflare_url = self.cloudflare()\n", " else:\n", " cloudflare_url = None\n", "\n", " if ngrok is True and ngrok_token is not None:\n", " ngrok_url = self.ngrok(ngrok_token)\n", " else:\n", " ngrok_url = None\n", "\n", " if remote_moe is True:\n", " remote_moe_url = self.remote_moe()\n", " else:\n", " remote_moe_url = None\n", "\n", " if localhost_run is True:\n", " localhost_run_url = self.localhost_run()\n", " else:\n", " localhost_run_url = None\n", "\n", " if gradio is True:\n", " gradio_url = self.gradio()\n", " else:\n", " gradio_url = None\n", "\n", " echo(\"下方为访问地址\")\n", " print(\"==================================================================================\")\n", " echo(f\"CloudFlare: {cloudflare_url}\")\n", " echo(f\"Ngrok: {ngrok_url}\")\n", " echo(f\"remote.moe: {remote_moe_url}\")\n", " echo(f\"localhost_run: {localhost_run_url}\")\n", " echo(f\"Gradio: {gradio_url}\")\n", " print(\"==================================================================================\")\n", "\n", "\n", "\n", "# ENV\n", "class ENV:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 准备ipynb笔记自身功能的依赖\n", " def prepare_env_depend(self, use_mirror=True):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " echo(\"安装自身组件依赖\")\n", " !pip install pyngrok pycloudflared gradio-tunneling {pip_mirror}\n", " !apt update\n", " !apt install aria2 ssh google-perftools -y\n", "\n", "\n", " # 安装pytorch和xformers\n", " def prepare_torch(self, torch_ver, xformers_ver, use_mirror=False):\n", " arg = \"--no-deps\"\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " \n", " if torch_ver != \"\":\n", " echo(\"安装 PyTorch\")\n", " !pip install {torch_ver} {pip_mirror}\n", " if xformers_ver != \"\":\n", " echo(\"安装 xFormers\")\n", " !pip install {xformers_ver} {pip_mirror} {arg}\n", " \n", "\n", " # 安装requirements.txt依赖\n", " def install_requirements(self, path, use_mirror=False):\n", " import os\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " if os.path.exists(path):\n", " echo(\"安装依赖\")\n", " !pip install -r \"{path}\" {pip_mirror}\n", " else:\n", " echo(\"依赖文件路径为空\")\n", "\n", "\n", " # python软件包安装\n", " # 可使用的操作:\n", " # 安装: install -> install\n", " # 仅安装: install_single -> install --no-deps\n", " # 强制重装: force_install -> install --force-reinstall\n", " # 仅强制重装: force_install_single -> install --force-reinstall --no-deps\n", " # 更新: update -> install --upgrade\n", " # 卸载: uninstall -y\n", " def py_pkg_manager(self, pkg, type=None, use_mirror=False):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " if type == \"install\":\n", " func = \"install\"\n", " args = \"\"\n", " elif type == \"install_single\":\n", " func = \"install\"\n", " args = \"--no-deps\"\n", " elif type == \"force_install\":\n", " func = \"install\"\n", " args = \"--force-reinstall\"\n", " elif type == \"force_install_single\":\n", " func = \"install\"\n", " args = \"install --force-reinstall --no-deps\"\n", " elif type == \"update\":\n", " func = \"install\"\n", " args = \"--upgrade\"\n", " elif type == \"uninstall\":\n", " func = \"uninstall\"\n", " args = \"-y\"\n", " pip_mirror = \"\"\n", " else:\n", " echo(f\"未知操作: {type}\")\n", " return\n", " echo(f\"执行操作: pip {func} {pkg} {args} {pip_mirror}\")\n", " !pip {func} {pkg} {args} {pip_mirror}\n", "\n", "\n", " # 配置内存优化\n", " def tcmalloc(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " os.environ[\"LD_PRELOAD\"] = \"/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4\"\n", "\n", "\n", " # 适用于colab的内存优化\n", " def tcmalloc_colab(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " aria2 = ARIA2(self.WORKSPACE, self.WORKFOLDER)\n", " path = self.WORKSPACE\n", " libtcmalloc_path = self.WORKSPACE + \"/libtcmalloc_minimal.so.4\"\n", " aria2.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/libtcmalloc_minimal.so.4\", path, \"libtcmalloc_minimal.so.4\")\n", " os.environ[\"LD_PRELOAD\"] = libtcmalloc_path\n", "\n", "\n", "\n", "# MANAGER\n", "class MANAGER:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 清理ipynb笔记的输出\n", " def clear_up(self, opt):\n", " from IPython.display import clear_output\n", " clear_output(wait=opt)\n", "\n", "\n", " # 检查gpu是否可用\n", " def check_gpu(self):\n", " echo(\"检测 GPU 是否可用\")\n", " import tensorflow as tf\n", " echo(f\"TensorFlow 版本: {tf.__version__}\")\n", " if tf.test.gpu_device_name():\n", " echo(\"GPU 可用\")\n", " else:\n", " echo(\"GPU 不可用\")\n", " raise Exception(\"\\n没有使用GPU,请在代码执行程序-更改运行时类型-设置为GPU!\\n如果不能使用GPU,建议更换账号!\")\n", "\n", "\n", " # 配置google drive\n", " def config_google_drive(self):\n", " echo(\"挂载 Google Drive\")\n", " import os\n", " if not os.path.exists('/content/drive/MyDrive'):\n", " from google.colab import drive\n", " drive.mount('/content/drive')\n", " echo(\"Google Dirve 挂载完成\")\n", " else:\n", " echo(\"Google Drive 已挂载\")\n", "\n", " # 检测并创建输出文件夹\n", " if os.path.exists('/content/drive/MyDrive'):\n", " if not os.path.exists('/content/drive/MyDrive/fooocus_output'):\n", " echo(\"在 Google Drive 创建 fooocus_ouput 文件夹\")\n", " !mkdir -p /content/drive/MyDrive/fooocus_output\n", " else:\n", " raise Exception(\"未挂载 Google Drive,请重新挂载后重试!\")\n", "\n", "\n", " def set_huggingface_mirror(self ,mirror):\n", " import os\n", " echo(f\"设置 HuggingFace 镜像源: {mirror}\")\n", " os.environ[\"HF_ENDPOINT\"] = mirror\n", "\n", "\n", " def unset_huggingface_mirror(self):\n", " import os\n", " if \"HF_ENDPOINT\" in os.environ:\n", " echo(\"删除 HuggingFace 镜像源配置\")\n", " os.unsetenv(\"HF_ENDPOINT\")\n", " else:\n", " echo(\"HuggingFace 镜像源未设置, 无需删除\")\n", "\n", "\n", " def hf_link_to_mirror_link(self, hf_mirror, url):\n", " if isinstance(url, str):\n", " return url.replace(\"https://huggingface.co\",hf_mirror)\n", " else:\n", " mirror_url = url\n", " j = 0\n", " for i in mirror_url:\n", " tmp = i.replace(\"https://huggingface.co\",hf_mirror)\n", " mirror_url[j] = tmp\n", " j += 1\n", " return mirror_url\n", "\n", "\n", " def select_list(self, data, name):\n", " # https://stackoverflow.com/questions/57219796/ipywidgets-dynamic-creation-of-checkboxes-and-selection-of-data\n", " # https://gist.github.com/MattJBritton/9dc26109acb4dfe17820cf72d82f1e6f\n", " import ipywidgets as widgets\n", " names = [] # 可选择的列表\n", " checkbox_objects = [] # 按钮对象\n", " for key in data:\n", " value = key[1]\n", " key = key[0].split(\"/\").pop()\n", " if value == 1:\n", " select = True\n", " else:\n", " select = False\n", " checkbox_objects.append(widgets.Checkbox(value=select, description=key, )) # 扩展按钮列表\n", " names.append(key)\n", "\n", " arg_dict = {names[i]: checkbox for i, checkbox in enumerate(checkbox_objects)}\n", "\n", " ui = widgets.VBox(children=checkbox_objects) # 创建widget\n", "\n", " selected_data = []\n", " select_value = [] # 存储每个模型选择情况\n", " url_list = [] # 地址列表\n", " def select_data(**kwargs): # 每次点击按钮时都会执行\n", " selected_data.clear()\n", " select_value.clear()\n", " for key in kwargs:\n", " if kwargs[key] is True:\n", " selected_data.append(key)\n", " select_value.append(True)\n", " else:\n", " select_value.append(False)\n", "\n", " list = \"\"\n", " for i in selected_data: # 已选择的模型列表(模型名称)\n", " list = f\"{list}\\n- {i}\"\n", " print(f\"已选择列表: {list}\")\n", " j = 0\n", " url_list.clear()\n", " for i in select_value: # 返回的地址列表\n", " if i is True:\n", " url_list.append(data[j][0])\n", " j += 1\n", " \n", " out = widgets.interactive_output(select_data, arg_dict)\n", " ui.children = [*ui.children, out]\n", " ui = widgets.Accordion(children=[ui,], titles=(name,))\n", " #display(ui, out)\n", " display(ui)\n", " return url_list\n", "\n", "\n", " def select_button(self, name, normal_value):\n", " import ipywidgets as widgets\n", " return widgets.Checkbox(\n", " value=normal_value,\n", " description=name,\n", " disabled=False,\n", " indent=False\n", " )\n", "\n", "\n", " def text_input(self, name, notice, normal_text=\"\"):\n", " import ipywidgets as widgets\n", " return widgets.Textarea(\n", " value=normal_text,\n", " placeholder=notice ,\n", " description=name,\n", " disabled=False\n", " )\n", "\n", "\n", " def dropdown(self, name, list, normal_value):\n", " import ipywidgets as widgets\n", " widgets.Dropdown(\n", " options=list,\n", " value=normal_value,\n", " description=name,\n", " disabled=False,\n", " )\n", "\n", "\n", " def fix_lang(self):\n", " # ???\n", " import os\n", " os.environ[\"LANG\"] = \"zh_CN.UTF-8\"\n", "\n", "\n", "\n", "#SD_WEBUI\n", "class SD_WEBUI(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7860)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def install_extension(self, list):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions\"\n", " if isinstance(list, str):\n", " self.clone(list, path)\n", " else:\n", " for i in list:\n", " if i != \"\":\n", " self.clone(i, path)\n", "\n", "\n", " def install_model(self, sd, lora, vae, vae_approx, embedding, upscale, controlnet):\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", " self.get_vae_model_from_list(vae)\n", " self.get_vae_approx_model_from_list(vae_approx)\n", " self.get_embedding_model_from_list(embedding)\n", " self.get_upscale_model_from_list(upscale)\n", " self.get_controlnet_model_from_list(controlnet)\n", "\n", "\n", " def install_config(self):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/sd_webui_config.json\", path, \"config.json\")\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, extension, sd, lora, vae, vae_approx, embedding, upscale, controlnet, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/AUTOMATIC1111/stable-diffusion-webui\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.install_config()\n", " self.tcmalloc()\n", " self.install_extension(extension)\n", " self.install_model(sd, lora, vae, vae_approx, embedding, upscale, controlnet)\n", "\n", "\n", " def update(self):\n", " import os\n", " sd_webui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(sd_webui_path)\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions\"\n", " extensions_list = os.listdir(path)\n", " for i in extensions_list:\n", " extensions_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions/\" + i\n", " if os.path.isdir(extensions_path) and os.path.exists(extensions_path + \"/.git\"):\n", " self.pull(extensions_path)\n", "\n", "\n", " def get_extension_ver_list(self, name):\n", " import os\n", " sd_webui_extension_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions/\" + name\n", " if os.path.exists(sd_webui_extension_path):\n", " print(self.log(sd_webui_extension_path))\n", " else:\n", " echo(f\"未找到 {name}\")\n", "\n", "\n", " def set_extension_ver(self, name, commit):\n", " import os\n", " sd_webui_extension_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions/\" + name\n", " if os.path.exists(sd_webui_extension_path):\n", " self.checkout(sd_webui_extension_path, commit)\n", " else:\n", " echo(f\"未找到 {name}\")\n", "\n", "\n", " def get_core_ver(self):\n", " sd_webui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(sd_webui_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " sd_webui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(sd_webui_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " sd_webui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"SD WebUI 版本:\")\n", " print(self.git_show_ver(sd_webui_path))\n", " echo(\"SD WebUI 插件版本:\")\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions\"\n", " extensions_list = os.listdir(path)\n", " for i in extensions_list:\n", " extensions_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/extensions/\" + i\n", " if os.path.isdir(extensions_path) and os.path.exists(extensions_path + \"/.git\"):\n", " print(self.git_show_ver(extensions_path))\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/Stable-diffusion\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", " def get_controlnet_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/ControlNet\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", " \n", "\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/Lora\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/VAE\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_approx_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/VAE-approx\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_upscale_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/ESRGAN\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename) \n", "\n", "\n", " def get_embedding_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/embeddings\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_controlnet_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_controlnet_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_approx_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_approx_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_upscale_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_upscale_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_embedding_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_embedding_model(i, i.split(\"/\").pop())\n", "\n", "\n", "\n", "# COMFYUI\n", "class COMFYUI(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 8188)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def install_custom_node(self, list):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes\"\n", " if isinstance(list, str):\n", " self.clone(list, path)\n", " else:\n", " for i in list:\n", " if i != \"\":\n", " self.clone(i, path)\n", "\n", "\n", " def install_model(self, sd, lora, vae, vae_approx, embedding, upscale, controlnet):\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", " self.get_vae_model_from_list(vae)\n", " self.get_vae_approx_model_from_list(vae_approx)\n", " self.get_embedding_model_from_list(embedding)\n", " self.get_upscale_model_from_list(upscale)\n", " self.get_controlnet_model_from_list(controlnet)\n", "\n", "\n", " def install_custom_node_requirement(self):\n", " import os\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes\"\n", " custom_node_list = os.listdir(path)\n", " for i in custom_node_list:\n", " custom_node_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes/\" + i\n", " if os.path.isdir(custom_node_path):\n", " os.chdir(custom_node_path)\n", " if os.path.exists(\"install.py\"):\n", " echo(f\"安装 {i} 扩展依赖\")\n", " !python install.py\n", " if os.path.exists(\"requirements.txt\"):\n", " echo(f\"安装 {i} 扩展依赖\")\n", " !pip install -r requirements.txt\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, custom_node, sd, lora, vae, vae_approx, embedding, upscale, controlnet, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/comfyanonymous/ComfyUI\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " self.install_requirements(req_file, use_mirror)\n", " self.tcmalloc()\n", " self.install_custom_node(custom_node)\n", " self.install_custom_node_requirement()\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.install_model(sd, lora, vae, vae_approx, embedding, upscale, controlnet)\n", "\n", "\n", " def get_custom_node_ver_list(self, name):\n", " import os\n", " comfyui_custom_node_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes/\" + name\n", " if os.path.exists(comfyui_custom_node_path):\n", " print(self.log(comfyui_custom_node_path))\n", " else:\n", " echo(f\"未找到 {name}\")\n", "\n", "\n", " def set_custom_node_ver(self, name, commit):\n", " import os\n", " comfyui_custom_node_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes/\" + name\n", " if os.path.exists(comfyui_custom_node_path):\n", " self.checkout(comfyui_custom_node_path, commit)\n", " else:\n", " echo(f\"未找到 {name}\")\n", "\n", "\n", " def get_core_ver(self):\n", " comfyui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(comfyui_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " comfyui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(comfyui_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " comfyui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"ComfyUI 版本:\")\n", " print(self.git_show_ver(comfyui_path))\n", " echo(\"ComfyUI 插件版本:\")\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes\"\n", " custom_nodes_list = os.listdir(path)\n", " for i in custom_nodes_list:\n", " custom_node_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes/\" + i\n", " if os.path.isdir(custom_node_path) and os.path.exists(custom_node_path + \"/.git\"):\n", " print(self.git_show_ver(custom_node_path))\n", "\n", "\n", " def update(self):\n", " import os\n", " comfyui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(comfyui_path)\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes\"\n", " custom_node_list = os.listdir(path)\n", " for i in custom_node_list:\n", " custom_node_path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/custom_nodes/\" + i\n", " if os.path.isdir(custom_node_path) and os.path.exists(custom_node_path + \"/.git\"):\n", " self.pull(custom_node_path)\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoints\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_controlnet_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/controlnet\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", " \n", "\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/vae\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_approx_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/vae_approx\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_upscale_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/upscale_models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename) \n", "\n", "\n", " def get_embedding_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/embeddings\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_controlnet_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_controlnet_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_approx_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_approx_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_upscale_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_upscale_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_embedding_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_embedding_model(i, i.split(\"/\").pop())\n", "\n", "\n", "\n", "# FOOOCUS\n", "class FOOOCUS(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7865)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载大模型\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoints\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " # 下载lora模型\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " # 下载配置文件\n", " def install_config(self):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"下载配置文件\")\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_config.json\", path + \"/presets\", \"custom.json\")\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_zh_cn.json\", path + \"/language\", \"zh.json\")\n", " \n", "\n", " def install_config_colab(self):\n", " import os\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " path_config = path + \"/config.txt\"\n", " echo(\"下载路径配置文件\")\n", " if os.path.exists(path_config):\n", " !rm -rf \"{path_config}\"\n", " self.aria2(\"https://github.com/licyk/sd-webui-all-in-one/releases/download/archive/fooocus_path_config_colab.json\", path, \"config.txt\")\n", "\n", "\n", " # 安装fooocus\n", " def install(self, torch_ver, xformers_ver, sd, lora, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/lllyasviel/Fooocus\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver, use_mirror)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements_versions.txt\"\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.install_config()\n", " self.tcmalloc()\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", "\n", "\n", " def update(self):\n", " import os\n", " fooocus_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(fooocus_path)\n", "\n", "\n", "# INVOKEAI\n", "class INVOKEAI(ARIA2, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 9090)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoint\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_embedding_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/embeddings\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_embedding_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_embedding_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/vae\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, lora, vae, embedding, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " os.mkdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(\"\", xformers_ver)\n", " self.py_pkg_manager(\"invokeai\", \"install\", use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.tcmalloc()\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", " self.get_vae_model_from_list(vae)\n", " self.get_embedding_model_from_list(embedding)\n", "\n", "\n", " def update(self):\n", " echo(\"更新 InvokeAI\")\n", " !pip install invokeai -U\n", "\n", "\n", "# SD_TRAINER\n", "class SD_TRAINER(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 28000)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install_kohya_requirements(self,use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts\")\n", " self.install_requirements(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts/requirements.txt\", use_mirror)\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, vae, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/Akegarasu/lora-scripts\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " # self.install_kohya_requirements(use_mirror)\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.tcmalloc()\n", " self.get_sd_model_from_list(sd)\n", " self.get_vae_model_from_list(vae)\n", "\n", "\n", " def update(self):\n", " import os\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(sd_trainer_path)\n", "\n", "\n", " def get_core_ver(self):\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(sd_trainer_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(sd_trainer_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"SD Trainer 版本:\")\n", " print(self.git_show_ver(sd_trainer_path))\n", "\n", "\n", "\n", "# KOHYA GUI\n", "class KOHYA_GUI(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7860)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install_kohya_requirements(self,use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts\")\n", " self.install_requirements(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts/requirements.txt\", use_mirror)\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, vae, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/bmaltais/kohya_ss\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " # self.install_kohya_requirements(use_mirror)\n", " self.install_requirements(req_file, use_mirror)\n", " self.py_pkg_manager(\"numpy==1.26.4\", \"force_install\", use_mirror)\n", " self.tcmalloc()\n", " self.get_sd_model_from_list(sd)\n", " self.get_vae_model_from_list(vae)\n", "\n", "\n", " def update(self):\n", " import os\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(kohya_gui_path)\n", "\n", "\n", " def get_core_ver(self):\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(kohya_gui_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(kohya_gui_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"Kohya_GUI 版本:\")\n", " print(self.git_show_ver(kohya_gui_path))\n", "\n", "\n", "echo(\"初始化功能完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 参数配置\n", "2. [[← 上一个单元](#功能初始化)|[下一个单元 →](#应用参数配置)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [], "source": [ "try: \n", " i = INIT_CONFIG\n", " echo(\"尝试安装 ipywidgets 组件\")\n", " !pip install ipywidgets -qq\n", " from IPython.display import clear_output\n", " clear_output(wait=False)\n", " INIT_CONFIG_1 = 1\n", "except:\n", " raise Exception(\"未初始化功能\")\n", "\n", "import ipywidgets as widgets\n", "\n", "WEBUI = \"\"\n", "WORKSPACE = \"\"\n", "WORKFOLDER = \"\"\n", "USE_MIRROR = False\n", "USE_NGROK = False\n", "NGROK_TOKEN = \"\"\n", "USE_CLOUDFLARE = False\n", "USE_REMOTE_MOE = True\n", "USE_LOCALHOST_RUN = True\n", "USE_GRADIO_SHARE = False\n", "FIX_LANG = False\n", "TORCH_VER = \"\"\n", "XFORMERS_VER = \"\"\n", "GITHUB_MIRROR = [\n", " \"https://ghproxy.net/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://mirror.ghproxy.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gh-proxy.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://ghps.cc/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gh.idayer.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gitclone.com/github.com/term_sd_git_user/term_sd_git_repo\"\n", "]\n", "HUGGINGFACE_MIRROR = \"https://hf-mirror.com\"\n", "sd_model = [\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cetusMix_Whalefall2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ex2K_sse2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/kohakuV5_rev2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinamix_meinaV11.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/oukaStar_10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/rabbit_v6.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/sweetSugarSyndrome_rev15.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/AnythingV5Ink_ink.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinapastel_v6Pastel.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/qteamixQ_omegaFp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/AnythingXL_xl.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/abyssorangeXLElse_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animaPencilXL_v200.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/nekorayxl_v06W3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/CounterfeitXL-V1.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", 0]\n", "]\n", "lora = [\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_AnimeFace.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_Saturation.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_EdgeEmphasys.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_bodyshadow.safetensors\", 0],\n", " [\"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors\", 0]\n", "]\n", "embedding = [\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/EasyNegative.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/EasyNegativeV2.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-artist-anime.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-artist.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-hands-5.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-image-v2-39000.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad_prompt_version2.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/ng_deepnegative_v1_75t.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/verybadimagenegative_v1.3.pt\", 1]\n", "]\n", "vae = [\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", 1]\n", "]\n", "vae_approx = [\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/model.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sdxl.pt\", 1]\n", "]\n", "upscale = [\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x-UltraSharp.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/ESRGAN_4x.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", 0],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", 0],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", 1]\n", "]\n", "controlnet = [\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11e_sd15_ip2p_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11e_sd15_shuffle_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11f1e_sd15_tile_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11f1p_sd15_depth_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_canny_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_inpaint_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_mlsd_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_normalbae_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_openpose_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_scribble_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_seg_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15_softedge_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v1p_sd15_brightness.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v1p_sd15_illumination.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/control_v1p_sd15_qrcode_monster.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter_sd15.pth\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter_sd15_light.pth\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter_sd15_plus.pth\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter_sd15_vit-G.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter_sdxl.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/ip-adapter-plus_sdxl_vit-h.safetensors\", 1]\n", "]\n", "extension = [\n", " [\"https://github.com/hanamizuki-ai/stable-diffusion-webui-localization-zh_Hans\", 1],\n", " [\"https://github.com/Mikubill/sd-webui-controlnet\", 1],\n", " [\"https://github.com/continue-revolution/sd-webui-animatediff\", 1],\n", " [\"https://github.com/Bing-su/adetailer\", 1],\n", " [\"https://github.com/DominikDoom/a1111-sd-webui-tagcomplete\", 1],\n", " [\"https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111\", 1],\n", " [\"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding\", 1],\n", " [\"https://github.com/hnmr293/sd-webui-cutoff\", 1],\n", " [\"https://github.com/Akegarasu/sd-webui-model-converter\", 1],\n", " [\"https://github.com/hako-mikan/sd-webui-supermerger\", 1],\n", " [\"https://github.com/Akegarasu/sd-webui-wd14-tagger\", 1],\n", " [\"https://github.com/hako-mikan/sd-webui-regional-prompter\", 1],\n", " [\"https://github.com/zanllp/sd-webui-infinite-image-browsing\", 1],\n", " [\"https://github.com/Coyote-A/ultimate-upscale-for-automatic1111\", 1],\n", " [\"https://github.com/AUTOMATIC1111/stable-diffusion-webui-rembg\", 1],\n", " [\"https://github.com/hako-mikan/sd-webui-lora-block-weight\", 1],\n", " [\"https://github.com/Physton/sd-webui-prompt-all-in-one\", 1],\n", " [\"https://github.com/huchenlei/sd-webui-openpose-editor\", 1],\n", " [\"https://github.com/arenasys/stable-diffusion-webui-model-toolkit\", 1],\n", " [\"https://github.com/Tencent/LightDiffusionFlow\", 1],\n", " [\"https://github.com/Haoming02/sd-webui-boomer\", 1],\n", " [\"https://github.com/mix1009/model-keyword\", 1],\n", " [\"https://github.com/KohakuBlueleaf/a1111-sd-webui-haku-img\", 1],\n", " [\"https://github.com/continue-revolution/sd-webui-segment-anything\", 0],\n", " [\"https://github.com/Uminosachi/sd-webui-inpaint-anything\", 0],\n", " [\"https://github.com/KohakuBlueleaf/z-a1111-sd-webui-dtg\", 0],\n", " [\"https://github.com/pkuliyi2015/sd-webui-stablesr\", 0],\n", " [\"https://github.com/Elldreth/loopback_scaler\", 0],\n", " [\"https://github.com/CodeZombie/latentcoupleregionmapper\", 0],\n", " [\"https://github.com/ashen-sensored/stable-diffusion-webui-two-shot\", 0],\n", " [\"https://github.com/journey-ad/sd-webui-bilingual-localization\", 0],\n", " [\"https://github.com/zero01101/openOutpaint-webUI-extension\", 0],\n", " [\"https://github.com/huchenlei/sd-webui-api-payload-display\", 0],\n", " [\"https://github.com/thomasasfk/sd-webui-aspect-ratio-helper\", 0],\n", " [\"https://github.com/hako-mikan/sd-webui-cd-tuner\", 0],\n", " [\"https://github.com/hako-mikan/sd-webui-negpip\", 0,],\n", " [\"https://github.com/butaixianran/Stable-Diffusion-Webui-Civitai-Helper\", 0],\n", " [\"https://github.com/mattyamonaca/PBRemTools\", 0],\n", " [\"https://github.com/BlafKing/sd-civitai-browser-plus\", 0],\n", " [\"https://github.com/nihedon/sd-webui-weight-helper\", 0],\n", " [\"https://github.com/Koishi-Star/Euler-Smea-Dyn-Sampler\", 0],\n", " [\"https://github.com/Firetheft/sd-webui-next-style\", 0],\n", " [\"https://github.com/Haoming02/sd-webui-vectorscope-cc\", 0],\n", " [\"https://github.com/AG-w/sd-webui-smea\", 0],\n", " [\"https://github.com/ljleb/sd-webui-neutral-prompt\", 0]\n", "]\n", "custom_node = [\n", " [\"https://github.com/Fannovel16/comfyui_controlnet_aux\", 1],\n", " [\"https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved\", 1],\n", " [\"https://github.com/cubiq/ComfyUI_IPAdapter_plus\", 1],\n", " [\"https://github.com/ltdrdata/ComfyUI-Impact-Pack\", 1],\n", " [\"https://github.com/kijai/ComfyUI-Marigold\", 1],\n", " [\"https://github.com/pythongosssss/ComfyUI-WD14-Tagger\", 1],\n", " [\"https://github.com/WASasquatch/was-node-suite-comfyui\", 0],\n", " [\"https://github.com/BlenderNeko/ComfyUI_Cutoff\", 0],\n", " [\"https://github.com/BlenderNeko/ComfyUI_TiledKSampler\", 1],\n", " [\"https://github.com/ltdrdata/ComfyUI-Manager\", 1],\n", " [\"https://github.com/pythongosssss/ComfyUI-Custom-Scripts\", 1],\n", " [\"https://github.com/Derfuu/Derfuu_ComfyUI_ModdedNodes\", 1],\n", " [\"https://github.com/comfyanonymous/ComfyUI_experiments\", 1],\n", " [\"https://github.com/ssitu/ComfyUI_UltimateSDUpscale\", 1],\n", " [\"https://github.com/AlekPet/ComfyUI_Custom_Nodes_AlekPet\", 1],\n", " [\"https://github.com/AIGODLIKE/AIGODLIKE-COMFYUI-TRANSLATION\", 1],\n", " [\"https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI\", 1],\n", " [\"https://github.com/jags111/efficiency-nodes-comfyui\", 1],\n", " [\"https://github.com/11cafe/comfyui-workspace-manager\", 1],\n", " [\"https://github.com/talesofai/comfyui-browser\", 1],\n", " [\"https://github.com/ltdrdata/ComfyUI-Inspire-Pack\", 1],\n", " [\"https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes\", 1],\n", " [\"https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet\", 1],\n", " [\"https://github.com/WASasquatch/PowerNoiseSuite\", 1],\n", " [\"https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved\", 0],\n", " [\"https://github.com/huchenlei/ComfyUI-layerdiffusion\", 0],\n", " [\"https://github.com/huchenlei/ComfyUI_DanTagGen\", 0,],\n", " [\"https://github.com/gameltb/Comfyui-StableSR\", 0],\n", " [\"https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb\", 0],\n", " [\"https://github.com/Davemane42/ComfyUI_Dave_CustomNode\", 0],\n", " [\"https://github.com/LucianoCirino/efficiency-nodes-comfyui\", 0],\n", " [\"https://github.com/lilly1987/ComfyUI_node_Lilly\", 0],\n", " [\"https://github.com/hnmr293/ComfyUI-nodes-hnmr\", 0],\n", " [\"https://github.com/yolain/ComfyUI-Easy-Use\", 0],\n", " [\"https://github.com/chrisgoringe/cg-use-everywhere\", 0],\n", " [\"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding\", 0],\n", " [\"https://github.com/crystian/ComfyUI-Crystools\", 0],\n", " [\"https://github.com/Nuked88/ComfyUI-N-Sidebar\", 0],\n", " [\"https://github.com/chflame163/ComfyUI_LayerStyle\", 0],\n", " [\"https://github.com/flowtyone/ComfyUI-Flowty-TripoSR\", 0],\n", " [\"https://github.com/kijai/ComfyUI-SUPIR\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-PixArt-alpha-Diffusers\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-BiRefNet-ZHO\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-DepthFM\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-APISR\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-ArtGallery\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-I2VGenXL\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-SegMoE\", 0],\n", " [\"https://github.com/ZHO-ZHO-ZHO/ComfyUI-AnyText\", 0],\n", " [\"https://github.com/Clybius/ComfyUI-Extra-Samplers\", 0],\n", " [\"https://github.com/blepping/ComfyUI-sonar\", 0],\n", " [\"https://github.com/ssitu/ComfyUI_restart_sampling\", 0],\n", " [\"https://github.com/kijai/ComfyUI-Diffusers-X-Adapter\", 0],\n", " [\"https://github.com/nullquant/ComfyUI-BrushNet\", 0],\n", " [\"https://github.com/kijai/ComfyUI-BrushNet-Wrapper\", 0],\n", " [\"https://github.com/Koishi-Star/Euler-Smea-Dyn-Sampler\", 0],\n", " [\"https://github.com/blepping/ComfyUI-bleh\", 0],\n", " [\"https://github.com/dfl/comfyui-tcd-scheduler\", 0]\n", "]\n", "WEBUI_LIST = [\"sd_webui\", \"comfyui\", \"fooocus\", \"invokeai\", \"sd_trainer\", \"kohya_gui\"]\n", "\n", "manager = MANAGER(WORKSPACE, WORKFOLDER)\n", "gi = GIT(WORKSPACE, WORKFOLDER)\n", "\n", "workspace_state = widgets.Textarea(value=\"\", placeholder=\"请输入工作区路径\", description=\"工作区路径: \", disabled=False)\n", "webui_state = widgets.Dropdown(options=WEBUI_LIST, value=\"sd_webui\", description=\"使用的 WebUI: \", disabled=False)\n", "torch_ver_state = widgets.Textarea(value=\"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121\", placeholder=\"请填写 PyTorch 版本\", description=\"PyTorch 版本: \", disabled=False)\n", "xformers_ver_state = widgets.Textarea(value=\"xformers==0.0.25\", placeholder=\"请填写 xFormers 版本\", description=\"xFormers 版本: \", disabled=False)\n", "use_mirror_state = widgets.Checkbox(value=False, description=\"使用镜像源\", disabled=False)\n", "fix_lang_state = widgets.Checkbox(value=False, description=\"修复语言问题\", disabled=False)\n", "is_colab_state = widgets.Checkbox(value=False, description=\"使用 Colab 环境\", disabled=False)\n", "use_ngrok_state = widgets.Checkbox(value=False, description=\"使用 Ngrok 内网穿透\", disabled=False)\n", "ngrok_token_state = widgets.Textarea(value=\"\", placeholder=\"请填写 Ngrok Token(可在 Ngrok 官网获取)\", description=\"Ngrok Token: \", disabled=False)\n", "use_cloudflare_state = widgets.Checkbox(value=False, description=\"使用 CloudFlare 内网穿透\", disabled=False)\n", "use_remote_moe_state = widgets.Checkbox(value=True, description=\"使用 remote.moe 内网穿透\", disabled=False)\n", "use_localhost_run_state = widgets.Checkbox(value=True, description=\"使用 localhost.run 内网穿透\", disabled=False)\n", "use_gradio_share_state = widgets.Checkbox(value=False, description=\"使用 Gradio 内网穿透\", disabled=False)\n", "display(workspace_state, webui_state, torch_ver_state, xformers_ver_state, use_mirror_state, fix_lang_state, use_ngrok_state, ngrok_token_state, use_cloudflare_state, use_remote_moe_state, use_localhost_run_state, use_gradio_share_state)\n", "\n", "\n", "sd_model_list = manager.select_list(sd_model,\"Stable Diffusion 模型\")\n", "lora_list = manager.select_list(lora, \"LoRA 模型\")\n", "embedding_list = manager.select_list(embedding, \"Embedding 模型\")\n", "vae_list = manager.select_list(vae, \"VAE 模型\")\n", "vae_approx_list = manager.select_list(vae_approx, \"VAE-approx 模型\")\n", "upscale_list = manager.select_list(upscale, \"放大模型\")\n", "controlnet_list = manager.select_list(controlnet, \"ControlNet 模型\")\n", "extension_list = manager.select_list(extension, \"SD WebUI 扩展\")\n", "custom_node_list = manager.select_list(custom_node, \"ComfyUI 扩展\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 应用参数配置\n", "3. [[← 上一个单元](#参数配置)|[下一个单元 →](#安装)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try: \n", " i = INIT_CONFIG_1\n", " INIT_CONFIG_1 = 1\n", " INIT_CONFIG_2 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数配置\\\"单元\")\n", "\n", "WORKSPACE = workspace_state.value.rstrip(\"/\").rstrip(\"\\\\\")\n", "WEBUI = webui_state.value\n", "TORCH_VER = torch_ver_state.value\n", "XFORMERS_VER = xformers_ver_state.value\n", "USE_MIRROR = use_mirror_state.value\n", "FIX_LANG = fix_lang_state.value\n", "IS_COLAB = is_colab_state.value\n", "USE_NGROK = use_ngrok_state.value\n", "NGROK_TOKEN = ngrok_token_state.value\n", "USE_CLOUDFLARE = use_cloudflare_state.value\n", "USE_REMOTE_MOE = use_remote_moe_state.value\n", "USE_LOCALHOST_RUN = use_localhost_run_state.value\n", "USE_GRADIO_SHARE = use_gradio_share_state.value\n", "\n", "if WORKSPACE != \"\":\n", " if WEBUI == \"sd_webui\":\n", " WORKFOLDER = \"stable-diffusion-webui\"\n", " sd_webui = SD_WEBUI(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"comfyui\":\n", " WORKFOLDER = \"ComfyUI\"\n", " comfyui = COMFYUI(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"fooocus\":\n", " WORKFOLDER = \"Fooocus\"\n", " fooocus = FOOOCUS(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"invokeai\":\n", " WORKFOLDER = \"InvokeAI\"\n", " invokeai = INVOKEAI(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"sd_trainer\":\n", " WORKFOLDER = \"lora-scripts\"\n", " sd_trainer = SD_TRAINER(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"kohya_gui\":\n", " WORKFOLDER = \"kohya_ss\"\n", " kohya_gui = KOHYA_GUI(WORKSPACE, WORKFOLDER)\n", "else:\n", " raise Exception(\"未填写工作区路径\")\n", "\n", "import os\n", "os.chdir(WORKSPACE)\n", "manager = MANAGER(WORKSPACE, WORKFOLDER)\n", "\n", "if USE_MIRROR:\n", " sd_model = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, sd_model_list)\n", " lora = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, lora_list)\n", " embedding = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, embedding_list)\n", " vae = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, vae_list)\n", " vae_approx = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, vae_approx_list)\n", " upscale = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, upscale_list)\n", " controlnet = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, controlnet_list)\n", " manager.set_huggingface_mirror(HUGGINGFACE_MIRROR)\n", " gi.set_github_mirror(GITHUB_MIRROR)\n", "echo(\"参数设置完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 安装\n", "4. [[← 上一个单元](#应用参数配置)|[下一个单元 →](#启动)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try: \n", " i = INIT_CONFIG_2\n", " INIT_CONFIG_2 = 1\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数设置\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE)\n", "echo(f\"开始安装 {WEBUI}\")\n", "if WEBUI == \"sd_webui\":\n", " sd_webui.install(TORCH_VER, XFORMERS_VER, extension_list, sd_model_list, lora_list, vae_list, vae_approx_list, embedding_list, upscale_list, controlnet_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " sd_webui.tcmalloc_colab()\n", "elif WEBUI == \"comfyui\":\n", " comfyui.install(TORCH_VER, XFORMERS_VER, custom_node_list, sd_model_list, lora_list, vae_list, vae_approx_list, embedding_list, upscale_list, controlnet_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " comfyui.tcmalloc_colab()\n", "elif WEBUI == \"fooocus\":\n", " fooocus.install(TORCH_VER, XFORMERS_VER, sd_model_list, lora_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " fooocus.tcmalloc_colab()\n", " fooocus.install_config_colab()\n", "elif WEBUI == \"invokeai\":\n", " invokeai.install(TORCH_VER, XFORMERS_VER, sd_model_list, lora_list, vae_list, embedding_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " fooocus.tcmalloc_colab()\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.install(TORCH_VER, XFORMERS_VER, sd_model_list, vae_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " sd_trainer.tcmalloc_colab()\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.install(TORCH_VER, XFORMERS_VER, sd_model_list, vae_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " kohya_gui.tcmalloc_colab()\n", "\n", "manager.clear_up(False)\n", "if FIX_LANG:\n", " manager.fix_lang()\n", "\n", "echo(f\"{WEBUI} 安装完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 启动\n", "5. [[← 上一个单元](#安装)|[下一个单元 →](#自定义模型|扩展下载配置)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "echo(f\"启动 {WEBUI}\")\n", "if WEBUI == \"sd_webui\":\n", " sd_webui.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !python \"{WORKSPACE}\"/stable-diffusion-webui/launch.py --xformers \n", "elif WEBUI == \"comfyui\":\n", " comfyui.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !python \"{WORKSPACE}\"/ComfyUI/main.py\n", "elif WEBUI == \"fooocus\":\n", " fooocus.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !python \"{WORKSPACE}\"/Fooocus/launch.py --preset custom --language zh --disable-offload-from-vram --async-cuda-allocation\n", "elif WEBUI == \"invokeai\":\n", " invokeai.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !invokeai-web --root \"{WORKSPACE}\"/InvokeAI/invokeai\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !python \"{WORKSPACE}\"/lora-scripts/gui.py\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=USE_GRADIO_SHARE)\n", " !python \"{WORKSPACE}\"/kohya_ss/kohya_gui.py --language zh-CN\n", "manager.clear_up(False)\n", "echo(f\"{WEBUI} 已关闭\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 其他功能" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 自定义模型|扩展下载配置\n", "6. [[← 上一个单元](#启动)|[下一个单元 →](#自定义模型|扩展下载)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", " INIT_CONFIG_4 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import ipywidgets as widgets\n", "\n", "model_ = widgets.Textarea(\n", " value=\"\",\n", " placeholder='请填写模型 / 扩展下载链接',\n", " description='模型 / 扩展下载链接: ',\n", " disabled=False\n", ")\n", "\n", "model_name_ = widgets.Textarea(\n", " value=\"\",\n", " placeholder='请填写模型名称',\n", " description='模型名称: ',\n", " disabled=False\n", ")\n", "\n", "model_type_ = widgets.Dropdown(\n", " options=[(\"Stable Diffusion 模型(大模型)\", \"sd\"),\n", " (\"LoRA 模型\", \"lora\"),\n", " (\"Emebdding 模型\", \"embedding\"),\n", " (\"VAE 模型\", \"vae\"),\n", " (\"VAE-approx 模型\", \"vae-approx\"),\n", " (\"放大模型\", \"upscale\"),\n", " (\"ControlNet 模型\", \"controlnet\"),\n", " (\"SD WebUI 扩展\", \"extension\"),\n", " (\"ComfyUI 扩展\", \"custom_node\")\n", " ],\n", " value=\"sd\",\n", " description='模型 / 扩展种类',\n", ")\n", "\n", "display(model_, model_name_, model_type_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 自定义模型|扩展下载\n", "7. [[← 上一个单元](#自定义模型|扩展下载配置)|[下一个单元 →](#更新)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG_4\n", "except:\n", " raise Exception(\"未运行\\\"自定义模型 / 扩展下载配置\\\"单元\")\n", "\n", "model = model_.value\n", "model_name = model_name_.value\n", "model_type = model_type_.value\n", "\n", "if model == \"\" and model_name == \"\":\n", " raise Exception(\"未填写模型 / 扩展链接或者模型名称\")\n", "\n", "\n", "if WEBUI == \"sd_webui\":\n", " if model_type == \"ss\":\n", " sd_webui.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " sd_webui.get_lora_model(model, model_name)\n", " if model_type == \"embedding\":\n", " sd_webui.get_embedding_model(model, model_name)\n", " if model_type == \"vae\":\n", " sd_webui.get_vae_model(model, model_name)\n", " if model_type == \"vae-approx\":\n", " sd_webui.get_vae_approx_model(model, model_name)\n", " if model_type == \"upscale\":\n", " sd_webui.get_upscale_model(model, model_name)\n", " if model_type == \"controlnet\":\n", " sd_webui.get_controlnet_model(model, model_name)\n", " if model_type == \"extension\":\n", " sd_webui.install_extension(model)\n", "elif WEBUI == \"comfyui\":\n", " if model_type == \"sd\":\n", " comfyui.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " comfyui.get_lora_model(model, model_name)\n", " if model_type == \"embedding\":\n", " comfyui.get_embedding_model(model, model_name)\n", " if model_type == \"vae\":\n", " comfyui.get_vae_model(model, model_name)\n", " if model_type == \"vae-approx\":\n", " comfyui.get_vae_approx_model(model, model_name)\n", " if model_type == \"upscale\":\n", " comfyui.get_upscale_model(model, model_name)\n", " if model_type == \"controlnet\":\n", " comfyui.get_controlnet_model(model, model_name)\n", " if model_type == \"custom_node\":\n", " comfyui.install_custom_node(model)\n", "elif WEBUI == \"invokeai\":\n", " if model_type == \"sd\":\n", " invokeai.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " invokeai.get_lora_model(model, model_name)\n", " if model_type == \"embedding\":\n", " invokeai.get_embedding_model(model, model_name)\n", " if model_type == \"vae\":\n", " invokeai.get_vae_model(model, model_name)\n", "elif WEBUI == \"fooocus\":\n", " if model_type == \"sd\":\n", " fooocus.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " fooocus.get_lora_model(model, model_name)\n", "elif WEBUI == \"sd_trainer\":\n", " if model_type == \"sd\":\n", " sd_trainer.get_sd_model(model, model_name)\n", " if model_type == \"vae\":\n", " sd_trainer.get_vae_model(model, model_name)\n", "elif WEBUI == \"kohya_gui\":\n", " if model_type == \"sd\":\n", " kohya_gui.get_sd_model(model, model_name)\n", " if model_type == \"vae\":\n", " sd_trainer.get_vae_model(model, model_name)\n", "else:\n", " raise Exception(f\"未知软件类型 {WEBUI}\")\n", "\n", "echo(f\"{WEBUI} 模型文件扩展下载完成\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 更新\n", "8. [[← 上一个单元](#自定义模型|扩展下载)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "echo(f\"启动 {WEBUI}\")\n", "if WEBUI == \"sd_webui\":\n", " sd_webui.update()\n", "elif WEBUI == \"comfyui\":\n", " comfyui.update()\n", "elif WEBUI == \"fooocus\":\n", " fooocus.update()\n", "elif WEBUI == \"invokeai\":\n", " invokeai.update()\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.update()\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.update()\n", "echo(f\"更新 {WEBUI} 完成\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 4 }
2301_81996401/sd-webui-all-in-one
notebook/sd_webui_all_in_one.ipynb
Jupyter Notebook
agpl-3.0
107,391
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "1dc-6G5q_ydz" }, "source": [ "# SD WebUI All In One Colab\n", "#### Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是一个支持部署多种 WebUI 的 Jupyter Notebook,支持部署以下 WebUI:\n", "- 1、[InvokeAI](https://github.com/invoke-ai/InvokeAI)\n", "- 2、[Fooocus](https://github.com/lllyasviel/Fooocus)\n", "- 3、[lora-scripts](https://github.com/Akegarasu/lora-scripts)\n", "- 4、[kohya_ss](https://github.com/bmaltais/kohya_ss)\n", "\n", "使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "## 主要功能\n", "1. 功能初始化:导入 SD WebUI All In One 所使用的功能\n", "2. 参数配置:配置安装参数、远程访问方式、模型 / 扩展选择(有以下选项:Stable Diffusion 模型、LoRA 模型、Embedding 模型、VAE 模型、VAE-approx 模型、放大模型、ControlNet 模型、SD WebUI 扩展、ComfyUI 扩展)。\n", "3. 应用参数配置:应用已设置的参数\n", "4. 安装:根据配置安装对应的 WebUI\n", "5. 启动:根据配置启动对应的 WebUI\n", "\n", "## 其他功能\n", "1. 自定义模型 / 扩展下载配置:设置要下载的模型 / 扩展参数\n", "2. 自定义模型 / 扩展下载:根据配置进行下载模型 / 扩展\n", "3. 更新:将已安装的 WebUI 进行更新\n", "\n", "## 提示\n", "1. 在参数配置界面,请填写工作区路径(根据使用的平台进行填写,如Kaggle 平台填写`/kaggle`,Colab 平台填写`/content`),选择要使用的 WebUI,根据自己的需求选择内网穿透方式(用于访问 WebUI 界面),再根据自己的需求选择模型和扩展。\n", "2. 已知 CloudFlare、Gradio 内网穿透会导致 [Kaggle](https://www.kaggle.com) 平台强制关机,在使用 [Kaggle](https://www.kaggle.com) 平台时请勿勾选这两个选项。\n", "3. 若使用 [Colab](https://colab.research.google.com) 平台,请注意该 Jupyter Notebook 无法在免费版的 Colab 账号中使用,运行前将会收到 Colab 的警告提示,强行运行将会导致 Colab 强制关机(如果 Colab 账号已付费订阅可直接使用该 Jupyter Notebook),可选择仓库中其他的 Jupyter Notebook(将 Colab 中禁止的 WebUI 移除了)。\n", "4. [Ngrok](https://ngrok.com) 内网穿透的稳定性高,使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "5. 在启动时将启动内网穿透,可在控制台输出中看到内网穿透地址,用于访问 WebUI 界面。\n", "6. 云平台可能存在 ipywidgets 显示 Bug 导致一些提示无法显示出来,主要在参数配置单元的模型 / 扩展选择中出现这种问题。\n", "7. 调整参数配置后必须运行一次应用参数配置。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "id": "REpDxeFzBH-T", "outputId": "bec4e2e4-c059-45a6-ee0e-668eebbcf9c3" }, "outputs": [], "source": [ "#@title 👇 功能初始化\n", "INIT_CONFIG = 1\n", "\n", "# 消息格式输出\n", "def echo(*args):\n", " for i in args:\n", " print(f\":: {i}\")\n", "\n", "\n", "\n", "# ARIA2\n", "class ARIA2:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载器\n", " def aria2(self, url, path, filename):\n", " import os\n", " if not os.path.exists(path + \"/\" + filename):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " if os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"开始下载 {filename} ,路径: {path}/{filename}\")\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{url}\" -d \"{path}\" -o \"{filename}\"\n", " if os.path.exists(path + \"/\" + filename) and not os.path.exists(path + \"/\" + filename + \".aria2\"):\n", " echo(f\"{filename} 下载完成\")\n", " else:\n", " echo(f\"{filename} 下载中断\")\n", " else:\n", " echo(f\"{filename} 文件已存在,路径: {path}/{filename}\")\n", "\n", "\n", " # 大模型下载\n", " def get_sd_model(self, url, filename):\n", " pass\n", "\n", "\n", " # lora下载\n", " def get_lora_model(self, url, filename):\n", " pass\n", "\n", "\n", " # 放大模型下载\n", " def get_upscale_model(self, url, filename):\n", " pass\n", "\n", "\n", " # embedding模型下载\n", " def get_embedding_model(self, url, filename):\n", " pass\n", "\n", "\n", " # controlnet模型下载\n", " def get_controlnet_model(self, url, filename):\n", " pass\n", "\n", "\n", " # vae模型下载\n", " def get_vae_model(self, url, filename):\n", " pass\n", "\n", "\n", " # vae-approx模型下载\n", " def get_vae_approx_model(self, url, filename):\n", " pass\n", "\n", "\n", " # 获取modelscope下载链接\n", " def get_modelscope_link(self, origin):\n", " user = origin.split(\"/\")[0]\n", " repo = origin.split(\"/\")[1]\n", " branch = origin.split(\"/\")[2]\n", " tmp = f\"{user}/{repo}/{branch}/\"\n", " file = origin.split(tmp).pop().replace(\"/\", \"%2F\")\n", " link = f\"https://modelscope.cn/api/v1/models/{user}/{repo}/repo?Revision={branch}&FilePath={file}\"\n", " return link\n", "\n", "\n", "\n", "# GIT\n", "class GIT:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 检测要克隆的项目是否存在于指定路径\n", " def exists(self, addr=None, path=None, name=None):\n", " import os\n", " if addr is not None:\n", " if path is None and name is None:\n", " path = os.getcwd() + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " elif path is None and name is not None:\n", " path = os.getcwd() + \"/\" + name\n", " elif path is not None and name is None:\n", " path = os.path.normpath(path) + \"/\" + addr.split(\"/\").pop().split(\".git\", 1)[0]\n", "\n", " if os.path.exists(path):\n", " return True\n", " else:\n", " return False\n", "\n", "\n", " # 克隆项目\n", " def clone(self, addr, path=None, name=None):\n", " import os\n", " repo = addr.split(\"/\").pop().split(\".git\", 1)[0]\n", " if not self.exists(addr, path, name):\n", " echo(f\"开始下载 {repo}\")\n", " if path is None and name is None:\n", " path = os.getcwd()\n", " name = repo\n", " elif path is not None and name is None:\n", " name = repo\n", " elif path is None and name is not None:\n", " path = os.getcwd()\n", " !git clone {addr} \"{path}/{name}\" --recurse-submodules\n", " else:\n", " echo(f\"{repo} 已存在\")\n", "\n", "\n", " # 拉取更新\n", " def pull(self, path):\n", " import os\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " echo(f\"更新 {repo} 中\")\n", " if self.is_git_pointer_offset(path=path):\n", " self.fix_pointer(path=path)\n", " !git -C \"{path}\" pull --recurse-submodules\n", " else:\n", " echo(f\"路径不存在\")\n", "\n", "\n", " # 切换到指定版本\n", " def checkout(self, path, commit=None):\n", " import os\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " if commit is not None:\n", " echo(f\"切换 {repo} 版本中\")\n", " !git -C \"{path}\" reset --hard {commit} --recurse-submodules\n", " else:\n", " echo(f\"未指定 {repo} 版本\")\n", " else:\n", " echo(\"路径不存在\")\n", "\n", "\n", " # 修复分支漂移\n", " def fix_pointer(self, path):\n", " import os\n", " import subprocess\n", " if self.exists(path=path):\n", " repo = os.path.normpath(path).split(\"/\" and \"\\\\\").pop()\n", " echo(f\"修复 {repo} 分支游离中\")\n", " !git -C \"{path}\" remote prune origin\n", " !git -C \"{path}\" submodule init\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" branch -a | grep /HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout\n", " print(result)\n", " branch = result.split(\"/\").pop()\n", " !git -C \"{path}\" checkout {branch} # 切换到主分支\n", " !git -C \"{path}\" reset --recurse-submodules --hard origin/{branch}\n", " !git -C \"{path}\" reset --recurse-submodules --hard HEAD\n", " !git -C \"{path}\" restore --recurse-submodules --source=HEAD :/\n", " else:\n", " echo(\"路径不存在\")\n", "\n", "\n", " # 检测分支是否漂移\n", " def is_git_pointer_offset(self, path):\n", " if self.exists(path=path):\n", " import subprocess\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result == 0:\n", " return True\n", " else:\n", " echo(\"检测到出现分支游离\")\n", " return False\n", "\n", "\n", " # 输出版本信息\n", " def git_show_ver(self, path):\n", " import subprocess\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result == 0:\n", " cmd1 = f\"git -C \\\"{path}\\\" rev-parse --short HEAD\"\n", " cmd2 = f\"git -C \\\"{path}\\\" show -s --format=\\\"%cd\\\" --date=format:\\\"%Y-%m-%d %H:%M:%S\\\"\"\n", " commit = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"refs/heads/\", \"\").replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " else:\n", " cmd1 = f\"git -C \\\"{path}\\\" rev-parse --short HEAD\"\n", " cmd2 = f\"git -C \\\"{path}\\\" show -s --format=\\\"%cd\\\" --date=format:\\\"%Y-%m-%d %H:%M:%S\\\"\"\n", " commit = subprocess.run(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" \" + subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout.replace(\"\\n\",\"\")\n", " commit = commit + \" (分支游离)\"\n", " return path.split(\"/\").pop() + \": \" + commit\n", " else:\n", " return \"(非 Git 安装)\"\n", "\n", "\n", " def log(self, path):\n", " import subprocess\n", " if self.exists(path=path) and self.exists(path + \"/.git\"):\n", " result = subprocess.run(f\"git -C \\\"{path}\\\" symbolic-ref HEAD\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).returncode\n", " if result == 0:\n", " cmd = f\"git -C \\\"{path}\\\" log --all --date=short --pretty=format:\\\"%h %cd\\\" --date=format:\\\"%Y-%m-%d | %H:%M:%S\\\"\"\n", " return path.split(\"/\").pop() + \" 版本信息: \\n\" + subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout\n", " else:\n", " return path.split(\"/\").pop() + \" 非 Git 安装\"\n", "\n", "\n", " def test_github_mirror(self, mirror):\n", " import os\n", " import subprocess\n", " path = self.WORKSPACE + \"/empty\"\n", " for i in mirror:\n", " test_repo = i.replace(\"term_sd_git_user/term_sd_git_repo\",\"licyk/empty\")\n", " avaliable_mirror = i.replace(\"/term_sd_git_user/term_sd_git_repo\",\"\")\n", " mirror_url = i.replace(\"term_sd_git_user/term_sd_git_repo\",\"\")\n", " echo(f\"测试 Github 镜像源: {mirror_url}\")\n", " if os.path.exists(path):\n", " !rm -rf \"{path}\"\n", " result = subprocess.run(f\"git clone {test_repo} {path}\")\n", " if os.path.exists(path):\n", " !rm -rf \"{path}\"\n", " if result.returncode == 0:\n", " return avaliable_mirror\n", " return False\n", "\n", "\n", " def set_github_mirror(self, mirror):\n", " import os\n", " avaliable_mirror = self.test_github_mirror(mirror)\n", " git_config_path = self.WORKSPACE + \"/.gitconfig\"\n", " if avaliable_mirror is not False:\n", " echo(f\"设置 GIthub 镜像源: {avaliable_mirror}\")\n", " if os.path.exists(git_config_path):\n", " !rm -rf \"{git_config_path}\"\n", " os.environ[\"GIT_CONFIG_GLOBAL\"] = git_config_path\n", " !git config --global url.{avaliable_mirror}.insteadOf https://github.com\n", " else:\n", " echo(\"未找到可用 Github 镜像源, 取消设置 GIthub 镜像源\")\n", "\n", "\n", " def unset_github_mirror(self):\n", " import os\n", " if \"GIT_CONFIG_GLOBAL\" in os.environ:\n", " echo(\"删除 Github 镜像源配置\")\n", " os.unsetenv(\"GIT_CONFIG_GLOBAL\")\n", " else:\n", " echo(\"Github 镜像源未设置, 无需删除\")\n", "\n", "\n", "\n", "# TUNNEL\n", "class TUNNEL:\n", " LOCALHOST_RUN = \"localhost.run\"\n", " REMOTE_MOE = \"remote.moe\"\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", " PORT = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder, port) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", " self.PORT = port\n", "\n", "\n", " # ngrok内网穿透\n", " def ngrok(self, ngrok_token: str):\n", " from pyngrok import conf, ngrok\n", " conf.get_default().auth_token = ngrok_token\n", " conf.get_default().monitor_thread = False\n", " port = self.PORT\n", " ssh_tunnels = ngrok.get_tunnels(conf.get_default())\n", " if len(ssh_tunnels) == 0:\n", " ssh_tunnel = ngrok.connect(port, bind_tls=True)\n", " return ssh_tunnel.public_url\n", " else:\n", " return ssh_tunnels[0].public_url\n", "\n", "\n", " # cloudflare内网穿透\n", " def cloudflare(self):\n", " from pycloudflared import try_cloudflare\n", " port = self.PORT\n", " urls = try_cloudflare(port).tunnel\n", " return urls\n", "\n", "\n", " from typing import Union\n", " from pathlib import Path\n", "\n", " # 生成ssh密钥\n", " def gen_key(self, path: Union[str, Path]) -> None:\n", " import subprocess\n", " import shlex\n", " from pathlib import Path\n", " path = Path(path)\n", " arg_string = f'ssh-keygen -t rsa -b 4096 -N \"\" -q -f {path.as_posix()}'\n", " args = shlex.split(arg_string)\n", " subprocess.run(args, check=True)\n", " path.chmod(0o600)\n", "\n", "\n", " # ssh内网穿透\n", " def ssh_tunnel(self, host: str) -> None:\n", " import subprocess\n", " import atexit\n", " import shlex\n", " import re\n", " import os\n", " from pathlib import Path\n", " from tempfile import TemporaryDirectory\n", "\n", " ssh_name = \"id_rsa\"\n", " ssh_path = Path(self.WORKSPACE) / ssh_name\n", " port = self.PORT\n", "\n", " tmp = None\n", " if not ssh_path.exists():\n", " try:\n", " self.gen_key(ssh_path)\n", " # write permission error or etc\n", " except subprocess.CalledProcessError:\n", " tmp = TemporaryDirectory()\n", " ssh_path = Path(tmp.name) / ssh_name\n", " self.gen_key(ssh_path)\n", "\n", " arg_string = f\"ssh -R 80:127.0.0.1:{port} -o StrictHostKeyChecking=no -i {ssh_path.as_posix()} {host}\"\n", " args = shlex.split(arg_string)\n", "\n", " tunnel = subprocess.Popen(\n", " args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", " if tmp is not None:\n", " atexit.register(tmp.cleanup)\n", "\n", " tunnel_url = \"\"\n", " LOCALHOST_RUN = self.LOCALHOST_RUN\n", " lines = 27 if host == LOCALHOST_RUN else 5\n", " localhostrun_pattern = re.compile(r\"(?P<url>https?://\\S+\\.lhr\\.life)\")\n", " remotemoe_pattern = re.compile(r\"(?P<url>https?://\\S+\\.remote\\.moe)\")\n", " pattern = localhostrun_pattern if host == LOCALHOST_RUN else remotemoe_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", "\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " if lines == 27:\n", " os.environ['LOCALHOST_RUN'] = tunnel_url\n", " return tunnel_url\n", " else:\n", " os.environ['REMOTE_MOE'] = tunnel_url\n", " return tunnel_url\n", " # break\n", " else:\n", " echo(f\"启动 {host} 内网穿透失败\")\n", "\n", "\n", " # localhost.run穿透\n", " def localhost_run(self):\n", " urls = self.ssh_tunnel(self.LOCALHOST_RUN)\n", " return urls\n", "\n", "\n", " # remote.moe内网穿透\n", " def remote_moe(self):\n", " urls = self.ssh_tunnel(self.REMOTE_MOE)\n", " return urls\n", "\n", "\n", " # gradio内网穿透\n", " def gradio(self):\n", " import subprocess\n", " import shlex\n", " import atexit\n", " import re\n", " port = self.PORT\n", " cmd = f\"gradio-tunneling --port {port}\"\n", " cmd = shlex.split(cmd)\n", " tunnel = subprocess.Popen(\n", " cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\"\n", " )\n", "\n", " atexit.register(tunnel.terminate)\n", "\n", " tunnel_url = \"\"\n", " lines = 5\n", " gradio_pattern = re.compile(r\"(?P<url>https?://\\S+\\.gradio\\.live)\")\n", " pattern = gradio_pattern\n", "\n", " for _ in range(lines):\n", " line = tunnel.stdout.readline()\n", " if line.startswith(\"Warning\"):\n", " print(line, end=\"\")\n", " url_match = pattern.search(line)\n", " if url_match:\n", " tunnel_url = url_match.group(\"url\")\n", " return tunnel_url\n", " else:\n", " echo(f\"启动 Gradio 内网穿透失败\")\n", "\n", "\n", " # 启动内网穿透\n", " def start(self, ngrok=False, ngrok_token=None, cloudflare=False, remote_moe=False, localhost_run=False, gradio=False):\n", " if cloudflare is True or ngrok is True or ngrok_token is not None or remote_moe is True or localhost_run is True or gradio is True:\n", " echo(\"启动内网穿透\")\n", "\n", " if cloudflare is True:\n", " cloudflare_url = self.cloudflare()\n", " else:\n", " cloudflare_url = None\n", "\n", " if ngrok is True and ngrok_token is not None:\n", " ngrok_url = self.ngrok(ngrok_token)\n", " else:\n", " ngrok_url = None\n", "\n", " if remote_moe is True:\n", " remote_moe_url = self.remote_moe()\n", " else:\n", " remote_moe_url = None\n", "\n", " if localhost_run is True:\n", " localhost_run_url = self.localhost_run()\n", " else:\n", " localhost_run_url = None\n", "\n", " if gradio is True:\n", " gradio_url = self.gradio()\n", " else:\n", " gradio_url = None\n", "\n", " echo(\"下方为访问地址\")\n", " print(\"==================================================================================\")\n", " echo(f\"CloudFlare: {cloudflare_url}\")\n", " echo(f\"Ngrok: {ngrok_url}\")\n", " echo(f\"remote.moe: {remote_moe_url}\")\n", " echo(f\"localhost_run: {localhost_run_url}\")\n", " echo(f\"Gradio: {gradio_url}\")\n", " print(\"==================================================================================\")\n", "\n", "\n", "\n", "# ENV\n", "class ENV:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 准备ipynb笔记自身功能的依赖\n", " def prepare_env_depend(self, use_mirror=True):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " echo(\"安装自身组件依赖\")\n", " !pip install pyngrok pycloudflared gradio-tunneling {pip_mirror}\n", " !apt update\n", " !apt install aria2 ssh google-perftools -y\n", "\n", "\n", " # 安装pytorch和xformers\n", " def prepare_torch(self, torch_ver, xformers_ver, use_mirror=False):\n", " arg = \"--no-deps\"\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " \n", " if torch_ver != \"\":\n", " echo(\"安装 PyTorch\")\n", " !pip install {torch_ver} {pip_mirror}\n", " if xformers_ver != \"\":\n", " echo(\"安装 xFormers\")\n", " !pip install {xformers_ver} {pip_mirror} {arg}\n", "\n", "\n", " # 安装requirements.txt依赖\n", " def install_requirements(self, path, use_mirror=False):\n", " import os\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", " if os.path.exists(path):\n", " echo(\"安装依赖\")\n", " !pip install -r \"{path}\" {pip_mirror}\n", " else:\n", " echo(\"依赖文件路径为空\")\n", "\n", "\n", " # python软件包安装\n", " # 可使用的操作:\n", " # 安装: install -> install\n", " # 仅安装: install_single -> install --no-deps\n", " # 强制重装: force_install -> install --force-reinstall\n", " # 仅强制重装: force_install_single -> install --force-reinstall --no-deps\n", " # 更新: update -> install --upgrade\n", " # 卸载: uninstall -y\n", " def py_pkg_manager(self, pkg, type=None, use_mirror=False):\n", " if use_mirror is True:\n", " pip_mirror = \"--index-url https://mirrors.cloud.tencent.com/pypi/simple --find-links https://mirror.sjtu.edu.cn/pytorch-wheels/cu121/torch_stable.html\"\n", " else:\n", " pip_mirror = \"--index-url https://pypi.python.org/simple --find-links https://download.pytorch.org/whl/cu121/torch_stable.html\"\n", "\n", " if type == \"install\":\n", " func = \"install\"\n", " args = \"\"\n", " elif type == \"install_single\":\n", " func = \"install\"\n", " args = \"--no-deps\"\n", " elif type == \"force_install\":\n", " func = \"install\"\n", " args = \"--force-reinstall\"\n", " elif type == \"force_install_single\":\n", " func = \"install\"\n", " args = \"install --force-reinstall --no-deps\"\n", " elif type == \"update\":\n", " func = \"install\"\n", " args = \"--upgrade\"\n", " elif type == \"uninstall\":\n", " func = \"uninstall\"\n", " args = \"-y\"\n", " pip_mirror = \"\"\n", " else:\n", " echo(f\"未知操作: {type}\")\n", " return\n", " echo(f\"执行操作: pip {func} {pkg} {args} {pip_mirror}\")\n", " !pip {func} {pkg} {args} {pip_mirror}\n", "\n", "\n", " # 配置内存优化\n", " def tcmalloc(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " os.environ[\"LD_PRELOAD\"] = \"/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4\"\n", "\n", "\n", " # 适用于colab的内存优化\n", " def tcmalloc_colab(self):\n", " echo(\"配置内存优化\")\n", " import os\n", " aria2 = ARIA2(self.WORKSPACE, self.WORKFOLDER)\n", " path = self.WORKSPACE\n", " libtcmalloc_path = self.WORKSPACE + \"/libtcmalloc_minimal.so.4\"\n", " aria2.aria2(\"https://github.com/licyk/term-sd/releases/download/archive/libtcmalloc_minimal.so.4\", path, \"libtcmalloc_minimal.so.4\")\n", " os.environ[\"LD_PRELOAD\"] = libtcmalloc_path\n", "\n", "\n", "\n", "# MANAGER\n", "class MANAGER:\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 清理ipynb笔记的输出\n", " def clear_up(self, opt):\n", " from IPython.display import clear_output\n", " clear_output(wait=opt)\n", "\n", "\n", " # 检查gpu是否可用\n", " def check_gpu(self):\n", " echo(\"检测 GPU 是否可用\")\n", " import tensorflow as tf\n", " echo(f\"TensorFlow 版本: {tf.__version__}\")\n", " if tf.test.gpu_device_name():\n", " echo(\"GPU 可用\")\n", " else:\n", " echo(\"GPU 不可用\")\n", " raise Exception(\"\\n没有使用GPU,请在代码执行程序-更改运行时类型-设置为GPU!\\n如果不能使用GPU,建议更换账号!\")\n", "\n", "\n", " # 配置google drive\n", " def config_google_drive(self):\n", " echo(\"挂载 Google Drive\")\n", " import os\n", " if not os.path.exists('/content/drive/MyDrive'):\n", " from google.colab import drive\n", " drive.mount('/content/drive')\n", " echo(\"Google Dirve 挂载完成\")\n", " else:\n", " echo(\"Google Drive 已挂载\")\n", "\n", " # 检测并创建输出文件夹\n", " if os.path.exists('/content/drive/MyDrive'):\n", " if not os.path.exists('/content/drive/MyDrive/fooocus_output'):\n", " echo(\"在 Google Drive 创建 fooocus_ouput 文件夹\")\n", " !mkdir -p /content/drive/MyDrive/fooocus_output\n", " else:\n", " raise Exception(\"未挂载 Google Drive,请重新挂载后重试!\")\n", "\n", "\n", " def set_huggingface_mirror(self ,mirror):\n", " import os\n", " echo(f\"设置 HuggingFace 镜像源: {mirror}\")\n", " os.environ[\"HF_ENDPOINT\"] = mirror\n", "\n", "\n", " def unset_huggingface_mirror(self):\n", " import os\n", " if \"HF_ENDPOINT\" in os.environ:\n", " echo(\"删除 HuggingFace 镜像源配置\")\n", " os.unsetenv(\"HF_ENDPOINT\")\n", " else:\n", " echo(\"HuggingFace 镜像源未设置, 无需删除\")\n", "\n", "\n", " def hf_link_to_mirror_link(self, hf_mirror, url):\n", " if isinstance(url, str):\n", " return url.replace(\"https://huggingface.co\",hf_mirror)\n", " else:\n", " mirror_url = url\n", " j = 0\n", " for i in mirror_url:\n", " tmp = i.replace(\"https://huggingface.co\",hf_mirror)\n", " mirror_url[j] = tmp\n", " j += 1\n", " return mirror_url\n", "\n", "\n", " def select_list(self, data, name):\n", " # https://stackoverflow.com/questions/57219796/ipywidgets-dynamic-creation-of-checkboxes-and-selection-of-data\n", " # https://gist.github.com/MattJBritton/9dc26109acb4dfe17820cf72d82f1e6f\n", " import ipywidgets as widgets\n", " names = [] # 可选择的列表\n", " checkbox_objects = [] # 按钮对象\n", " for key in data:\n", " value = key[1]\n", " key = key[0].split(\"/\").pop()\n", " if value == 1:\n", " select = True\n", " else:\n", " select = False\n", " checkbox_objects.append(widgets.Checkbox(value=select, description=key, )) # 扩展按钮列表\n", " names.append(key)\n", "\n", " arg_dict = {names[i]: checkbox for i, checkbox in enumerate(checkbox_objects)}\n", "\n", " ui = widgets.VBox(children=checkbox_objects) # 创建widget\n", "\n", " selected_data = []\n", " select_value = [] # 存储每个模型选择情况\n", " url_list = [] # 地址列表\n", " def select_data(**kwargs): # 每次点击按钮时都会执行\n", " selected_data.clear()\n", " select_value.clear()\n", " for key in kwargs:\n", " if kwargs[key] is True:\n", " selected_data.append(key)\n", " select_value.append(True)\n", " else:\n", " select_value.append(False)\n", "\n", " list = \"\"\n", " for i in selected_data: # 已选择的模型列表(模型名称)\n", " list = f\"{list}\\n- {i}\"\n", " print(f\"已选择列表: {list}\")\n", " j = 0\n", " url_list.clear()\n", " for i in select_value: # 返回的地址列表\n", " if i is True:\n", " url_list.append(data[j][0])\n", " j += 1\n", "\n", " out = widgets.interactive_output(select_data, arg_dict)\n", " ui.children = [*ui.children, out]\n", " ui = widgets.Accordion(children=[ui,], titles=(name,))\n", " #display(ui, out)\n", " display(ui)\n", " return url_list\n", "\n", "\n", " def select_button(self, name, normal_value):\n", " import ipywidgets as widgets\n", " return widgets.Checkbox(\n", " value=normal_value,\n", " description=name,\n", " disabled=False,\n", " indent=False\n", " )\n", "\n", "\n", " def text_input(self, name, notice, normal_text=\"\"):\n", " import ipywidgets as widgets\n", " return widgets.Textarea(\n", " value=normal_text,\n", " placeholder=notice ,\n", " description=name,\n", " disabled=False\n", " )\n", "\n", "\n", " def dropdown(self, name, list, normal_value):\n", " import ipywidgets as widgets\n", " widgets.Dropdown(\n", " options=list,\n", " value=normal_value,\n", " description=name,\n", " disabled=False,\n", " )\n", "\n", "\n", "\n", "# FOOOCUS\n", "class FOOOCUS(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7865)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " # 下载大模型\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoints\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " # 下载lora模型\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " # 下载配置文件\n", " def install_config(self):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"下载配置文件\")\n", " self.aria2(\"https://github.com/licyk/term-sd/releases/download/archive/fooocus_config.json\", path + \"/presets\", \"custom.json\")\n", " self.aria2(\"https://github.com/licyk/term-sd/releases/download/archive/fooocus_zh_cn.json\", path + \"/language\", \"zh.json\")\n", "\n", "\n", " def install_config_colab(self):\n", " import os\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " path_config = path + \"/config.txt\"\n", " echo(\"下载路径配置文件\")\n", " if os.path.exists(path_config):\n", " !rm -rf \"{path_config}\"\n", " self.aria2(\"https://github.com/licyk/term-sd/releases/download/archive/fooocus_path_config_colab.json\", path, \"config.txt\")\n", "\n", "\n", " # 安装fooocus\n", " def install(self, torch_ver, xformers_ver, sd, lora, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/lllyasviel/Fooocus\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver, use_mirror)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements_versions.txt\"\n", " self.install_requirements(req_file, use_mirror)\n", " self.install_config()\n", " self.tcmalloc()\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", "\n", "\n", " def update(self):\n", " import os\n", " fooocus_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(fooocus_path)\n", "\n", "\n", "\n", "# INVOKEAI\n", "class INVOKEAI(ARIA2, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 9090)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/checkpoint\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_lora_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/loras\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_lora_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_lora_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_embedding_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/embeddings\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_embedding_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_embedding_model(i, i.split(\"/\").pop())\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/models/vae\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, lora, vae, embedding, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " os.mkdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(\"\", xformers_ver)\n", " self.py_pkg_manager(\"invokeai\", \"install\", use_mirror)\n", " self.tcmalloc()\n", " echo(\"下载模型\")\n", " self.get_sd_model_from_list(sd)\n", " self.get_lora_model_from_list(lora)\n", " self.get_vae_model_from_list(vae)\n", " self.get_embedding_model_from_list(embedding)\n", "\n", "\n", " def update(self):\n", " echo(\"更新 InvokeAI\")\n", " !pip install invokeai -U\n", "\n", "\n", "\n", "# SD_TRAINER\n", "class SD_TRAINER(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 28000)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install_kohya_requirements(self,use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts\")\n", " self.install_requirements(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts/requirements.txt\", use_mirror)\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, vae, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/Akegarasu/lora-scripts\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " # self.install_kohya_requirements(use_mirror)\n", " self.install_requirements(req_file, use_mirror)\n", " self.tcmalloc()\n", " self.get_sd_model_from_list(sd)\n", " self.get_vae_model_from_list(vae)\n", "\n", "\n", " def update(self):\n", " import os\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(sd_trainer_path)\n", "\n", "\n", " def get_core_ver(self):\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(sd_trainer_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(sd_trainer_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " sd_trainer_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"SD Trainer 版本:\")\n", " print(self.git_show_ver(sd_trainer_path))\n", "\n", "\n", "# KOHYA GUI\n", "class KOHYA_GUI(ARIA2, GIT, TUNNEL, MANAGER, ENV):\n", " WORKSPACE = \"\"\n", " WORKFOLDER = \"\"\n", "\n", " tun = TUNNEL(WORKSPACE, WORKFOLDER, 7860)\n", "\n", " def __init__(self, workspace, workfolder) -> None:\n", " self.WORKSPACE = workspace\n", " self.WORKFOLDER = workfolder\n", "\n", "\n", " def get_sd_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_vae_model(self, url, filename = None):\n", " path = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-models\"\n", " filename = url.split(\"/\").pop() if filename is None else filename\n", " super().aria2(url, path, filename)\n", "\n", "\n", " def get_sd_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_sd_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def get_vae_model_from_list(self, list):\n", " for i in list:\n", " if i != \"\":\n", " self.get_vae_model(i, i.split(\"/\").pop())\n", "\n", "\n", " def install_kohya_requirements(self,use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts\")\n", " self.install_requirements(self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/sd-scripts/requirements.txt\", use_mirror)\n", " os.chdir(self.WORKSPACE + \"/\" + self.WORKFOLDER)\n", "\n", "\n", " def install(self, torch_ver, xformers_ver, sd, vae, use_mirror):\n", " import os\n", " os.chdir(self.WORKSPACE)\n", " self.check_gpu()\n", " self.prepare_env_depend(use_mirror)\n", " self.clone(\"https://github.com/bmaltais/kohya_ss\", self.WORKSPACE)\n", " os.chdir(f\"{self.WORKSPACE}/{self.WORKFOLDER}\")\n", " self.prepare_torch(torch_ver, xformers_ver)\n", " req_file = self.WORKSPACE + \"/\" + self.WORKFOLDER + \"/requirements.txt\"\n", " # self.install_kohya_requirements(use_mirror)\n", " self.install_requirements(req_file, use_mirror)\n", " self.tcmalloc()\n", " self.get_sd_model_from_list(sd)\n", " self.get_vae_model_from_list(vae)\n", "\n", "\n", " def update(self):\n", " import os\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.pull(kohya_gui_path)\n", "\n", "\n", " def get_core_ver(self):\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " print(self.log(kohya_gui_path))\n", "\n", "\n", " def set_core_ver(self, commit):\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " self.checkout(kohya_gui_path, commit)\n", "\n", "\n", " def show_ver(self):\n", " import os\n", " kohya_gui_path = self.WORKSPACE + \"/\" + self.WORKFOLDER\n", " echo(\"Kohya_GUI 版本:\")\n", " print(self.git_show_ver(kohya_gui_path))\n", "\n", "\n", "echo(\"初始化功能完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "editable": true, "id": "Ry2HYOEE_yd6", "outputId": "087427b7-5c71-45c2-de3f-db49b8892c5c", "tags": [] }, "outputs": [], "source": [ "#@title 👇 参数配置\n", "try:\n", " i = INIT_CONFIG\n", " echo(\"尝试安装 ipywidgets 组件\")\n", " !pip install ipywidgets -qq\n", " from IPython.display import clear_output\n", " clear_output(wait=False)\n", " INIT_CONFIG_1 = 1\n", "except:\n", " raise Exception(\"未初始化功能\")\n", "\n", "import ipywidgets as widgets\n", "\n", "WEBUI = \"\"\n", "WORKSPACE = \"\"\n", "WORKFOLDER = \"\"\n", "USE_MIRROR = False\n", "USE_NGROK = True\n", "NGROK_TOKEN = \"\"\n", "USE_CLOUDFLARE = True\n", "USE_REMOTE_MOE = True\n", "USE_LOCALHOST_RUN = True\n", "USE_GRADIO_SHARE = False\n", "TORCH_VER = \"\"\n", "XFORMERS_VER = \"\"\n", "GITHUB_MIRROR = [\n", " \"https://ghproxy.net/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://mirror.ghproxy.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gh-proxy.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://ghps.cc/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gh.idayer.com/https://github.com/term_sd_git_user/term_sd_git_repo\",\n", " \"https://gitclone.com/github.com/term_sd_git_user/term_sd_git_repo\"\n", "]\n", "HUGGINGFACE_MIRROR = \"https://hf-mirror.com\"\n", "sd_model = [\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/Counterfeit-V3.0_fp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cetusMix_Whalefall2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/cuteyukimixAdorable_neochapter3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ekmix-pastel-fp16-no-ema.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/ex2K_sse2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/kohakuV5_rev2.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinamix_meinaV11.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/oukaStar_10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/pastelMixStylizedAnime_pastelMixPrunedFP16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/rabbit_v6.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/sweetSugarSyndrome_rev15.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/AnythingV5Ink_ink.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/bartstyledbBlueArchiveArtStyleFineTunedModel_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/meinapastel_v6Pastel.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/qteamixQ_omegaFp16.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/tmndMix_tmndMixSPRAINBOW.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/AnythingXL_xl.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/abyssorangeXLElse_v10.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animaPencilXL_v200.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/baxlBartstylexlBlueArchiveFlatCelluloid_xlv1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/nekorayxl_v06W3.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/CounterfeitXL-V1.0.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", 0]\n", "]\n", "lora = [\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_AnimeFace.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_Saturation.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_EdgeEmphasys.safetensors\", 0],\n", " [\"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/AnimagineXLV3_Style_Difference_bodyshadow.safetensors\", 0],\n", " [\"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors\", 0]\n", "]\n", "embedding = [\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/EasyNegative.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/EasyNegativeV2.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-artist-anime.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-artist.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-hands-5.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad-image-v2-39000.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/bad_prompt_version2.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/ng_deepnegative_v1_75t.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-embeddings/resolve/main/sd_1.5/verybadimagenegative_v1.3.pt\", 1]\n", "]\n", "vae = [\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", 1]\n", "]\n", "vae_approx = [\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/model.pt\", 1],\n", " [\"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sdxl.pt\", 1]\n", "]\n", "upscale = [\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x-UltraSharp.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/ESRGAN_4x.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", 0],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", 0],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", 1],\n", " [\"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", 1]\n", "]\n", "\n", "WEBUI_LIST = [\"fooocus\", \"invokeai\", \"sd_trainer\", \"kohya_gui\"]\n", "\n", "manager = MANAGER(WORKSPACE, WORKFOLDER)\n", "gi = GIT(WORKSPACE, WORKFOLDER)\n", "\n", "workspace_state = widgets.Textarea(value=\"/content\", placeholder=\"请输入工作区路径\", description=\"工作区路径: \", disabled=False)\n", "webui_state = widgets.Dropdown(options=WEBUI_LIST, value=\"fooocus\", description=\"使用的 WebUI: \", disabled=False)\n", "torch_ver_state = widgets.Textarea(value=\"torch==2.2.1+cu121 torchvision==0.17.1+cu121 torchaudio==2.2.1+cu121\", placeholder=\"请填写 PyTorch 版本\", description=\"PyTorch 版本: \", disabled=False)\n", "xformers_ver_state = widgets.Textarea(value=\"xformers==0.0.25\", placeholder=\"请填写 xFormers 版本\", description=\"xFormers 版本: \", disabled=False)\n", "use_mirror_state = widgets.Checkbox(value=False, description=\"使用镜像源\", disabled=False)\n", "is_colab_state = widgets.Checkbox(value=True, description=\"使用 Colab 环境\", disabled=False)\n", "use_ngrok_state = widgets.Checkbox(value=False, description=\"使用 Ngrok 内网穿透\", disabled=False)\n", "ngrok_token_state = widgets.Textarea(value=\"\", placeholder=\"请填写 Ngrok Token(可在 Ngrok 官网获取)\", description=\"Ngrok Token: \", disabled=False)\n", "use_cloudflare_state = widgets.Checkbox(value=False, description=\"使用 CloudFlare 内网穿透\", disabled=False)\n", "use_remote_moe_state = widgets.Checkbox(value=True, description=\"使用 remote.moe 内网穿透\", disabled=False)\n", "use_localhost_run_state = widgets.Checkbox(value=True, description=\"使用 localhost.run 内网穿透\", disabled=False)\n", "use_gradio_share_state = widgets.Checkbox(value=False, description=\"使用 Gradio 内网穿透\", disabled=False)\n", "display(workspace_state, webui_state, torch_ver_state, xformers_ver_state, use_mirror_state, use_ngrok_state, ngrok_token_state, use_cloudflare_state, use_remote_moe_state, use_localhost_run_state, use_gradio_share_state)\n", "\n", "\n", "sd_model_list = manager.select_list(sd_model,\"Stable Diffusion 模型\")\n", "lora_list = manager.select_list(lora, \"LoRA 模型\")\n", "embedding_list = manager.select_list(embedding, \"Embedding 模型\")\n", "vae_list = manager.select_list(vae, \"VAE 模型\")\n", "vae_approx_list = manager.select_list(vae_approx, \"VAE-approx 模型\")\n", "upscale_list = manager.select_list(upscale, \"放大模型\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "f3MUpZmT_yd8" }, "outputs": [], "source": [ "#@title 👇 应用参数配置\n", "try:\n", " i = INIT_CONFIG_1\n", " INIT_CONFIG_1 = 1\n", " INIT_CONFIG_2 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数配置\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE)\n", "WORKSPACE = workspace_state.value.rstrip(\"/\").rstrip(\"\\\\\")\n", "WEBUI = webui_state.value\n", "TORCH_VER = torch_ver_state.value\n", "XFORMERS_VER = xformers_ver_state.value\n", "USE_MIRROR = use_mirror_state.value\n", "IS_COLAB = is_colab_state.value\n", "USE_NGROK = use_ngrok_state.value\n", "NGROK_TOKEN = ngrok_token_state.value\n", "USE_CLOUDFLARE = use_cloudflare_state.value\n", "USE_REMOTE_MOE = use_remote_moe_state.value\n", "USE_LOCALHOST_RUN = use_localhost_run_state.value\n", "USE_GRADIO_SHARE = use_gradio_share_state.value\n", "\n", "if WORKSPACE != \"\":\n", " if WEBUI == \"fooocus\":\n", " WORKFOLDER = \"Fooocus\"\n", " fooocus = FOOOCUS(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"invokeai\":\n", " WORKFOLDER = \"InvokeAI\"\n", " invokeai = INVOKEAI(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"sd_trainer\":\n", " WORKFOLDER = \"lora-scripts\"\n", " sd_trainer = SD_TRAINER(WORKSPACE, WORKFOLDER)\n", " elif WEBUI == \"kohya_gui\":\n", " WORKFOLDER = \"kohya_ss\"\n", " kohya_gui = KOHYA_GUI(WORKSPACE, WORKFOLDER)\n", "else:\n", " raise Exception(\"未填写工作区路径\")\n", "\n", "manager = MANAGER(WORKSPACE, WORKFOLDER)\n", "\n", "if USE_MIRROR:\n", " sd_model = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, sd_model_list)\n", " lora = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, lora_list)\n", " embedding = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, embedding_list)\n", " vae = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, vae_list)\n", " vae_approx = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, vae_approx_list)\n", " upscale = manager.hf_link_to_mirror_link(HUGGINGFACE_MIRROR, upscale_list)\n", " manager.set_huggingface_mirror(HUGGINGFACE_MIRROR)\n", " gi.set_github_mirror(GITHUB_MIRROR)\n", "echo(\"参数设置完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "0wKZt0Ca_yd9" }, "outputs": [], "source": [ "#@title 👇 安装\n", "try:\n", " i = INIT_CONFIG_2\n", " INIT_CONFIG_2 = 1\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"参数设置\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE)\n", "echo(f\"开始安装 {WEBUI}\")\n", "if WEBUI == \"fooocus\":\n", " fooocus.install(TORCH_VER, XFORMERS_VER, sd_model_list, lora_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " fooocus.tcmalloc_colab()\n", " fooocus.install_config_colab()\n", "elif WEBUI == \"invokeai\":\n", " invokeai.install(TORCH_VER, XFORMERS_VER, sd_model_list, lora_list, vae_list, embedding_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " fooocus.tcmalloc_colab()\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.install(TORCH_VER, XFORMERS_VER, sd_model_list, vae_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " sd_trainer.tcmalloc_colab()\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.install(TORCH_VER, XFORMERS_VER, sd_model_list, vae_list, USE_MIRROR)\n", " if IS_COLAB is True:\n", " kohya_gui.tcmalloc_colab()\n", "manager.clear_up(False)\n", "echo(f\"{WEBUI} 安装完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "iKZbtmP1_yd_" }, "outputs": [], "source": [ "#@title 👇 启动\n", "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "echo(f\"启动 {WEBUI}\")\n", "if WEBUI == \"fooocus\":\n", " fooocus.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=False)\n", " if USE_GRADIO_SHARE:\n", " !python \"{WORKSPACE}\"/Fooocus/launch.py --preset custom --language zh --disable-offload-from-vram --async-cuda-allocation --share\n", " else:\n", " !python \"{WORKSPACE}\"/Fooocus/launch.py --preset custom --language zh --disable-offload-from-vram --async-cuda-allocation\n", "elif WEBUI == \"invokeai\":\n", " invokeai.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=False)\n", " if USE_GRADIO_SHARE:\n", " !invokeai-web --root \"{WORKSPACE}\"/InvokeAI/invokeai\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=False)\n", " !python \"{WORKSPACE}\"/lora-scripts/gui.py\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.tun.start(ngrok=USE_NGROK, ngrok_token=NGROK_TOKEN, cloudflare=USE_CLOUDFLARE, remote_moe=USE_REMOTE_MOE, localhost_run=USE_LOCALHOST_RUN, gradio=False)\n", " if USE_GRADIO_SHARE:\n", " !python \"{WORKSPACE}\"/kohya_ss/kohya_gui.py --language zh-CN --share\n", " else:\n", " !python \"{WORKSPACE}\"/kohya_ss/kohya_gui.py --language zh-CN\n", "manager.clear_up(False)\n", "echo(f\"{WEBUI} 已关闭\")" ] }, { "cell_type": "markdown", "metadata": { "id": "C7GxnRN4_yd_" }, "source": [ "##✨ 其他功能" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "25Gcy5jO_yeB" }, "outputs": [], "source": [ "#@title 👇 自定义模型 / 扩展下载配置\n", "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", " INIT_CONFIG_4 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import ipywidgets as widgets\n", "\n", "model_ = widgets.Textarea(\n", " value=\"\",\n", " placeholder='请填写模型 / 扩展下载链接',\n", " description='模型 / 扩展下载链接: ',\n", " disabled=False\n", ")\n", "\n", "model_name_ = widgets.Textarea(\n", " value=\"\",\n", " placeholder='请填写模型名称',\n", " description='模型名称: ',\n", " disabled=False\n", ")\n", "\n", "model_type_ = widgets.Dropdown(\n", " options=[(\"Stable Diffusion 模型(大模型)\", \"sd\"),\n", " (\"LoRA 模型\", \"lora\"),\n", " (\"Emebdding 模型\", \"embedding\"),\n", " (\"VAE 模型\", \"vae\"),\n", " (\"VAE-approx 模型\", \"vae-approx\"),\n", " (\"放大模型\", \"upscale\"),\n", " (\"ControlNet 模型\", \"controlnet\"),\n", " (\"SD WebUI 扩展\", \"extension\"),\n", " (\"ComfyUI 扩展\", \"custom_node\")\n", " ],\n", " value=\"sd\",\n", " description='模型 / 扩展种类',\n", ")\n", "\n", "display(model_, model_name_, model_type_)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "33RPATJT_yeB" }, "outputs": [], "source": [ "#@title 👇 自定义模型 / 扩展下载\n", "try:\n", " i = INIT_CONFIG_4\n", "except:\n", " raise Exception(\"未运行\\\"自定义模型 / 扩展下载配置\\\"单元\")\n", "\n", "model = model_.value\n", "model_name = model_name_.value\n", "model_type = model_type_.value\n", "\n", "if model == \"\" and model_name == \"\":\n", " raise Exception(\"未填写模型 / 扩展链接或者模型名称\")\n", "\n", "\n", "if WEBUI == \"invokeai\":\n", " if model_type == \"sd\":\n", " invokeai.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " invokeai.get_lora_model(model, model_name)\n", " if model_type == \"embedding\":\n", " invokeai.get_embedding_model(model, model_name)\n", " if model_type == \"vae\":\n", " invokeai.get_vae_model(model, model_name)\n", "elif WEBUI == \"fooocus\":\n", " if model_type == \"sd\":\n", " fooocus.get_sd_model(model, model_name)\n", " if model_type == \"lora\":\n", " fooocus.get_lora_model(model, model_name)\n", "elif WEBUI == \"sd_trainer\":\n", " if model_type == \"sd\":\n", " sd_trainer.get_sd_model(model, model_name)\n", " if model_type == \"vae\":\n", " sd_trainer.get_vae_model(model, model_name)\n", "elif WEBUI == \"kohya_gui\":\n", " if model_type == \"sd\":\n", " kohya_gui.get_sd_model(model, model_name)\n", " if model_type == \"vae\":\n", " kohya_gui.get_vae_model(model, model_name)\n", "else:\n", " raise Exception(f\"未知软件类型 {WEBUI}\")\n", "\n", "echo(f\"{WEBUI} 模型文件扩展下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "UT_eaCug_yeB" }, "outputs": [], "source": [ "#@title 👇 更新\n", "try:\n", " i = INIT_CONFIG_3\n", " INIT_CONFIG_3 = 1\n", "except:\n", " raise Exception(\"未运行\\\"安装\\\"单元\")\n", "\n", "import os\n", "os.chdir(WORKSPACE + \"/\" + WORKFOLDER)\n", "echo(f\"启动 {WEBUI}\")\n", "if WEBUI == \"fooocus\":\n", " fooocus.update()\n", "elif WEBUI == \"invokeai\":\n", " invokeai.update()\n", "elif WEBUI == \"sd_trainer\":\n", " sd_trainer.update()\n", "elif WEBUI == \"kohya_gui\":\n", " kohya_gui.update()\n", "echo(f\"更新 {WEBUI} 完成\")" ] } ], "metadata": { "colab": { "collapsed_sections": [ "C7GxnRN4_yd_" ], "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/sd_webui_all_in_one_colab.ipynb
Jupyter Notebook
agpl-3.0
79,342
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xlyptNJ2ICnN" }, "source": [ "# Stable Diffusion WebUI Colab\n", "Colab NoteBook Created by [licyk](https://github.com/licyk)\n", "\n", "Jupyter Notebook 仓库:[licyk/sd-webui-all-in-one](https://github.com/licyk/sd-webui-all-in-one)\n", "\n", "这是适用于 [Colab](https://colab.research.google.com) 部署 [Stable-Diffusion-WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) / [Stable-Diffusion-WebUI-Forge](https://github.com/lllyasviel/stable-diffusion-webui-forge) / [Stable-Diffusion-WebUI-reForge](https://github.com/Panchovix/stable-diffusion-webui-reForge) / [Stable-Diffusion-WebUI-Forge-Classic](https://github.com/Haoming02/sd-webui-forge-classic) / [Stable-Diffusion-WebUI-AMDGPU](https://github.com/lshqqytiger/stable-diffusion-webui-amdgpu) / [SD.Next](https://github.com/vladmandic/sdnext) 的 Jupyter Notebook,使用时请按顺序执行 Jupyter Notebook 单元。\n", "\n", "Colab 链接:<a href=\"https://colab.research.google.com/github/licyk/sd-webui-all-in-one/blob/main/notebook/stable_diffusion_webui_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "\n", "## 功能\n", "1. 环境配置:配置安装的 PyTorch 版本、内网穿透的方式,并安装 Stable Diffusion WebUI。默认设置下已启用`配置环境完成后立即启动 Stable Diffusion WebUI`选项,则安装完成后将直接启动 Stable Diffusion WebUI,并显示访问地址。\n", "2. 下载模型:下载可选列表中的模型(可选)。\n", "3. 自定义模型下载:使用链接下载模型(可选)。\n", "4. 扩展下载:使用链接下载扩展(可选)。\n", "5. 启动 Stable Diffusion WebUI:启动 Stable Diffusion WebUI,并显示访问地址。\n", "\n", "\n", "## 使用\n", "1. 在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择`GPU T4`或者其他 GPU。\n", "2. `环境配置`单元中的选项通常不需要修改,保持默认即可。如需切换其他 Stable Diffusion WebUI 分支,可修改`环境配置`单元中的`Stable Diffusion WebUI 分支预设`选项。\n", "3. 运行`环境配置`单元,默认设置下已启用`配置环境完成后立即启动 Stable Diffusion WebUI`选项,则环境配置完成后立即启动 Stable Diffusion WebUI,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 Stable Diffusion WebUI,Stable Diffusion WebUI 的访问地址可在日志中查看。\n", "4. 如果未启用`配置环境完成后立即启动 Stable Diffusion WebUI`选项,需要运行`启动 Stable Diffusion WebUI`单元,此时将弹出 Google Drive 授权页面,根据提示进行操作。配置完成后将启动 Stable Diffusion WebUI,Stable Diffusion WebUI 的访问地址可在日志中查看。\n", "5. 提示词查询工具:[SD 绘画提示词查询](https://licyk.github.io/t/tag)\n", "\n", "\n", "## 提示\n", "1. Colab 在关机后将会清除所有数据,所以每次重新启动时必须运行`环境配置`单元才能运行`启动 Stable Diffusion WebUI`单元。\n", "2. [Ngrok](https://ngrok.com) 内网穿透在使用前需要填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取。\n", "3. [Zrok](https://zrok.io) 内网穿透在使用前需要填写 Zrok Token, 可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取。\n", "4. 每次启动 Colab 后必须运行`环境配置`单元,才能运行`启动 Stable Diffusion WebUI`单元启动 Stable Diffusion WebUI。\n", "5. 其他功能有自定义模型下载等功能,根据自己的需求进行使用。\n", "6. 运行`启动 Stable Diffusion WebUI`时将弹出 Google Drive 访问授权提示,根据提示进行授权。授权后,使用 Stable Diffusion WebUI 生成的图片将保存在 Google Drive 的`sd_webui_output`文件夹中。\n", "7. 在`额外挂载目录设置`中可以挂载一些额外目录,如 LoRA 模型目录,挂载后的目录可在 Google Drive 的`sd_webui_output`文件夹中查看和修改。可通过该功能在 Google Drive 上传模型并在 Stable Diffusion WebUI 中使用。\n", "8. 默认挂载以下目录到 Google Drive,可在 Google Drive 的`sd_webui_output`文件夹中上传和修改文件:`outputs`, `config_states`, `params.txt`, `config.json`, `ui-config.json`, `styles.csv`\n", "9. Stable Diffusion WebUI 使用教程可阅读:</br>[SD WebUI 部署与使用 - SD Note](https://sdnote.netlify.app/guide/sd_webui)</br>[SD WebUI Forge 部署与使用 - SD Note](https://sdnote.netlify.app/guide/sd_webui_forge)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "VjYy0F2gZIPR" }, "outputs": [], "source": [ "#@title 👇 环境配置\n", "# SD WebUI All In One 功能初始化部分, 通常不需要修改\n", "# 如果需要查看完整代码实现, 可阅读: https://github.com/licyk/sd-webui-all-in-one/blob/main/sd_webui_all_in_one\n", "#################################################################################################################\n", "# SD_WEBUI_ALL_IN_ONE_URL, FORCE_DOWNLOAD_CORE 参数可根据需求修改, 通常保持默认即可\n", "SD_WEBUI_ALL_IN_ONE_URL = \"https://github.com/licyk/sd-webui-all-in-one@main\" # SD WebUI All In One 核心下载地址\n", "FORCE_DOWNLOAD_CORE = False # 设置为 True 时, 即使 SD WebUI All In One 已存在也会重新下载\n", "#################################################################################################################\n", "import os\n", "import sys\n", "from pathlib import Path\n", "try:\n", " _ = JUPYTER_ROOT_PATH # type: ignore # noqa: F821\n", "except Exception:\n", " JUPYTER_ROOT_PATH = os.getcwd()\n", "!python -c \"import sd_webui_all_in_one\" &> /dev/null && [ \"{FORCE_DOWNLOAD_CORE}\" != \"True\" ] || python -m pip install \"git+{SD_WEBUI_ALL_IN_ONE_URL}\"\n", "from sd_webui_all_in_one import logger, VERSION, SDWebUIManager\n", "logger.info(\"SD WebUI All In One 核心模块初始化完成, 版本: %s\", VERSION)\n", "\n", "#######################################################\n", "\n", "# Stable Diffusion WebUI 分支预设\n", "SD_WEBUI_BRANCH_PRESET_DICT = {\n", " \"AUTOMATIC1111/Stable-Diffusion-WebUI 主分支\": {\n", " \"url\": \"https://github.com/AUTOMATIC1111/stable-diffusion-webui\",\n", " \"branch\": \"master\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-load-model-at-start --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"AUTOMATIC1111/Stable-Diffusion-WebUI 测试分支\": {\n", " \"url\": \"https://github.com/AUTOMATIC1111/stable-diffusion-webui\",\n", " \"branch\": \"dev\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-load-model-at-start --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"lllyasviel/Stable-Diffusion-WebUI-Forge 分支\": {\n", " \"url\": \"https://github.com/lllyasviel/stable-diffusion-webui-forge\",\n", " \"branch\": \"main\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_forge_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"Panchovix/Stable-Diffusion-WebUI-reForge 主分支\": {\n", " \"url\": \"https://github.com/Panchovix/stable-diffusion-webui-reForge\",\n", " \"branch\": \"main\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"Panchovix/Stable-Diffusion-WebUI-reForge 测试分支\": {\n", " \"url\": \"https://github.com/Panchovix/stable-diffusion-webui-reForge\",\n", " \"branch\": \"dev\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"Haoming02/Stable-Diffusion-WebUI-Forge-Classic 分支\": {\n", " \"url\": \"https://github.com/Haoming02/sd-webui-forge-classic\",\n", " \"branch\": \"classic\",\n", " \"requirements\": \"requirements.txt\",\n", " \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_forge_classic_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"Haoming02/Stable-Diffusion-WebUI-Forge-Neo 分支\": {\n", " \"url\": \"https://github.com/Haoming02/sd-webui-forge-classic\",\n", " \"branch\": \"neo\",\n", " \"requirements\": \"requirements.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --xformers --api --skip-python-version-check --skip-version-check --enable-insecure-extension-access\",\n", " },\n", " \"lshqqytiger/Stable-Diffusion-WebUI-AMDGPU 分支\": {\n", " \"url\": \"https://github.com/lshqqytiger/stable-diffusion-webui-amdgpu\",\n", " \"branch\": \"master\",\n", " \"requirements\": \"requirements_versions.txt\",\n", " \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--theme dark --api --skip-torch-cuda-test --skip-python-version-check --skip-version-check --no-download-sd-model --enable-insecure-extension-access\",\n", " },\n", " \"vladmandic/SD.NEXT 主分支\": {\n", " \"url\": \"https://github.com/vladmandic/sdnext\",\n", " \"branch\": \"master\",\n", " \"requirements\": \"requirements.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--use-cuda --use-xformers --enable_insecure_extension_access\",\n", " },\n", " \"vladmandic/SD.NEXT 测试分支\": {\n", " \"url\": \"https://github.com/vladmandic/sdnext\",\n", " \"branch\": \"dev\",\n", " \"requirements\": \"requirements.txt\",\n", " # \"requirements_url\": \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_requirements_versions.txt\",\n", " \"launch_args\": \"--use-cuda --use-xformers --enable_insecure_extension_access\",\n", " },\n", "}\n", "\n", "#@markdown ## Stable Diffusion WebUI 核心配置选项\n", "#@markdown - Stable Diffusion WebUI 分支预设:\n", "SD_WEBUI_BRANCH_PRESET = \"lllyasviel/Stable-Diffusion-WebUI-Forge 分支\" # @param [\"AUTOMATIC1111/Stable-Diffusion-WebUI 主分支\", \"AUTOMATIC1111/Stable-Diffusion-WebUI 测试分支\", \"lllyasviel/Stable-Diffusion-WebUI-Forge 分支\", \"Panchovix/Stable-Diffusion-WebUI-reForge 主分支\", \"Panchovix/Stable-Diffusion-WebUI-reForge 测试分支\", \"Haoming02/Stable-Diffusion-WebUI-Forge-Classic 分支\", \"Haoming02/Stable-Diffusion-WebUI-Forge-Neo 分支\", \"lshqqytiger/Stable-Diffusion-WebUI-AMDGPU 分支\", \"vladmandic/SD.NEXT 主分支\", \"vladmandic/SD.NEXT 测试分支\"]\n", "#@markdown - Stable Diffusion WebUI 启动预设文件地址:\n", "SD_WEBUI_SETTING = \"https://github.com/licyk/sd-webui-all-in-one/raw/main/config/sd_webui_config.json\" #@param {type:\"string\"}\n", "#@markdown - Stable Diffusion WebUI 分支仓库地址(可选,不填则使用分支预设值):\n", "SD_WEBUI_REPO_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - Stable Diffusion WebUI 分支(可选,不填则使用分支预设值):\n", "SD_WEBUI_BRANCH_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - Stable Diffusion WebUI 依赖表名(可选,不填则使用分支预设值):\n", "SD_WEBUI_REQUIREMENTS_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - Stable Diffusion WebUI 启动参数(可选,不填则使用分支预设值):\n", "SD_WEBUI_LAUNCH_ARGS_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown - Stable Diffusion WebUI 新依赖表下载地址(可选,不填则使用分支预设值):\n", "SD_WEBUI_REQUIREMENTS_URL_OPT = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## PyTorch 组件版本选项:\n", "#@markdown - PyTorch:\n", "PYTORCH_VER = \"torch==2.8.0+cu126 torchvision==0.23.0+cu126 torchaudio==2.8.0+cu126\" #@param {type:\"string\"}\n", "#@markdown - xFormers:\n", "XFORMERS_VER = \"xformers==0.0.32.post2\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 包管理器选项:\n", "#@markdown - 使用 uv 作为 Python 包管理器\n", "USE_UV = True #@param {type:\"boolean\"}\n", "#@markdown - PyPI 主镜像源\n", "PIP_INDEX_MIRROR = \"https://pypi.python.org/simple\" #@param {type:\"string\"}\n", "#@markdown - PyPI 扩展镜像源\n", "PIP_EXTRA_INDEX_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown - PyPI 额外镜像源\n", "PIP_FIND_LINKS_MIRROR = \"https://licyk.github.io/t/pypi/index_hf.html\" #@param {type:\"string\"}\n", "#@markdown - PyTorch 镜像源\n", "PYTORCH_MIRROR = \"https://download.pytorch.org/whl/cu126\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 内网穿透选项:\n", "#@markdown - 使用 remote.moe 内网穿透\n", "USE_REMOTE_MOE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 localhost.run 内网穿透\n", "USE_LOCALHOST_RUN = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 pinggy.io 内网穿透\n", "USE_PINGGY_IO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 CloudFlare 内网穿透\n", "USE_CLOUDFLARE = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Gradio 内网穿透\n", "USE_GRADIO = True #@param {type:\"boolean\"}\n", "#@markdown - 使用 Ngrok 内网穿透(需填写 Ngrok Token,可在 [Ngrok](https://ngrok.com) 官网获取)\n", "USE_NGROK = True #@param {type:\"boolean\"}\n", "#@markdown - Ngrok Token\n", "NGROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown - 使用 Zrok 内网穿透(需填写 Zrok Token,可在 [Zrok](https://docs.zrok.io/docs/getting-started) 官网获取)\n", "USE_ZROK = True #@param {type:\"boolean\"}\n", "#@markdown - Zrok Token\n", "ZROK_TOKEN = \"\" #@param {type:\"string\"}\n", "#@markdown ---\n", "#@markdown ## 快速启动选项:\n", "#@markdown - 配置环境完成后立即启动 Stable Diffusion WebUI(并挂载 Google Drive)\n", "QUICK_LAUNCH = True #@param {type:\"boolean\"}\n", "#@markdown - 不重复配置环境(当重复运行环境配置时将不会再进行安装)\n", "NO_REPEAT_CONFIGURE_ENV = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "#@markdown ## 其他选项:\n", "#@markdown - 清理无用日志\n", "CLEAR_LOG = True #@param {type:\"boolean\"}\n", "#@markdown - 检查可用 GPU\n", "CHECK_AVALIABLE_GPU = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 TCMalloc 内存优化\n", "ENABLE_TCMALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 启用 CUDA Malloc 显存优化\n", "ENABLE_CUDA_MALLOC = True #@param {type:\"boolean\"}\n", "#@markdown - 更新内核和扩展\n", "UPDATE_CORE = True #@param {type:\"boolean\"}\n", "\n", "# 预设参数处理\n", "SD_WEBUI_REPO = SD_WEBUI_REPO_OPT or SD_WEBUI_BRANCH_PRESET_DICT.get(SD_WEBUI_BRANCH_PRESET).get(\"url\")\n", "SD_WEBUI_BRANCH = SD_WEBUI_BRANCH_OPT or SD_WEBUI_BRANCH_PRESET_DICT.get(SD_WEBUI_BRANCH_PRESET).get(\"branch\")\n", "SD_WEBUI_REQUIREMENTS = SD_WEBUI_REQUIREMENTS_OPT or SD_WEBUI_BRANCH_PRESET_DICT.get(SD_WEBUI_BRANCH_PRESET).get(\"requirements\")\n", "SD_WEBUI_LAUNCH_ARGS = SD_WEBUI_LAUNCH_ARGS_OPT or SD_WEBUI_BRANCH_PRESET_DICT.get(SD_WEBUI_BRANCH_PRESET).get(\"launch_args\")\n", "SD_WEBUI_REQUIREMENTS_URL = SD_WEBUI_REQUIREMENTS_URL_OPT or SD_WEBUI_BRANCH_PRESET_DICT.get(SD_WEBUI_BRANCH_PRESET).get(\"requirements_url\")\n", "\n", "# @markdown ---\n", "#######################################################\n", "# @markdown ## 扩展设置, 在安装时将会下载选择的扩展:\n", "EXTENSION_LIST = []\n", "\n", "ultimate_upscale_for_automatic1111 = True # @param {type:\"boolean\"}\n", "a1111_sd_webui_tagcomplete = True # @param {type:\"boolean\"}\n", "adetailer = True # @param {type:\"boolean\"}\n", "sd_webui_infinite_image_browsing = True # @param {type:\"boolean\"}\n", "sd_webui_openpose_editor = True # @param {type:\"boolean\"}\n", "sd_webui_prompt_all_in_one = True # @param {type:\"boolean\"}\n", "sd_webui_wd14_tagger = True # @param {type:\"boolean\"}\n", "stable_diffusion_webui_localization_zh_hans = True # @param {type:\"boolean\"}\n", "sd_webui_mosaic_outpaint = True # @param {type:\"boolean\"}\n", "sd_webui_resource_monitor = True # @param {type:\"boolean\"}\n", "sd_webui_tcd_sampler = True # @param {type:\"boolean\"}\n", "advanced_euler_sampler_extension = True # @param {type:\"boolean\"}\n", "sd_webui_regional_prompter = True # @param {type:\"boolean\"}\n", "sd_webui_model_converter = True # @param {type:\"boolean\"}\n", "sd_webui_controlnet = False # @param {type:\"boolean\"}\n", "multidiffusion_upscaler_for_automatic1111 = False # @param {type:\"boolean\"}\n", "sd_dynamic_thresholding = False # @param {type:\"boolean\"}\n", "sd_webui_lora_block_weight = False # @param {type:\"boolean\"}\n", "stable_diffusion_webui_model_toolkit = False # @param {type:\"boolean\"}\n", "a1111_sd_webui_haku_img = True # @param {type:\"boolean\"}\n", "sd_webui_supermerger = False # @param {type:\"boolean\"}\n", "sd_webui_segment_anything = False # @param {type:\"boolean\"}\n", "sd_forge_hypertile_svd_z123 = True # @param {type:\"boolean\"}\n", "sd_forge_layerdiffuse = True # @param {type:\"boolean\"}\n", "sd_webui_licyk_style_image = True # @param {type:\"boolean\"}\n", "sdwebui_close_confirmation_dlalogue = True # @param {type:\"boolean\"}\n", "stable_diffusion_webui_zoomimage = True # @param {type:\"boolean\"}\n", "\n", "ultimate_upscale_for_automatic1111 and EXTENSION_LIST.append(\"https://github.com/Coyote-A/ultimate-upscale-for-automatic1111\")\n", "a1111_sd_webui_tagcomplete and EXTENSION_LIST.append(\"https://github.com/DominikDoom/a1111-sd-webui-tagcomplete\")\n", "adetailer and EXTENSION_LIST.append(\"https://github.com/Bing-su/adetailer\")\n", "sd_webui_infinite_image_browsing and EXTENSION_LIST.append(\"https://github.com/zanllp/sd-webui-infinite-image-browsing\")\n", "sd_webui_openpose_editor and EXTENSION_LIST.append(\"https://github.com/huchenlei/sd-webui-openpose-editor\")\n", "sd_webui_prompt_all_in_one and EXTENSION_LIST.append(\"https://github.com/Physton/sd-webui-prompt-all-in-one\")\n", "sd_webui_wd14_tagger and EXTENSION_LIST.append(\"https://github.com/licyk/sd-webui-wd14-tagger\")\n", "stable_diffusion_webui_localization_zh_hans and EXTENSION_LIST.append(\"https://github.com/hanamizuki-ai/stable-diffusion-webui-localization-zh_Hans\")\n", "sd_webui_mosaic_outpaint and EXTENSION_LIST.append(\"https://github.com/Haoming02/sd-webui-mosaic-outpaint\")\n", "sd_webui_resource_monitor and EXTENSION_LIST.append(\"https://github.com/Haoming02/sd-webui-resource-monitor\")\n", "sd_webui_tcd_sampler and EXTENSION_LIST.append(\"https://github.com/licyk/sd-webui-tcd-sampler\")\n", "advanced_euler_sampler_extension and EXTENSION_LIST.append(\"https://github.com/licyk/advanced_euler_sampler_extension\")\n", "sd_webui_regional_prompter and EXTENSION_LIST.append(\"https://github.com/hako-mikan/sd-webui-regional-prompter\")\n", "sd_webui_model_converter and EXTENSION_LIST.append(\"https://github.com/Akegarasu/sd-webui-model-converter\")\n", "sd_webui_controlnet and EXTENSION_LIST.append(\"https://github.com/Mikubill/sd-webui-controlnet\")\n", "multidiffusion_upscaler_for_automatic1111 and EXTENSION_LIST.append(\"https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111\")\n", "sd_dynamic_thresholding and EXTENSION_LIST.append(\"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding\")\n", "sd_webui_lora_block_weight and EXTENSION_LIST.append(\"https://github.com/hako-mikan/sd-webui-lora-block-weight\")\n", "stable_diffusion_webui_model_toolkit and EXTENSION_LIST.append(\"https://github.com/arenasys/stable-diffusion-webui-model-toolkit\")\n", "a1111_sd_webui_haku_img and EXTENSION_LIST.append(\"https://github.com/licyk/a1111-sd-webui-haku-img\")\n", "sd_webui_supermerger and EXTENSION_LIST.append(\"https://github.com/hako-mikan/sd-webui-supermerger\")\n", "sd_webui_segment_anything and EXTENSION_LIST.append(\"https://github.com/continue-revolution/sd-webui-segment-anything\")\n", "sd_forge_hypertile_svd_z123 and EXTENSION_LIST.append(\"https://github.com/licyk/sd_forge_hypertile_svd_z123\")\n", "sd_forge_layerdiffuse and EXTENSION_LIST.append(\"https://github.com/lllyasviel/sd-forge-layerdiffuse\")\n", "sd_webui_licyk_style_image and EXTENSION_LIST.append(\"https://github.com/licyk/sd-webui-licyk-style-image\")\n", "sdwebui_close_confirmation_dlalogue and EXTENSION_LIST.append(\"https://github.com/w-e-w/sdwebui-close-confirmation-dialogue\")\n", "stable_diffusion_webui_zoomimage and EXTENSION_LIST.append(\"https://github.com/viyiviyi/stable-diffusion-webui-zoomimage\")\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 模型设置, 在安装时将会下载选择的模型:\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = True # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = True # @param {type:\"boolean\"}\n", "# @markdown - VAE Approx 模型\n", "vae_approx_model = True # @param {type:\"boolean\"}\n", "vae_approx_sdxl = True # @param {type:\"boolean\"}\n", "vae_approx_sd3 = True # @param {type:\"boolean\"}\n", "# @markdown - 放大模型\n", "upscale_dat_x2 = False # @param {type:\"boolean\"}\n", "upscale_dat_x3 = False # @param {type:\"boolean\"}\n", "upscale_dat_x4 = True # @param {type:\"boolean\"}\n", "upscale_4x_nmkd_superscale_sp_178000_g = False # @param {type:\"boolean\"}\n", "upscale_8x_nmkd_superscale_150000_g = False # @param {type:\"boolean\"}\n", "upscale_lollypop = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus_anime_6b = True # @param {type:\"boolean\"}\n", "upscale_swinir_4x = False # @param {type:\"boolean\"}\n", "# @markdown - ControlNet 模型\n", "illustriousxlcanny_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineart_v10 = False # @param {type:\"boolean\"}\n", "illustriousxldepth_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlsoftedge_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineartrrealistic_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlshuffle_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlopenpose_v10 = False # @param {type:\"boolean\"}\n", "illustriousxltile_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlv0_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_canny_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_depth_midas_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_tile_fp16 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epscanny = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartanime = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsnormalmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epssoftedgehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsmangaline = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartrealistic = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidasv11 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblepidinet = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_openposemodel = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epstile = False # @param {type:\"boolean\"}\n", "noobai_inpainting_controlnet = False # @param {type:\"boolean\"}\n", "noobipamark1_mark1 = False # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", \"type\": \"Stable-diffusion\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", \"type\": \"Stable-diffusion\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", \"type\": \"Stable-diffusion\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", \"type\": \"Stable-diffusion\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", \"type\": \"Stable-diffusion\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", \"type\": \"Stable-diffusion\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", \"type\": \"Stable-diffusion\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", \"type\": \"VAE\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", \"type\": \"VAE\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", \"type\": \"VAE\"})\n", "# VAE Approx 模型\n", "vae_approx_model and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/model.pt\", \"type\": \"VAE-approx\"})\n", "vae_approx_sdxl and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sdxl.pt\", \"type\": \"VAE-approx\"})\n", "vae_approx_sd3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/vae-approx/vaeapprox-sd3.pt\", \"type\": \"VAE-approx\"})\n", "# 放大模型\n", "upscale_dat_x2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", \"type\": \"DAT\"})\n", "upscale_dat_x3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", \"type\": \"DAT\"})\n", "upscale_dat_x4 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", \"type\": \"DAT\"})\n", "upscale_4x_nmkd_superscale_sp_178000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", \"type\": \"ESRGAN\"})\n", "upscale_8x_nmkd_superscale_150000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/8x_NMKD-Superscale_150000_G.pth\", \"type\": \"ESRGAN\"})\n", "upscale_lollypop and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/lollypop.pth\", \"type\": \"ESRGAN\"})\n", "upscale_realesrgan_x4plus and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", \"type\": \"RealESRGAN\"})\n", "upscale_realesrgan_x4plus_anime_6b and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", \"type\": \"RealESRGAN\"})\n", "upscale_swinir_4x and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/SwinIR/SwinIR_4x.pth\", \"type\": \"SwinIR\"})\n", "# ControlNet 模型\n", "illustriousxlcanny_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLCanny_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxllineart_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineart_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxldepth_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLDepth_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlsoftedge_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLSoftedge_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxllineartrrealistic_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineartRrealistic_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlshuffle_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLShuffle_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlopenpose_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLOpenPose_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxltile_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLTile_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv0_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv0.1_inpainting_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_canny_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_canny_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_depth_midas_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_depth_midas_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_inpainting_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_tile_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_tile_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epscanny and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsCanny.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsdepthmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidas.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epslineartanime and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartAnime.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsnormalmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsNormalMidas.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epssoftedgehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsSoftedgeHed.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsmangaline and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsMangaLine.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epslineartrealistic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartRealistic.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsdepthmidasv11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidasV11.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsscribblehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribbleHed.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsscribblepidinet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribblePidinet.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_openposemodel and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_openposeModel.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epstile and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsTile.safetensors\", \"type\": \"ControlNet\"})\n", "noobai_inpainting_controlnet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/NoobAI_Inpainting_ControlNet.safetensors\", \"type\": \"ControlNet\"})\n", "noobipamark1_mark1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/noobIPAMARK1_mark1.safetensors\", \"type\": \"ControlNet\"})\n", "\n", "# @markdown ---\n", "##############################################################################\n", "# @markdown ## 额外挂载目录设置, 在启动时挂载目录到 Google Drive:\n", "EXTRA_LINK_DIR = []\n", "\n", "#@markdown - models/Stable-diffusion 目录\n", "link_stable_diffusion_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/Lora 目录\n", "link_lora_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/VAE 目录\n", "link_vae_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/VAE-approx 目录\n", "link_vae_approx_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/text_encoder 目录\n", "link_text_encoder_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/CLIP 目录\n", "link_clip_dir = False # @param {type:\"boolean\"}\n", "#@markdown - embeddings 目录\n", "link_embeddings_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/RealESRGAN 目录\n", "link_realesrgan_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/GFPGAN 目录\n", "link_gfpgan_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/ESRGAN 目录\n", "link_esrgan_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/DAT 目录\n", "link_dat_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/diffusers 目录\n", "link_diffusers_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/ControlNet 目录\n", "link_controlnet_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/hypernetworks 目录\n", "link_hypernetworks_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/layer_model 目录\n", "link_layer_model_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/svd 目录\n", "link_svd_dir = False # @param {type:\"boolean\"}\n", "#@markdown - models/z123 目录\n", "link_z123_dir = False # @param {type:\"boolean\"}\n", "#@markdown - extensions 目录\n", "link_extensions_dir = False # @param {type:\"boolean\"}\n", "#@markdown - cache 目录\n", "link_cache_dir = False # @param {type:\"boolean\"}\n", "\n", "\n", "link_stable_diffusion_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/Stable-diffusion\"})\n", "link_lora_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/Lora\"})\n", "link_vae_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/VAE\"})\n", "link_vae_approx_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/VAE-approx\"})\n", "link_text_encoder_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/text_encoder\"})\n", "link_clip_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/CLIP\"})\n", "link_embeddings_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"embeddings\"})\n", "link_realesrgan_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/RealESRGAN\"})\n", "link_gfpgan_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/GFPGAN\"})\n", "link_esrgan_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/ESRGAN\"})\n", "link_dat_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/DAT\"})\n", "link_diffusers_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/diffusers\"})\n", "link_controlnet_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/ControlNet\"})\n", "link_hypernetworks_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/hypernetworks\"})\n", "link_layer_model_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/layer_model\"})\n", "link_svd_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/svd\"})\n", "link_z123_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"models/z123\"})\n", "link_extensions_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"extensions\"})\n", "link_cache_dir and EXTRA_LINK_DIR.append({\"link_dir\": \"cache\"})\n", "\n", "##############################################################################\n", "\n", "INSTALL_PARAMS = {\n", " \"torch_ver\": PYTORCH_VER or None,\n", " \"xformers_ver\": XFORMERS_VER or None,\n", " \"use_uv\": USE_UV,\n", " \"pypi_index_mirror\": PIP_INDEX_MIRROR or None,\n", " \"pypi_extra_index_mirror\": PIP_EXTRA_INDEX_MIRROR or None,\n", " \"pypi_find_links_mirror\": PIP_FIND_LINKS_MIRROR or None,\n", " # Colab 的环境暂不需要以下镜像源\n", " # \"github_mirror\": GITHUB_MIRROR or None,\n", " # \"huggingface_mirror\": HUGGINGFACE_MIRROR or None,\n", " \"pytorch_mirror\": PYTORCH_MIRROR or None,\n", " \"sd_webui_repo\": SD_WEBUI_REPO or None,\n", " \"sd_webui_branch\": SD_WEBUI_BRANCH or None,\n", " \"sd_webui_requirements\": SD_WEBUI_REQUIREMENTS or None,\n", " \"sd_webui_requirements_url\": SD_WEBUI_REQUIREMENTS_URL or None,\n", " \"sd_webui_setting\": SD_WEBUI_SETTING or None,\n", " \"extension_list\": EXTENSION_LIST,\n", " \"model_list\": SD_MODEL,\n", " \"check_avaliable_gpu\": CHECK_AVALIABLE_GPU,\n", " \"enable_tcmalloc\": ENABLE_TCMALLOC,\n", " \"enable_cuda_malloc\": ENABLE_CUDA_MALLOC,\n", " \"custom_sys_pkg_cmd\": None,\n", " \"huggingface_token\": None,\n", " \"modelscope_token\": None,\n", " \"update_core\": UPDATE_CORE,\n", "}\n", "\n", "TUNNEL_PARAMS = {\n", " \"use_ngrok\": USE_NGROK,\n", " \"ngrok_token\": NGROK_TOKEN or None,\n", " \"use_cloudflare\": USE_CLOUDFLARE,\n", " \"use_remote_moe\": USE_REMOTE_MOE,\n", " \"use_localhost_run\": USE_LOCALHOST_RUN,\n", " \"use_gradio\": USE_GRADIO,\n", " \"use_pinggy_io\": USE_PINGGY_IO,\n", " \"use_zrok\": USE_ZROK,\n", " \"zrok_token\": ZROK_TOKEN or None,\n", " \"message\": \"##### Stable Diffusion WebUI 访问地址 #####\",\n", "}\n", "\n", "SD_WEBUI_PATH = \"/content/stable-diffusion-webui\"\n", "try:\n", " _ = sd_webui_manager_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " sd_webui = SDWebUIManager(os.path.dirname(SD_WEBUI_PATH), os.path.basename(SD_WEBUI_PATH), port=7860)\n", " sd_webui_manager_has_init = True\n", "\n", "try:\n", " _ = sd_webui_has_init # type: ignore # noqa: F821\n", "except Exception:\n", " sd_webui_has_init = False\n", "\n", "if NO_REPEAT_CONFIGURE_ENV:\n", " if not sd_webui_has_init:\n", " sd_webui.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " sd_webui_has_init = True\n", " CLEAR_LOG and sd_webui.clear_up()\n", " logger.info(\"Stable Diffusion WebUI 运行环境配置完成\")\n", " else:\n", " logger.info(\"检测到不重复配置环境已启用, 并且在当前 Colab 实例中已配置 Stable Diffusion WebUI 运行环境, 不再重复配置 Stable Diffusion WebUI 运行环境\")\n", " logger.info(\"如需在当前 Colab 实例中重新配置 Stable Diffusion WebUI 运行环境, 请在快速启动选项中取消不重复配置环境功能\")\n", "else:\n", " sd_webui.install(**INSTALL_PARAMS)\n", " INIT_CONFIG = 1\n", " CLEAR_LOG and sd_webui.clear_up()\n", " logger.info(\"Stable Diffusion WebUI 运行环境配置完成\")\n", "\n", "if USE_GRADIO:\n", " SD_WEBUI_LAUNCH_ARGS = f\"{SD_WEBUI_LAUNCH_ARGS} --share\"\n", "\n", "LAUNCH_CMD = sd_webui.get_launch_command(SD_WEBUI_LAUNCH_ARGS)\n", "\n", "if QUICK_LAUNCH:\n", " logger.info(\"启动 Stable Diffusion WebUI 中\")\n", " os.chdir(SD_WEBUI_PATH)\n", " sd_webui.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=SD_WEBUI_REQUIREMENTS,\n", " )\n", " sd_webui.mount_drive(EXTRA_LINK_DIR)\n", " sd_webui.tun.start_tunnel(**TUNNEL_PARAMS)\n", " logger.info(\"Stable Diffusion WebUI 启动参数: %s\", SD_WEBUI_LAUNCH_ARGS)\n", " !{LAUNCH_CMD}\n", " os.chdir(JUPYTER_ROOT_PATH)\n", " CLEAR_LOG and sd_webui.clear_up()\n", " logger.info(\"已关闭 Stable Diffusion WebUI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "ZWnei0cZwWzK" }, "outputs": [], "source": [ "#@title 👇 下载模型(可选)\n", "\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Stable Diffusion WebUI\")\n", "\n", "#@markdown 选择下载的模型:\n", "##############################\n", "SD_MODEL = []\n", "\n", "# @markdown - Stable Diffusion 模型\n", "v1_5_pruned_emaonly = False # @param {type:\"boolean\"}\n", "animefull_final_pruned = False # @param {type:\"boolean\"}\n", "sd_xl_base_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_refiner_1_0_0_9vae = False # @param {type:\"boolean\"}\n", "sd_xl_turbo_1_0_fp16 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0_base = False # @param {type:\"boolean\"}\n", "animagine_xl_3_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_3_1 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0 = False # @param {type:\"boolean\"}\n", "animagine_xl_4_0_opt = False # @param {type:\"boolean\"}\n", "holodayo_xl_2_1 = False # @param {type:\"boolean\"}\n", "kivotos_xl_2_0 = False # @param {type:\"boolean\"}\n", "clandestine_xl_1_0 = False # @param {type:\"boolean\"}\n", "UrangDiffusion_1_1 = False # @param {type:\"boolean\"}\n", "RaeDiffusion_XL_v2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_delta_rev1 = False # @param {type:\"boolean\"}\n", "kohakuXLEpsilon_rev1 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev2 = False # @param {type:\"boolean\"}\n", "kohaku_xl_epsilon_rev3 = False # @param {type:\"boolean\"}\n", "kohaku_xl_zeta = False # @param {type:\"boolean\"}\n", "starryXLV52_v52 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v20 = False # @param {type:\"boolean\"}\n", "heartOfAppleXL_v30 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v10 = False # @param {type:\"boolean\"}\n", "sanaexlAnimeV10_v11 = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_2_aesthetic = False # @param {type:\"boolean\"}\n", "SanaeXL_Anime_v1_3_aesthetic = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v0_1_GUIDED = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_0 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v1_1 = False # @param {type:\"boolean\"}\n", "Illustrious_XL_v2_0_stable = False # @param {type:\"boolean\"}\n", "jruTheJourneyRemains_v25XL = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_earlyAccessVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred075 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred077 = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred10Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_epsilonPred11Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPredTestVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred05Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred06Version = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred065SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred075SVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred09RVersion = False # @param {type:\"boolean\"}\n", "noobaiXLNAIXL_vPred10Version = False # @param {type:\"boolean\"}\n", "ponyDiffusionV6XL_v6StartWithThisOne = False # @param {type:\"boolean\"}\n", "pdForAnime_v20 = False # @param {type:\"boolean\"}\n", "omegaPonyXLAnime_v20 = False # @param {type:\"boolean\"}\n", "# @markdown - VAE 模型\n", "vae_ft_ema_560000_ema_pruned = False # @param {type:\"boolean\"}\n", "vae_ft_mse_840000_ema_pruned = False # @param {type:\"boolean\"}\n", "sdxl_fp16_fix_vae = False # @param {type:\"boolean\"}\n", "# @markdown - Upscale 模型\n", "upscale_dat_x2 = False # @param {type:\"boolean\"}\n", "upscale_dat_x3 = False # @param {type:\"boolean\"}\n", "upscale_dat_x4 = False # @param {type:\"boolean\"}\n", "upscale_4x_nmkd_superscale_sp_178000_g = False # @param {type:\"boolean\"}\n", "upscale_8x_nmkd_superscale_150000_g = False # @param {type:\"boolean\"}\n", "upscale_lollypop = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus = False # @param {type:\"boolean\"}\n", "upscale_realesrgan_x4plus_anime_6b = False # @param {type:\"boolean\"}\n", "upscale_swinir_4x = False # @param {type:\"boolean\"}\n", "# @markdown - ControlNet 模型\n", "illustriousxlcanny_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineart_v10 = False # @param {type:\"boolean\"}\n", "illustriousxldepth_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlsoftedge_v10 = False # @param {type:\"boolean\"}\n", "illustriousxllineartrrealistic_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlshuffle_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlopenpose_v10 = False # @param {type:\"boolean\"}\n", "illustriousxltile_v10 = False # @param {type:\"boolean\"}\n", "illustriousxlv0_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_canny_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_depth_midas_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_inpainting_fp16 = False # @param {type:\"boolean\"}\n", "illustriousxlv1_1_tile_fp16 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epscanny = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartanime = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsnormalmidas = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epssoftedgehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsmangaline = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epslineartrealistic = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsdepthmidasv11 = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblehed = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epsscribblepidinet = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_openposemodel = False # @param {type:\"boolean\"}\n", "noobaixlcontrolnet_epstile = False # @param {type:\"boolean\"}\n", "noobai_inpainting_controlnet = False # @param {type:\"boolean\"}\n", "noobipamark1_mark1 = False # @param {type:\"boolean\"}\n", "\n", "\n", "# Stable Diffusion 模型\n", "v1_5_pruned_emaonly and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/v1-5-pruned-emaonly.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animefull_final_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sd_1.5/animefull-final-pruned.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_base_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_base_1.0_0.9vae.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_refiner_1_0_0_9vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_refiner_1.0_0.9vae.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sd_xl_turbo_1_0_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sd_xl_turbo_1.0_fp16.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_0_base and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0-base.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_3_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-3.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_4_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "animagine_xl_4_0_opt and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/animagine-xl-4.0-opt.safetensors\", \"type\": \"Stable-diffusion\"})\n", "holodayo_xl_2_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/holodayo-xl-2.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kivotos_xl_2_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kivotos-xl-2.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "clandestine_xl_1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/clandestine-xl-1.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "UrangDiffusion_1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/UrangDiffusion-1.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "RaeDiffusion_XL_v2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/RaeDiffusion-XL-v2.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_delta_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-delta-rev1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohakuXLEpsilon_rev1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohakuXLEpsilon_rev1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_epsilon_rev2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev2.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_epsilon_rev3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-epsilon-rev3.safetensors\", \"type\": \"Stable-diffusion\"})\n", "kohaku_xl_zeta and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/kohaku-xl-zeta.safetensors\", \"type\": \"Stable-diffusion\"})\n", "starryXLV52_v52 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/starryXLV52_v52.safetensors\", \"type\": \"Stable-diffusion\"})\n", "heartOfAppleXL_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "heartOfAppleXL_v30 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/heartOfAppleXL_v30.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sanaexlAnimeV10_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v10.safetensors\", \"type\": \"Stable-diffusion\"})\n", "sanaexlAnimeV10_v11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/sanaexlAnimeV10_v11.safetensors\", \"type\": \"Stable-diffusion\"})\n", "SanaeXL_Anime_v1_2_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.2-aesthetic.safetensors\", \"type\": \"Stable-diffusion\"})\n", "SanaeXL_Anime_v1_3_aesthetic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/SanaeXL-Anime-v1.3-aesthetic.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v0_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v0_1_GUIDED and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v0.1-GUIDED.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v1_0 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.0.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v1_1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v1.1.safetensors\", \"type\": \"Stable-diffusion\"})\n", "Illustrious_XL_v2_0_stable and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/Illustrious-XL-v2.0-stable.safetensors\", \"type\": \"Stable-diffusion\"})\n", "jruTheJourneyRemains_v25XL and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/jruTheJourneyRemains_v25XL.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_earlyAccessVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_earlyAccessVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred05Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred075 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred075.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred077 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred077.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred10Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_epsilonPred11Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_epsilonPred11Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPredTestVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPredTestVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred05Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred05Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred06Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred06Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred065SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred065SVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred075SVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred075SVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred09RVersion and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred09RVersion.safetensors\", \"type\": \"Stable-diffusion\"})\n", "noobaiXLNAIXL_vPred10Version and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/noobaiXLNAIXL_vPred10Version.safetensors\", \"type\": \"Stable-diffusion\"})\n", "ponyDiffusionV6XL_v6StartWithThisOne and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/ponyDiffusionV6XL_v6StartWithThisOne.safetensors\", \"type\": \"Stable-diffusion\"})\n", "pdForAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/pdForAnime_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "omegaPonyXLAnime_v20 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-model/resolve/main/sdxl_1.0/omegaPonyXLAnime_v20.safetensors\", \"type\": \"Stable-diffusion\"})\n", "# VAE 模型\n", "vae_ft_ema_560000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-ema-560000-ema-pruned.safetensors\", \"type\": \"VAE\"})\n", "vae_ft_mse_840000_ema_pruned and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sd_1.5/vae-ft-mse-840000-ema-pruned.safetensors\", \"type\": \"VAE\"})\n", "sdxl_fp16_fix_vae and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-vae/resolve/main/sdxl_1.0/sdxl_fp16_fix_vae.safetensors\", \"type\": \"VAE\"})\n", "# 放大模型\n", "upscale_dat_x2 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x2.pth\", \"type\": \"DAT\"})\n", "upscale_dat_x3 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x3.pth\", \"type\": \"DAT\"})\n", "upscale_dat_x4 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/DAT/DAT_x4.pth\", \"type\": \"DAT\"})\n", "upscale_4x_nmkd_superscale_sp_178000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth\", \"type\": \"ESRGAN\"})\n", "upscale_8x_nmkd_superscale_150000_g and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/8x_NMKD-Superscale_150000_G.pth\", \"type\": \"ESRGAN\"})\n", "upscale_lollypop and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/ESRGAN/lollypop.pth\", \"type\": \"ESRGAN\"})\n", "upscale_realesrgan_x4plus and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus.pth\", \"type\": \"RealESRGAN\"})\n", "upscale_realesrgan_x4plus_anime_6b and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/RealESRGAN/RealESRGAN_x4plus_anime_6B.pth\", \"type\": \"RealESRGAN\"})\n", "upscale_swinir_4x and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd-upscaler-models/resolve/main/SwinIR/SwinIR_4x.pth\", \"type\": \"SwinIR\"})\n", "# ControlNet 模型\n", "illustriousxlcanny_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLCanny_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxllineart_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineart_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxldepth_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLDepth_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlsoftedge_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLSoftedge_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxllineartrrealistic_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLLineartRrealistic_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlshuffle_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLShuffle_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlopenpose_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLOpenPose_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxltile_v10 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLTile_v10.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv0_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv0.1_inpainting_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_canny_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_canny_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_depth_midas_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_depth_midas_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_inpainting_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_inpainting_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "illustriousxlv1_1_tile_fp16 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/illustriousXLv1.1_tile_fp16.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epscanny and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsCanny.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsdepthmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidas.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epslineartanime and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartAnime.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsnormalmidas and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsNormalMidas.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epssoftedgehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsSoftedgeHed.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsmangaline and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsMangaLine.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epslineartrealistic and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsLineartRealistic.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsdepthmidasv11 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsDepthMidasV11.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsscribblehed and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribbleHed.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epsscribblepidinet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsScribblePidinet.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_openposemodel and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_openposeModel.safetensors\", \"type\": \"ControlNet\"})\n", "noobaixlcontrolnet_epstile and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/noobaiXLControlnet_epsTile.safetensors\", \"type\": \"ControlNet\"})\n", "noobai_inpainting_controlnet and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/sd_control_collection/resolve/main/NoobAI_Inpainting_ControlNet.safetensors\", \"type\": \"ControlNet\"})\n", "noobipamark1_mark1 and SD_MODEL.append({\"url\": \"https://huggingface.co/licyk/controlnet_v1.1/resolve/main/noobIPAMARK1_mark1.safetensors\", \"type\": \"ControlNet\"})\n", "\n", "##############################\n", "logger.info(\"下载模型中\")\n", "sd_webui.get_sd_model_from_list(SD_MODEL)\n", "CLEAR_LOG and sd_webui.clear_up()\n", "logger.info(\"模型下载完成\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MbpZVvRMPIAC" }, "outputs": [], "source": [ "#@title 👇 自定义模型下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Stable Diffusion WebUI\")\n", "\n", "#@markdown ### 选择模型种类:\n", "model_type = \"Lora\" # @param [\"Stable-diffusion\", \"Lora\", \"VAE\", \"VAE-approx\", \"text_encoder\", \"CLIP\", \"embeddings\", \"RealESRGAN\", \"GFPGAN\", \"ESRGAN\", \"DAT\", \"diffusers\", \"ControlNet\", \"hypernetworks\", \"layer_model\", \"svd\", \"z123\"]:\n", "#@markdown ### 填写模型的下载链接:\n", "model_url = \"https://huggingface.co/licyk/sd-lora/resolve/main/sdxl/style/CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "#@markdown ### 填写模型的名称(包括后缀名):\n", "model_name = \"CoolFlatColor.safetensors\" #@param {type:\"string\"}\n", "\n", "sd_webui.get_sd_model(\n", " url=model_url,\n", " filename=model_name or None,\n", " model_type=model_type,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "8y0FPv15wHP9" }, "outputs": [], "source": [ "#@title 👇 扩展下载\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Stable Diffusion WebUI\")\n", "\n", "#@markdown ### 填写扩展的下载链接:\n", "extension_url = \"https://github.com/michP247/auto-noise-schedule\" #@param {type:\"string\"}\n", "\n", "sd_webui.install_extension(extension_url)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "cLB6sKhErcG8" }, "outputs": [], "source": [ "#@title 👇 启动 Stable Diffusion WebUI\n", "try:\n", " _ = INIT_CONFIG\n", "except Exception:\n", " raise Exception(\"未安装 Stable Diffusion WebUI\")\n", "\n", "logger.info(\"启动 Stable Diffusion WebUI\")\n", "os.chdir(SD_WEBUI_PATH)\n", "sd_webui.check_env(\n", " use_uv=USE_UV,\n", " requirements_file=SD_WEBUI_REQUIREMENTS,\n", ")\n", "sd_webui.mount_drive(EXTRA_LINK_DIR)\n", "sd_webui.tun.start_tunnel(**TUNNEL_PARAMS)\n", "logger.info(\"Stable Diffusion WebUI 启动参数: %s\", SD_WEBUI_LAUNCH_ARGS)\n", "!{LAUNCH_CMD}\n", "os.chdir(JUPYTER_ROOT_PATH)\n", "CLEAR_LOG and sd_webui.clear_up()\n", "logger.info(\"已关闭 Stable Diffusion WebUI\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "AVWoNIEhXy5o" }, "outputs": [], "source": [ "#@title 👇 文件下载工具\n", "\n", "#@markdown ### 填写文件的下载链接:\n", "url = \"\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存路径:\n", "file_path = \"/content\" #@param {type:\"string\"}\n", "#@markdown ### 填写文件的保存名称 (可选):\n", "filename = \"\" #@param {type:\"string\"}\n", "\n", "sd_webui.download_file(\n", " url=url,\n", " path=file_path or None,\n", " save_name=filename or None,\n", ")\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 0 }
2301_81996401/sd-webui-all-in-one
notebook/stable_diffusion_webui_colab.ipynb
Jupyter Notebook
agpl-3.0
89,356
"""SD WebUI All In One 模块初始化工具 (弃用)""" import sys import warnings import subprocess import importlib.metadata def init_sd_webui_all_in_one_module( url: str | None = None, force_download: bool | None = False, ) -> None: """SD WebUI All In One 模块下载工具""" if url is None: url = "https://github.com/licyk/sd-webui-all-in-one@main" cmd = f'"{sys.executable}" -m pip install git+"{url}"' if not force_download: try: _ = importlib.metadata.version("sd-webui-all-in-one") print("SD WebUI All In One 已安装") return except Exception: pass print("安装 SD WebUI All In One 中") with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True, shell=True, encoding="utf-8", errors="replace", ) as p: for line in p.stdout: print(line, end="", flush=True) p.wait() if p.returncode != 0: raise RuntimeError("执行 SD WebUI All In One 安装进程发生了错误") print("安装 SD WebUI All In One 成功") warnings.warn( """sd_scripts_ipynb_core 将被弃用, 请改用 sd_webui_all_in_one 模块. - 使用 sd_webui_all_in_one 的方法: 1. 安装 sd_webui_all_in_one 内核 python -m pip install git+https://github.com/licyk/sd-webui-all-in-one 2. 将原有 sd_scripts_ipynb_core 的模块导入改为 sd_webui_all_in_one, 例如原有的模块导入如下: from sd_scripts_ipynb_core import SDWebUIManager, logger 修改后的模块导入: from sd_webui_all_in_one import SDWebUIManager, logger """, DeprecationWarning, stacklevel=2, ) init_sd_webui_all_in_one_module() del init_sd_webui_all_in_one_module # pylint: disable=unused-wildcard-import # pylint: disable=wildcard-import # pylint: disable=wrong-import-position from sd_webui_all_in_one import * # noqa: F403
2301_81996401/sd-webui-all-in-one
sd_scripts_ipynb_core.py
Python
agpl-3.0
1,997
"""SD WebUI All In One 与 SD 有关的环境管理模块, 可用于 Jupyter Notebook 支持管理的环境: - SD WebUI / SD WebUI Forge / SD WebUI reForge / SD WebUI Forge Classic / SD WebUI AMDGPU / SD.Next - ComfyUI - InvokeAI - Fooocus - SD Script - SD Trainer - Kohya GUI 如果需要显示所有等级的日志, 可设置环境变量`SD_WEBUI_ALL_IN_ONE_LOGGER_LEVEL=10` 禁用彩色日志可设置环境变量`SD_WEBUI_ALL_IN_ONE_LOGGER_COLOR=0` 设置日志器的名称可通过环境变量`SD_WEBUI_ALL_IN_ONE_LOGGER_NAME=<日志器名称>`进行设置 如果需要禁用补丁可设置环境变量`SD_WEBUI_ALL_IN_ONE_PATCHER=0` """ from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_NAME, LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.version import VERSION from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.manager.sd_webui_manager import SDWebUIManager from sd_webui_all_in_one.manager.comfyui_manager import ComfyUIManager from sd_webui_all_in_one.manager.fooocus_manager import FooocusManager from sd_webui_all_in_one.manager.invokeai_manager import InvokeAIManager from sd_webui_all_in_one.manager.sd_trainer_manager import SDTrainerManager from sd_webui_all_in_one.manager.sd_scripts_manager import SDScriptsManager logger = get_logger( name=LOGGER_NAME, level=LOGGER_LEVEL, color=LOGGER_COLOR, ) __all__ = [ "BaseManager", "SDWebUIManager", "ComfyUIManager", "FooocusManager", "InvokeAIManager", "SDTrainerManager", "SDScriptsManager", "VERSION", "logger", ]
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/__init__.py
Python
agpl-3.0
1,623
"""Shell 命令执行器 不同平台下 subprocess 的执行结果不一致, 以下为不同平台的测试结果: ``` Test Platform: linux Case 1: {'cmd': ['/usr/bin/git', '--version'], 'shell': False} -> Success Case 2: {'cmd': ['/usr/bin/git', '--version'], 'shell': True} -> Failed Case 3: {'cmd': '"/usr/bin/git" --version', 'shell': False} -> Failed Case 4: {'cmd': '"/usr/bin/git" --version', 'shell': True} -> Success Case 5: {'cmd': ['/usr/bin/git', '--version'], 'shell': False} -> Success Case 6: {'cmd': ['/usr/bin/git', '--version'], 'shell': True} -> Failed Case 7: {'cmd': '"/usr/bin/git" --version', 'shell': False} -> Failed Case 8: {'cmd': '"/usr/bin/git" --version', 'shell': True} -> Success Test Platform: win32 Case 1: {'cmd': ['C:\\Program Files\\Git\\mingw64\\bin\\git.EXE', '--version'], 'shell': False} -> Success Case 2: {'cmd': ['C:\\Program Files\\Git\\mingw64\\bin\\git.EXE', '--version'], 'shell': True} -> Success Case 3: {'cmd': '"C:\\Program Files\\Git\\mingw64\\bin\\git.EXE" --version', 'shell': False} -> Success Case 4: {'cmd': '"C:\\Program Files\\Git\\mingw64\\bin\\git.EXE" --version', 'shell': True} -> Success Case 5: {'cmd': ['C:/Program Files/Git/mingw64/bin/git.EXE', '--version'], 'shell': False} -> Success Case 6: {'cmd': ['C:/Program Files/Git/mingw64/bin/git.EXE', '--version'], 'shell': True} -> Success Case 7: {'cmd': '"C:/Program Files/Git/mingw64/bin/git.EXE" --version', 'shell': False} -> Success Case 8: {'cmd': '"C:/Program Files/Git/mingw64/bin/git.EXE" --version', 'shell': True} -> Success Test Platform: darwin Case 1: {'cmd': ['/opt/homebrew/bin/git', '--version'], 'shell': False} -> Success Case 2: {'cmd': ['/opt/homebrew/bin/git', '--version'], 'shell': True} -> Failed Case 3: {'cmd': '"/opt/homebrew/bin/git" --version', 'shell': False} -> Failed Case 4: {'cmd': '"/opt/homebrew/bin/git" --version', 'shell': True} -> Success Case 5: {'cmd': ['/opt/homebrew/bin/git', '--version'], 'shell': False} -> Success Case 6: {'cmd': ['/opt/homebrew/bin/git', '--version'], 'shell': True} -> Failed Case 7: {'cmd': '"/opt/homebrew/bin/git" --version', 'shell': False} -> Failed Case 8: {'cmd': '"/opt/homebrew/bin/git" --version', 'shell': True} -> Success ``` - 对于 Linux 平台, 当使用 Shell=True 时, 应使用字符串命令; Shell=False 时, 使用列表命令 - 对于 Windows 平台, 当使用 Shell=True / Shell=False 时, 使用字符串命令和列表命令都可行 - 对于 MacOS 平台, 当使用 Shell=True 时, 应使用字符串命令; Shell=False 时, 使用列表命令 (行为和 Linux 中的一致) """ import os import sys import shlex import subprocess from pathlib import Path from typing import Literal from sd_webui_all_in_one.utils import in_jupyter from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL logger = get_logger( name="CMD Runner", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def preprocess_command(command: list[str] | str, shell: bool) -> list[str] | str: """针对不同平台对命令进行预处理 Args: command (list[str] | str): 原始命令 shell (bool): 是否调用 Shell Returns: (list[str] | str): 处理后的命令 """ if sys.platform == "win32": # Windows # 字符串命令和列表命令都可行 return command else: # Linux / MacOS if shell: # 使用字符串命令 if isinstance(command, list): return shlex.join(command) return command # 使用列表命令 if isinstance(command, str): return shlex.split(command) return command def run_cmd( command: str | list[str], desc: str | None = None, errdesc: str | None = None, custom_env: dict[str, str] | None = None, live: bool | None = True, shell: bool | None = None, cwd: Path | str | None = None, display_mode: Literal["terminal", "jupyter"] | None = None, ) -> str | None: """执行 Shell 命令 Args: command (str | list[str]): 要执行的命令 desc (str | None): 执行命令的描述 errdesc (str | None): 执行命令报错时的描述 custom_env (dict[str, str] | None): 自定义环境变量 live (bool | None): 是否实时输出命令执行日志 shell (bool | None): 是否使用内置 Shell 执行命令 cwd (Path | str | None): 执行进程时的起始路径 display_mode (Literal["terminal", "jupyter"] | None): 执行子进程时使用的输出模式 Returns: (str | None): 命令执行时输出的内容 Raises: RuntimeError: 当命令执行失败时 """ if shell is None: shell = sys.platform != "win32" if desc is not None: logger.info(desc) if custom_env is None: custom_env = os.environ command_to_exec = preprocess_command(command=command, shell=shell) if display_mode is None: if in_jupyter(): display_mode = "jupyter" else: display_mode = "terminal" cwd = Path(cwd) if not isinstance(cwd, Path) and cwd is not None else cwd logger.debug("执行命令时使用的显示模式: %s", display_mode) logger.debug("使用的输出模式: %s", ("实时输出" if live else "非实时输出")) if live: if display_mode == "jupyter": process_output = [] process = subprocess.Popen( command_to_exec, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1, encoding="utf-8", env=custom_env, cwd=cwd, ) for line in process.stdout: process_output.append(line) print(line, end="", flush=True) if sys.stdout and hasattr(sys.stdout, "flush"): sys.stdout.flush() process.wait() if process.returncode != 0: raise RuntimeError(f"""{errdesc or "执行命令时发生错误"} 命令: {command_to_exec} 错误代码: {process.returncode}""") return "".join(process_output) if display_mode == "terminal": result: subprocess.CompletedProcess[bytes] = subprocess.run( command_to_exec, shell=shell, env=custom_env, cwd=cwd, ) if result.returncode != 0: raise RuntimeError(f"""{errdesc or "执行命令时发生错误"} 命令: {command_to_exec} 错误代码: {result.returncode}""") try: # 当 subprocess.run() 使用 PIPE 捕获输出时, result 才有输出内容 return result.stdout.decode(encoding="utf8", errors="ignore") except Exception: # 未使用 PIPE 时 subprocess.run() 可以实时输出内容, 但是 result 将为 None return None logger.warning("未知的显示模式: %s, 将切换到非实时输出模式", display_mode) # 非实时输出模式 result: subprocess.CompletedProcess[bytes] = subprocess.run( command_to_exec, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell, env=custom_env, cwd=cwd, ) if result.returncode != 0: message = f"""{errdesc or "执行命令时发生错误"} 命令: {command_to_exec} 错误代码: {result.returncode} 标准输出: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout) > 0 else ""} 错误输出: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr) > 0 else ""} """ raise RuntimeError(message) return result.stdout.decode(encoding="utf8", errors="ignore")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/cmd.py
Python
agpl-3.0
7,932
"""Colab 工具集""" import os from pathlib import Path from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="Colab Tools", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def is_colab_environment() -> bool: """检测当前运行环境是否为 Colab 参考: https://github.com/googlecolab/colabtools/blob/be426fedb0bf192ea3b4f208e2c8d956caf94d65/google/colab/drive.py#L114 Returns: bool: 检测结果 """ return os.path.exists("/var/colab/hostname") def mount_google_drive(path: Path | str) -> bool: """挂载 Google Drive Args: path (Path | str): 要挂在的路径 Returns: bool: 挂载 Google Drive 的结果 """ path = Path(path) if not isinstance(path, Path) and path is not None else path if not path.exists(): logger.info("挂载 Google Drive 中, 请根据提示进行操作") try: from google.colab import drive drive.mount(path.as_posix()) logger.info("Google Dirve 挂载完成") return True except Exception as e: logger.error("挂载 Google Drive 时出现问题: %e", e) return False else: logger.info("Google Drive 已挂载") return True def get_colab_secret(key: str) -> str | None: """获取 Colab 密钥 Args: key (str): 密钥名称 Returns: (str | None): 密钥名称对应的值 """ try: from google.colab import userdata except Exception as e: logger.error("导入 Colab 工具失败, 无法获取 Colab Secret: %s", e) return None try: return userdata.get(key) except Exception as e: logger.error("密钥 %s 不存在", e) return None
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/colab_tools.py
Python
agpl-3.0
1,852
"""配置管理""" import os import logging from pathlib import Path LOGGER_NAME = os.getenv("SD_WEBUI_ALL_IN_ONE_LOGGER_NAME", "SD WebUI All In One") """日志器名字""" LOGGER_LEVEL = int(os.getenv("SD_WEBUI_ALL_IN_ONE_LOGGER_LEVEL", str(logging.INFO))) """日志等级""" LOGGER_COLOR = os.getenv("SD_WEBUI_ALL_IN_ONE_LOGGER_COLOR") not in ["0", "False", "false", "None", "none", "null"] """日志颜色""" DEFAULT_ENV_VARS = [ ["TF_CPP_MIN_LOG_LEVEL", "3"], ["BITSANDBYTES_NOWELCOME", "1"], ["GRADIO_ANALYTICS_ENABLED", "False"], ["ClDeviceGlobalMemSizeAvailablePercent", "100"], ["CUDA_MODULE_LOADING", "LAZY"], ["TORCH_CUDNN_V8_API_ENABLED", "1"], ["SAFETENSORS_FAST_GPU", "1"], ["SYCL_CACHE_PERSISTENT", "1"], ["PYTHONUTF8", "1"], ["PYTHONIOENCODING", "utf-8"], ["PYTHONUNBUFFERED", "1"], ["PYTHONFAULTHANDLER", "1"], [ "PYTHONWARNINGS", "ignore:::torchvision.transforms.functional_tensor,ignore::UserWarning,ignore::FutureWarning,ignore::DeprecationWarning", ], ] """默认配置的环境变量""" PYTORCH_MIRROR_DICT = { "other": "https://download.pytorch.org/whl", "cpu": "https://download.pytorch.org/whl/cpu", "xpu": "https://download.pytorch.org/whl/xpu", "rocm61": "https://download.pytorch.org/whl/rocm6.1", "rocm62": "https://download.pytorch.org/whl/rocm6.2", "rocm624": "https://download.pytorch.org/whl/rocm6.2.4", "rocm63": "https://download.pytorch.org/whl/rocm6.3", "rocm64": "https://download.pytorch.org/whl/rocm6.4", "cu118": "https://download.pytorch.org/whl/cu118", "cu121": "https://download.pytorch.org/whl/cu121", "cu124": "https://download.pytorch.org/whl/cu124", "cu126": "https://download.pytorch.org/whl/cu126", "cu128": "https://download.pytorch.org/whl/cu128", "cu129": "https://download.pytorch.org/whl/cu129", "cu130": "https://download.pytorch.org/whl/cu130", } """PyTorch 镜像源字典""" ROOT_PATH = Path(__file__).parent """SD WebUI All In One 根目录""" SD_WEBUI_ALL_IN_ONE_PATCHER_PATH = ROOT_PATH / "sdaio_patcher" """SD WebUI All In One 补丁目录""" SD_WEBUI_ALL_IN_ONE_PATCHER = os.getenv("SD_WEBUI_ALL_IN_ONE_PATCHER") not in ["0", "False", "false", "None", "none", "null"] """是否 SD WebUI All In One 启用补丁"""
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/config.py
Python
agpl-3.0
2,318
"""文件下载工具""" import os import time import queue import shutil import hashlib import datetime import threading import traceback from pathlib import Path from urllib.parse import urlparse from tempfile import TemporaryDirectory from typing import Any, Callable, Literal from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="Downloader", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def aria2( url: str, path: Path | str | None = None, save_name: str | None = None, ) -> Path: """Aria2 下载工具 Args: url (str): 文件下载链接 path (Path | str | None): 下载文件的路径, 为`None`时使用当前路径 save_name (str | None): 保存的文件名, 为`None`时使用`url`提取保存的文件名 Returns: Path: 下载成功时返回文件路径, 否则返回`None` Raises: RuntimeError: 下载出现错误 """ if path is None: path = os.getcwd() path = Path(path) if not isinstance(path, Path) and path is not None else path if save_name is None: parts = urlparse(url) save_name = os.path.basename(parts.path) save_path = path / save_name try: logger.info("下载 %s 到 %s 中", os.path.basename(url), save_path) run_cmd( [ "aria2c", "--console-log-level=error", "--summary-interval=30", "-c", "-x", "16", "-s", "16", "-k", "1M", url, "-d", path.as_posix(), "-o", save_name, ] ) return save_path except Exception as e: logger.error("下载 %s 时发生错误: %s", url, e) raise RuntimeError(e) from e def load_file_from_url( url: str, *, model_dir: Path | str | None = None, progress: bool | None = False, file_name: str | None = None, hash_prefix: str | None = None, re_download: bool | None = False, ): """使用 requrests 库下载文件 Args: url (str): 下载链接 model_dir (Path | str | None): 下载路径 progress (bool | None): 是否启用下载进度条 file_name (str | None): 保存的文件名, 如果为`None`则从`url`中提取文件 hash_prefix (str | None): sha256 十六进制字符串, 如果提供, 将检查下载文件的哈希值是否与此前缀匹配, 当不匹配时引发`ValueError` re_download (bool): 强制重新下载文件 Returns: Path: 下载的文件路径 Raises: ValueError: 当提供了 hash_prefix 但文件哈希值不匹配时 """ import requests from tqdm import tqdm if model_dir is None: model_dir = os.getcwd() model_dir = Path(model_dir) if not isinstance(model_dir, Path) and model_dir is not None else model_dir if not file_name: parts = urlparse(url) file_name = os.path.basename(parts.path) cached_file = model_dir.resolve() / file_name if re_download or not cached_file.exists(): model_dir.mkdir(parents=True, exist_ok=True) temp_file = model_dir / f"{file_name}.tmp" logger.info("下载 %s 到 %s 中", file_name, cached_file) response = requests.get(url, stream=True) response.raise_for_status() total_size = int(response.headers.get("content-length", 0)) with tqdm( total=total_size, unit="B", unit_scale=True, desc=file_name, disable=not progress, ) as progress_bar: with open(temp_file, "wb") as file: for chunk in response.iter_content(chunk_size=1024): if chunk: file.write(chunk) progress_bar.update(len(chunk)) if hash_prefix and not compare_sha256(temp_file, hash_prefix): logger.error("%s 的哈希值不匹配, 正在删除临时文件", temp_file) temp_file.unlink() raise ValueError(f"文件哈希值与预期的哈希前缀不匹配: {hash_prefix}") temp_file.rename(cached_file) logger.info("%s 下载完成", file_name) else: logger.info("%s 已存在于 %s 中", file_name, cached_file) return cached_file def compare_sha256(file_path: str | Path, hash_prefix: str) -> bool: """检查文件的 sha256 哈希值是否与给定的前缀匹配 Args: file_path (str | Path): 文件路径 hash_prefix (str): 哈希前缀 Returns: bool: 匹配结果 """ hash_sha256 = hashlib.sha256() blksize = 1024 * 1024 with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(blksize), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest().startswith(hash_prefix.strip().lower()) def download_file( url: str, path: str | Path = None, save_name: str | None = None, tool: Literal["aria2", "requests"] = "aria2", retry: int | None = 3, ) -> Path | None: """下载文件工具 Args: url (str): 文件下载链接 path (Path | str): 文件下载路径 save_name (str | None): 文件保存名称, 当为`None`时从`url`中解析文件名 tool (Literal["aria2", "requests"]): 下载工具 retry (int | None): 重试下载的次数 Returns: (Path | None): 保存的文件路径 """ if tool == "aria2" and shutil.which("aria2c") is None: logger.warning("未安装 Aria2, 无法使用 Aria2 进行下载, 将切换到 requests 进行下载任务") tool = "requests" count = 0 while count < retry: count += 1 try: if tool == "aria2": output = aria2( url=url, path=path, save_name=save_name, ) if output is None: continue return output elif tool == "requests": output = load_file_from_url( url=url, model_dir=path, file_name=save_name, ) if output is None: continue return output else: logger.error("未知下载工具: %s", tool) return None except Exception as e: logger.error("[%s/%s] 下载 %s 出现错误: %s", count, retry, url, e) if count < retry: logger.warning("[%s/%s] 重试下载 %s 中", count, retry, url) else: return None def download_archive_and_unpack(url: str, local_dir: Path | str, name: str | None = None, retry: int | None = 3) -> Path | None: """下载压缩包并解压到指定路径 Args: url (str): 压缩包下载链接, 压缩包只支持`zip`,`7z`,`tar`格式 local_dir (Path | str): 下载路径 name (str | None): 下载文件保存的名称, 为`None`时从`url`解析文件名 retry (int | None): 重试下载的次数 Returns: (Path | None): 下载成功并解压成功时返回路径 """ with TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) local_dir = Path(local_dir) if not isinstance(local_dir, Path) and local_dir is not None else local_dir if name is None: parts = urlparse(url) name = os.path.basename(parts.path) archive_format = Path(name).suffix # 压缩包格式 origin_file_path = download_file( # 下载文件 url=url, path=path, save_name=name, retry=retry ) if origin_file_path is not None: # 解压文件 logger.info("解压 %s 到 %s 中", name, local_dir) try: if archive_format == ".7z": run_cmd( [ "7z", "x", origin_file_path.as_posix(), f"-o{local_dir.as_posix()}", ] ) logger.info("%s 解压完成, 路径: %s", name, local_dir) return local_dir elif archive_format == ".zip": run_cmd( [ "unzip", origin_file_path.as_posix(), "-d", local_dir.as_posix(), ] ) logger.info("%s 解压完成, 路径: %s", name, local_dir) return local_dir elif archive_format == ".tar": run_cmd( [ "tar", "-xvf", origin_file_path.as_posix(), "-C", local_dir.as_posix(), ] ) logger.info("%s 解压完成, 路径: %s", name, local_dir) return local_dir else: logger.error("%s 的格式不支持解压", name) return None except Exception as e: logger.error("解压 %s 时发生错误: %s", name, e) traceback.print_exc() return None else: logger.error("%s 下载失败", name) return None class MultiThreadDownloader: """通用多线程下载器 Attributes: download_func (Callable): 执行下载任务的函数 download_args_list (list[Any]): 传入下载函数的位置参数列表 download_kwargs_list (list[dict[str, Any]]): 传入下载函数的关键字参数列表 queue (queue.Queue): 任务队列, 用于存储待执行的下载任务 total_tasks (int): 总的下载任务数 completed_count (int): 已完成的任务数 lock (threading.Lock): 线程锁, 用于保护对计数器的访问 retry (int | None): 重试次数 start_time (datetime.datetime | None): 下载开始时间 """ def __init__( self, download_func: Callable, download_args_list: list[Any] | None = None, download_kwargs_list: list[dict[str, Any]] | None = None, ) -> None: """多线程下载器初始化 下载参数列表, 每个元素是一个子列表或字典, 包含传递给下载函数的参数 格式示例: ```python # 仅使用位置参数 download_args_list = [ [arg1, arg2, arg3, ...], # 第一个下载任务的参数 [arg1, arg2, arg3, ...], # 第二个下载任务的参数 [arg1, arg2, arg3, ...], # 第三个下载任务的参数 ] # 仅使用关键字参数 download_kwargs_list = [ {"param1": value1, "param2": value2}, # 第一个下载任务的参数 {"param1": value3, "param2": value4}, # 第二个下载任务的参数 {"param1": value5, "param2": value6}, # 第三个下载任务的参数 ] # 混合使用位置参数和关键字参数 download_args_list = [ [arg1, arg2], [arg3, arg4], [arg5, arg6], ] download_kwargs_list = [ {"param1": value1, "param2": value2}, {"param1": value3, "param2": value4}, {"param1": value5, "param2": value6}, ] ``` Args: download_func (Callable): 执行下载任务的函数 download_args_list (list[Any]): 传入下载函数的参数列表 download_kwargs_list (list[dict[str, Any]]): 传入下载函数的参数字典列表 """ self.download_func = download_func self.download_args_list = download_args_list or [] self.download_kwargs_list = download_kwargs_list or [] self.queue = queue.Queue() self.total_tasks = max(len(download_args_list or []), len(download_kwargs_list or [])) # 记录总的下载任务数 (以参数列表长度为准) self.completed_count = 0 # 记录已完成的任务数 self.lock = threading.Lock() # 创建锁以保护对计数器的访问 self.retry = None self.start_time = None def worker(self) -> None: """工作线程函数, 执行下载任务""" while True: task = self.queue.get() if task is None: break args, kwargs = task count = 0 while count < self.retry: count += 1 try: self.download_func(*args, **kwargs) break except Exception as e: traceback.print_exc() logger.error( "[%s/%s] 执行 %s 时发生错误: %s", count, self.retry, self.download_func, e, ) if count < self.retry: logger.warning("[%s/%s] 重试执行中", count, self.retry) self.queue.task_done() with self.lock: # 访问共享资源时加锁 self.completed_count += 1 self.print_progress() # 打印进度 def print_progress(self) -> None: """进度条显示""" progress = (self.completed_count / self.total_tasks) * 100 current_time = datetime.datetime.now() time_interval = current_time - self.start_time hours = time_interval.seconds // 3600 minutes = (time_interval.seconds // 60) % 60 seconds = time_interval.seconds % 60 formatted_time = f"{hours:02}:{minutes:02}:{seconds:02}" if self.completed_count > 0: speed = self.completed_count / time_interval.total_seconds() else: speed = 0 remaining_tasks = self.total_tasks - self.completed_count if speed > 0: estimated_remaining_time_seconds = remaining_tasks / speed estimated_remaining_time = datetime.timedelta(seconds=estimated_remaining_time_seconds) estimated_hours = estimated_remaining_time.seconds // 3600 estimated_minutes = (estimated_remaining_time.seconds // 60) % 60 estimated_seconds = estimated_remaining_time.seconds % 60 formatted_estimated_time = f"{estimated_hours:02}:{estimated_minutes:02}:{estimated_seconds:02}" else: formatted_estimated_time = "N/A" logger.info( "下载进度: %.2f%% | %d/%d [%s<%s, %.2f it/s]", progress, self.completed_count, self.total_tasks, formatted_time, formatted_estimated_time, speed, ) def start( self, num_threads: int | None = 16, retry: int | None = 3, ) -> None: """启动多线程下载器 Args: num_threads (int): 下载线程数, 默认为 16 retry (int): 重试次数, 默认为 3 """ # 将重试次数作为属性传递给下载函数 self.retry = retry threads: list[threading.Thread] = [] self.start_time = datetime.datetime.now() time.sleep(0.1) # 避免 print_progress() 计算时间时出现 division by zero # 启动工作线程 for _ in range(num_threads): thread = threading.Thread(target=self.worker) thread.start() threads.append(thread) # 准备下载任务参数 max_tasks = max(len(self.download_args_list), len(self.download_kwargs_list)) # 将下载任务添加到队列 for i in range(max_tasks): # 获取位置参数 args = self.download_args_list[i] if i < len(self.download_args_list) else [] # 获取关键字参数 kwargs = self.download_kwargs_list[i] if i < len(self.download_kwargs_list) else {} # 将任务参数打包 self.queue.put((args, kwargs)) # 等待所有任务完成 self.queue.join() # 停止所有工作线程 for _ in range(num_threads): self.queue.put(None) for thread in threads: thread.join()
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/downloader.py
Python
agpl-3.0
16,825
"""环境变量管理工具""" import os import sys from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR, DEFAULT_ENV_VARS logger = get_logger( name="Env Var Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def configure_pip() -> None: """使用环境变量配置 Pip / uv""" logger.info("配置 Pip / uv") os.environ["UV_HTTP_TIMEOUT"] = "30" os.environ["UV_CONCURRENT_DOWNLOADS"] = "50" os.environ["UV_INDEX_STRATEGY"] = "unsafe-best-match" os.environ["UV_PYTHON"] = sys.executable os.environ["UV_NO_PROGRESS"] = "1" os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "1" os.environ["PIP_NO_WARN_SCRIPT_LOCATION"] = "0" os.environ["PIP_TIMEOUT"] = "30" os.environ["PIP_RETRIES"] = "5" os.environ["PIP_PREFER_BINARY"] = "1" os.environ["PIP_YES"] = "1" def configure_env_var() -> None: """通过环境变量配置部分环境功能""" logger.info("使用环境变量配置部分设置") for e, v in DEFAULT_ENV_VARS: logger.info("- Env:%s = %s", e, v) os.environ[e] = v def config_wandb_token(token: str | None = None) -> None: """配置 WandB 所需 Token, 配置时将设置`WANDB_API_KEY`环境变量 Args: token (str | None): WandB Token """ if token is not None: logger.info("配置 WandB Token") os.environ["WANDB_API_KEY"] = token
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env.py
Python
agpl-3.0
1,442
"""ComfyUI 环境检查工具""" import sys from pathlib import Path from typing import TypedDict from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.env_manager import install_requirements from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.utils import remove_duplicate_object_from_list from sd_webui_all_in_one.package_analyzer.py_ver_cmp import PyWhlVersionComparison from sd_webui_all_in_one.package_analyzer.pkg_check import ( get_package_name, get_package_version, is_package_has_version, is_package_installed, parse_requirement_list, read_packages_from_requirements_file, ) logger = get_logger( name="ComfyUI Env Check", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class ComponentEnvironmentDetails(TypedDict): """ComfyUI 组件的环境信息结构 Attributes: requirement_path (str): 依赖文件路径 is_disabled (bool): 组件是否禁用 requires (list[str]): 需要的依赖列表 has_missing_requires (bool): 是否存在缺失依赖 missing_requires (list[str]): 具体缺失的依赖项 has_conflict_requires (bool): 是否存在冲突依赖 conflict_requires (list[str]): 具体冲突的依赖项 """ requirement_path: str """依赖文件路径""" is_disabled: bool """组件是否禁用""" requires: list[str] """需要的依赖列表""" has_missing_requires: bool """是否存在缺失依赖""" missing_requires: list[str] """具体缺失的依赖项""" has_conflict_requires: bool """是否存在冲突依赖""" conflict_requires: list[str] """具体冲突的依赖项""" ComfyUIEnvironmentComponent = dict[str, ComponentEnvironmentDetails] """ComfyUI 环境组件表字典""" def create_comfyui_environment_dict( comfyui_path: str | Path, ) -> ComfyUIEnvironmentComponent: """创建 ComfyUI 环境组件表字典 Args: comfyui_path (str | Path): ComfyUI 根路径 Returns: ComfyUIEnvironmentComponent: ComfyUI 环境组件表字典 """ comfyui_path = Path(comfyui_path) if not isinstance(comfyui_path, Path) and comfyui_path is not None else comfyui_path comfyui_env_data: ComfyUIEnvironmentComponent = { "ComfyUI": { "requirement_path": (comfyui_path / "requirements.txt").as_posix(), "is_disabled": False, "requires": [], "has_missing_requires": False, "missing_requires": [], "has_conflict_requires": False, "conflict_requires": [], }, } custom_nodes_path = comfyui_path / "custom_nodes" for custom_node in custom_nodes_path.iterdir(): if custom_node.is_file(): continue custom_node_requirement_path = custom_node / "requirements.txt" custom_node_is_disabled = True if custom_node.parent.as_posix().endswith(".disabled") else False comfyui_env_data[custom_node.name] = { "requirement_path": (custom_node_requirement_path.as_posix() if custom_node_requirement_path.exists() else None), "is_disabled": custom_node_is_disabled, "requires": [], "has_missing_requires": False, "missing_requires": [], "has_conflict_requires": False, "conflict_requires": [], } return comfyui_env_data def update_comfyui_environment_dict( env_data: ComfyUIEnvironmentComponent, component_name: str, requirement_path: str | None = None, is_disabled: bool | None = None, requires: list[str] | None = None, has_missing_requires: bool | None = None, missing_requires: list[str] | None = None, has_conflict_requires: bool | None = None, conflict_requires: list[str] | None = None, ) -> None: """更新 ComfyUI 环境组件表字典 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 component_name (str): ComfyUI 组件名称 requirement_path (str | None): ComfyUI 组件依赖文件路径 is_disabled (bool | None): ComfyUI 组件是否被禁用 requires (list[str] | None): ComfyUI 组件需要的依赖列表 has_missing_requires (bool | None): ComfyUI 组件是否存在缺失依赖 missing_requires (list[str] | None): ComfyUI 组件缺失依赖列表 has_conflict_requires (bool | None): ComfyUI 组件是否存在冲突依赖 conflict_requires (list[str] | None): ComfyUI 组件冲突依赖列表 """ env_data[component_name] = { "requirement_path": (requirement_path if requirement_path else env_data.get(component_name).get("requirement_path")), "is_disabled": (is_disabled if is_disabled else env_data.get(component_name).get("is_disabled")), "requires": (requires if requires else env_data.get(component_name).get("requires")), "has_missing_requires": (has_missing_requires if has_missing_requires else env_data.get(component_name).get("has_missing_requires")), "missing_requires": (missing_requires if missing_requires else env_data.get(component_name).get("missing_requires")), "has_conflict_requires": (has_conflict_requires if has_conflict_requires else env_data.get(component_name).get("has_conflict_requires")), "conflict_requires": (conflict_requires if conflict_requires else env_data.get(component_name).get("conflict_requires")), } def update_comfyui_component_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> None: """更新 ComfyUI 环境组件表字典, 根据字典中的 requirement_path 确定 Python 软件包版本声明文件, 并解析后写入 requires 字段 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 """ for component_name, details in env_data.items(): if details.get("is_disabled"): continue requirement_path = details.get("requirement_path") if requirement_path is None: continue origin_requires = read_packages_from_requirements_file(requirement_path) requires = parse_requirement_list(origin_requires) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, requires=requires, ) def update_comfyui_component_missing_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> None: """更新 ComfyUI 环境组件表字典, 根据字典中的 requires 检查缺失的 Python 软件包, 并保存到 missing_requires 字段和设置 has_missing_requires 状态 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 """ for component_name, details in env_data.items(): if details.get("is_disabled"): continue requires = details.get("requires") has_missing_requires = False missing_requires = [] for package in requires: if not is_package_installed(package): has_missing_requires = True missing_requires.append(package) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, has_missing_requires=has_missing_requires, missing_requires=missing_requires, ) def update_comfyui_component_conflict_requires_list(env_data: ComfyUIEnvironmentComponent, conflict_package_list: list[str]) -> None: """更新 ComfyUI 环境组件表字典, 根据 conflicconflict_package_listt_package 检查 ComfyUI 组件冲突的 Python 软件包, 并保存到 conflict_requires 字段和设置 has_conflict_requires 状态 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 conflict_package_list (list[str]): 冲突的 Python 软件包列表 """ for component_name, details in env_data.items(): if details.get("is_disabled"): continue requires = details.get("requires") has_conflict_requires = False conflict_requires: list[str] = [] for conflict_package in conflict_package_list: for package in requires: if is_package_has_version(package) and get_package_name(conflict_package) == get_package_name(package): has_conflict_requires = True conflict_requires.append(package) update_comfyui_environment_dict( env_data=env_data, component_name=component_name, has_conflict_requires=has_conflict_requires, conflict_requires=conflict_requires, ) def get_comfyui_component_requires_list( env_data: ComfyUIEnvironmentComponent, ) -> list[str]: """从 ComfyUI 环境组件表字典读取所有组件的 requires Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: list[str]: ComfyUI 环境组件的 Python 软件包列表 """ package_list = [] for _, details in env_data.items(): if details.get("is_disabled"): continue package_list += details.get("requires") return remove_duplicate_object_from_list(package_list) def statistical_need_install_require_component( env_data: ComfyUIEnvironmentComponent, ) -> list[str]: """根据 ComfyUI 环境组件表字典中的 has_missing_requires 和 has_conflict_requires 字段确认需要安装依赖的列表 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: list[str]: ComfyUI 环境组件的依赖文件路径列表 """ requirement_list = [] for _, details in env_data.items(): if details.get("has_missing_requires") or details.get("has_conflict_requires"): requirement_list.append(Path(details.get("requirement_path")).as_posix()) return requirement_list def statistical_has_conflict_component(env_data: ComfyUIEnvironmentComponent, conflict_package_list: list[str]) -> str: """根据 ComfyUI 环境组件表字典中的 conflict_requires 字段统计冲突的组件信息 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 Returns: str: ComfyUI 环境冲突的组件信息列表 """ content = [] # 统一成下划线 conflict_package_list = remove_duplicate_object_from_list([x.replace("-", "_") for x in conflict_package_list]) for conflict_package in conflict_package_list: content.append(get_package_name(f"{conflict_package}:")) for component_name, details in env_data.items(): for conflict_component_package in details.get("conflict_requires"): # 将中划线统一成下划线再对比 conflict_component_package_format = get_package_name(conflict_component_package).replace("-", "_") conflict_package_format = conflict_package.replace("-", "_") if conflict_component_package_format == conflict_package_format: content.append(f" - {component_name}: {conflict_component_package}") content.append("") return "\n".join([str(x) for x in (content[:-1] if len(content) > 0 and content[-1] == "" else content)]) def fitter_has_version_package(package_list: list[str]) -> list[str]: """过滤不包含版本的 Python 软件包, 仅保留包含版本号声明的 Python 软件包 Args: package_list (list[str]): Python 软件包列表 Returns: list[str]: 仅包含版本号的 Python 软件包列表 """ return [p for p in package_list if is_package_has_version(p)] def detect_conflict_package(pkg1: str, pkg2: str) -> bool: """检测 Python 软件包版本号声明是否存在冲突 Args: pkg1 (str): 第 1 个 Python 软件包名称 pkg2 (str): 第 2 个 Python 软件包名称 Returns: bool: 如果 Python 软件包版本声明出现冲突则返回`True` """ # 进行 2 次循环, 第 2 次循环时交换版本后再进行判断 for i in range(2): if i == 1: if pkg1 == pkg2: break else: pkg1, pkg2 = pkg2, pkg1 ver1 = get_package_version(pkg1) ver2 = get_package_version(pkg2) logger.debug( "冲突依赖检测: pkg1: %s, pkg2: %s, ver1: %s, ver2: %s", pkg1, pkg2, ver1, ver2, ) # >=, <= if ">=" in pkg1 and "<=" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2) return True # >=, < if ">=" in pkg1 and "<" in pkg2 and "=" not in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2) return True # >, <= if ">" in pkg1 and "=" not in pkg1 and "<=" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2) return True # >, < if ">" in pkg1 and "=" not in pkg1 and "<" in pkg2 and "=" not in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2) return True # >, == if ">" in pkg1 and "=" not in pkg1 and "==" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2) return True # >=, == if ">=" in pkg1 and "==" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2) return True # <, == if "<" in pkg1 and "=" not in pkg1 and "==" in pkg2: if PyWhlVersionComparison(ver1) <= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s <= %s", pkg1, pkg2, ver1, ver2) return True # <=, == if "<=" in pkg1 and "==" in pkg2: if PyWhlVersionComparison(ver1) < PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s < %s", pkg1, pkg2, ver1, ver2) return True # !=, == if "!=" in pkg1 and "==" in pkg2: if PyWhlVersionComparison(ver1) == PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s == %s", pkg1, pkg2, ver1, ver2) return True # >, ~= if ">" in pkg1 and "=" not in pkg1 and "~=" in pkg2: if PyWhlVersionComparison(ver1) >= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2) return True # >=, ~= if ">=" in pkg1 and "~=" in pkg2: if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2) return True # <, ~= if "<" in pkg1 and "=" not in pkg1 and "~=" in pkg2: if PyWhlVersionComparison(ver1) <= PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s <= %s", pkg1, pkg2, ver1, ver2) return True # <=, ~= if "<=" in pkg1 and "~=" in pkg2: if PyWhlVersionComparison(ver1) < PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s < %s", pkg1, pkg2, ver1, ver2) return True # !=, ~= # 这个也没什么必要 # if '!=' in pkg1 and '~=' in pkg2: # if is_v1_c_eq_v2(ver1, ver2): # logger.debug( # '冲突依赖: %s, %s, 版本冲突: %s ~= %s', # pkg1, pkg2, ver1, ver2) # return True # ~=, == / ~=, === if ("~=" in pkg1 and "==" in pkg2) or ("~=" in pkg1 and "===" in pkg2): if PyWhlVersionComparison(ver1) > PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2) return True # ~=, ~= # ~= 类似 >= V.N, == V.*, 所以该部分的比较没必要使用 # if '~=' in pkg1 and '~=' in pkg2: # if not is_v1_c_eq_v2(ver1, ver2): # logger.debug( # '冲突依赖: %s, %s, 版本冲突: %s !~= %s', # pkg1, pkg2, ver1, ver2) # return True # ==, == / ===, === if ("==" in pkg1 and "==" in pkg2) or ("===" in pkg1 and "===" in pkg2): if PyWhlVersionComparison(ver1) != PyWhlVersionComparison(ver2): logger.debug("冲突依赖: %s, %s, 版本冲突: %s != %s", pkg1, pkg2, ver1, ver2) return True return False def detect_conflict_package_from_list(package_list: list[str]) -> list[str]: """检测 Python 软件包版本声明列表中存在冲突的软件包 Args: package_list (list[str]): Python 软件包版本声明列表 Returns: list[str]: 冲突的 Python 软件包列表 """ conflict_package = [] for i in package_list: for j in package_list: # 截取包名并将包名中的中划线统一成下划线 pkg1 = get_package_name(i).replace("-", "_") pkg2 = get_package_name(j).replace("-", "_") if pkg1 == pkg2 and detect_conflict_package(i, j): conflict_package.append(get_package_name(i)) return remove_duplicate_object_from_list(conflict_package) def display_comfyui_environment_dict( env_data: ComfyUIEnvironmentComponent, ) -> None: """列出 ComfyUI 环境组件字典内容 Args: env_data (ComfyUIEnvironmentComponent): ComfyUI 环境组件表字典 """ logger.debug("ComfyUI 环境组件表") for component_name, details in env_data.items(): logger.debug("Component: %s", component_name) logger.debug(" - requirement_path: %s", details["requirement_path"]) logger.debug(" - is_disabled: %s", details["is_disabled"]) logger.debug(" - requires: %s", details["requires"]) logger.debug(" - has_missing_requires: %s", details["has_missing_requires"]) logger.debug(" - missing_requires: %s", details["missing_requires"]) logger.debug(" - has_conflict_requires: %s", details["has_conflict_requires"]) logger.debug(" - conflict_requires: %s", details["conflict_requires"]) print() def display_check_result(requirement_list: list[str], conflict_result: str) -> None: """显示 ComfyUI 运行环境检查结果 Args: requirement_list (list[str]): ComfyUI 组件依赖文件路径列表 conflict_result (str): 冲突组件统计信息 """ if len(requirement_list) > 0: logger.debug("需要安装 ComfyUI 组件列表") for requirement in requirement_list: component_name = requirement.split("/")[-2] logger.debug("%s:", component_name) logger.debug(" - %s", requirement) print() if len(conflict_result) > 0: logger.debug("ComfyUI 冲突组件: \n%s", conflict_result) def process_comfyui_env_analysis(comfyui_root_path: Path | str) -> tuple[dict[str, ComponentEnvironmentDetails], list[str], str] | tuple[None, None, None]: """分析 ComfyUI 环境 Args: comfyui_root_path (Path | str): ComfyUI 根目录 Returns: (tuple[dict[str, ComponentEnvironmentDetails], list[str], str] | tuple[None, None, None]): ComfyUI 环境组件信息, 缺失依赖的依赖表, 冲突组件信息 """ comfyui_root_path = Path(comfyui_root_path) if not isinstance(comfyui_root_path, Path) and comfyui_root_path is not None else comfyui_root_path if not (comfyui_root_path / "requirements.txt").exists(): logger.error("ComfyUI 依赖文件缺失, 请检查 ComfyUI 是否安装完整") return None, None, None if not (comfyui_root_path / "custom_nodes").exists(): logger.error("ComfyUI 自定义节点文件夹未找到, 请检查 ComfyUI 是否安装完整") return None, None, None env_data = create_comfyui_environment_dict(comfyui_root_path) update_comfyui_component_requires_list(env_data) update_comfyui_component_missing_requires_list(env_data) pkg_list = get_comfyui_component_requires_list(env_data) has_version_pkg = fitter_has_version_package(pkg_list) conflict_pkg = detect_conflict_package_from_list(has_version_pkg) update_comfyui_component_conflict_requires_list(env_data, conflict_pkg) req_list = statistical_need_install_require_component(env_data) conflict_info = statistical_has_conflict_component(env_data, conflict_pkg) return env_data, req_list, conflict_info def comfyui_conflict_analyzer( comfyui_root_path: Path | str, install_conflict_component_requirement: bool | None = False, use_uv: bool | None = True, debug_mode: bool | None = False, ) -> None: """检查并安装 ComfyUI 的依赖环境 Args: comfyui_root_path (Path | str): ComfyUI 根目录 install_conflict_component_requirement (bool | None): 检测到冲突依赖时是否按顺序安装组件依赖 use_uv (bool | None): 是否使用 uv 安装依赖 debug_mode (bool | None): 显示调试信息 """ logger.info("检测 ComfyUI 环境中") env_data, req_list, conflict_info = process_comfyui_env_analysis(comfyui_root_path) if debug_mode: display_comfyui_environment_dict(env_data) display_check_result(req_list, conflict_info) if len(conflict_info) > 0: logger.warning("检测到当前 ComfyUI 环境中安装的插件之间存在依赖冲突情况, 该问题并非致命, 但建议只保留一个插件, 否则部分功能可能无法正常使用") logger.warning("您可以选择按顺序安装依赖, 由于这将向环境中安装不符合版本要求的组件, 您将无法完全解决此问题, 但可避免组件由于依赖缺失而无法启动的情况") logger.warning("检测到冲突的依赖:") print(conflict_info) if not install_conflict_component_requirement: logger.info("忽略警告并继续启动 ComfyUI") return task_sum = len(req_list) count = 0 for req in req_list: count += 1 req_path = Path(req) name = req_path.parent.name installer_script = req_path / "install.py" logger.info("[%s/%s] 安装 %s 的依赖中", count, task_sum, name) try: install_requirements( path=req, use_uv=use_uv, cwd=req_path.parent, ) except Exception as e: logger.error("[%s/%s] 安装 %s 的依赖失败: %s", count, task_sum, name, e) if installer_script.is_file(): logger.info("[%s/%s] 执行 %s 的安装脚本中", count, task_sum, name) try: run_cmd( [Path(sys.executable).as_posix(), installer_script.as_posix()], cwd=req_path.parent, ) except Exception as e: logger.info("[%s/%s] 执行 %s 的安装脚本时发生错误: %s", count, task_sum, name, e) logger.info("ComfyUI 环境检查完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/comfyui_env_analyze.py
Python
agpl-3.0
24,118
"""依赖检查与修复工具""" from pathlib import Path from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.env_manager import install_requirements from sd_webui_all_in_one.package_analyzer.pkg_check import validate_requirements logger = get_logger( name="Deps Check", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def py_dependency_checker( requirement_path: Path | str, name: str | None = None, use_uv: bool | None = True, ) -> None: """检测依赖完整性并安装缺失依赖 Args: requirement_path (Path | str): 依赖文件路径 name (str | None): 显示的名称 use_uv (bool | None): 是否使用 uv 安装依赖 """ requirement_path = Path(requirement_path) if not isinstance(requirement_path, Path) and requirement_path is not None else requirement_path if not requirement_path.exists(): logger.error("未找到 %s 文件, 无法检查依赖完整性", requirement_path) return if name is None: name = requirement_path.parent.name logger.info("检查 %s 依赖完整性中", name) if not validate_requirements(requirement_path): logger.info("安装 %s 依赖中", name) try: install_requirements( path=requirement_path, use_uv=use_uv, cwd=requirement_path.parent, ) logger.info("安装 %s 依赖完成", name) except Exception as e: logger.error("安装 %s 依赖出现错误: %s", name, e) return logger.info("%s 依赖完整性检查完成", name)
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/fix_dependencies.py
Python
agpl-3.0
1,698
"""Numpy 检查工具""" import importlib.metadata from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.env_manager import pip_install from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.package_analyzer.py_ver_cmp import PyWhlVersionComparison logger = get_logger( name="Numpy Check", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def check_numpy(use_uv: bool | None = True) -> None: """检查 Numpy 是否需要降级 Args: use_uv (bool| None): 是否使用 uv 安装依赖 """ logger.info("检查 Numpy 是否需要降级") try: numpy_ver = importlib.metadata.version("numpy") if PyWhlVersionComparison(numpy_ver) > PyWhlVersionComparison("1.26.4"): logger.info("降级 Numoy 中") pip_install("numpy==1.26.4", use_uv=use_uv) logger.info("Numpy 降级完成") else: logger.info("Numpy 无需降级") except Exception as e: logger.error("检查 Numpy 时出现错误: %s", e)
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/fix_numpy.py
Python
agpl-3.0
1,066
"""Torch 修复工具""" import ctypes import shutil import importlib.util from pathlib import Path from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="Torch Fixer", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def fix_torch_libomp() -> None: """检测并修复 PyTorch 的 libomp 问题""" logger.info("检测 PyTorch 的 libomp 问题") try: torch_spec = importlib.util.find_spec("torch") for folder in torch_spec.submodule_search_locations: folder = Path(folder) lib_folder = folder / "lib" test_file = lib_folder / "fbgemm.dll" dest = lib_folder / "libomp140.x86_64.dll" if dest.exists(): break with open(test_file, "rb") as f: contents = f.read() if b"libomp140.x86_64.dll" not in contents: break try: _ = ctypes.cdll.LoadLibrary(test_file) except FileNotFoundError as _: logger.warning("检测到 PyTorch 版本存在 libomp 问题, 进行修复") shutil.copyfile(lib_folder / "libiomp5md.dll", dest) except Exception as _: pass
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/fix_torch.py
Python
agpl-3.0
1,293
"""Onnxruntime GPU 检查工具""" import os import re import sys from enum import Enum from pathlib import Path import importlib.metadata from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.env_manager import pip_install from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.package_analyzer.ver_cmp import CommonVersionComparison logger = get_logger( name="Onnxruntime GPU Check", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class OrtType(str, Enum): """onnxruntime-gpu 的类型 版本说明: - CU130: CU13.x - CU121CUDNN8: CUDA 12.1 + cuDNN8 - CU121CUDNN9: CUDA 12.1 + cuDNN9 - CU118: CUDA 11.8 PyPI 中 1.19.0 及之后的版本为 CUDA 12.x 的 Attributes: CU130 (str): CUDA 13.x 版本的 onnxruntime-gpu CU121CUDNN8 (str): CUDA 12.1 + cuDNN 8 版本的 onnxruntime-gpu CU121CUDNN9 (str): CUDA 12.1 + cuDNN 9 版本的 onnxruntime-gpu CU118 (str): CUDA 11.8 版本的 onnxruntime-gpu """ CU130 = "cu130" CU121CUDNN8 = "cu121cudnn8" CU121CUDNN9 = "cu121cudnn9" CU118 = "cu118" def __str__(self): return self.value def get_onnxruntime_version_file() -> Path | None: """获取记录 onnxruntime 版本的文件路径 Returns: (Path | None): 记录 onnxruntime 版本的文件路径 """ package = "onnxruntime-gpu" version_file = "onnxruntime/capi/version_info.py" try: util = [p for p in importlib.metadata.files(package) if version_file in str(p)][0] info_path = Path(util.locate()) except Exception as _: info_path = None return info_path def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]: """获取 onnxruntime 支持的 CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None]): onnxruntime 支持的 CUDA, cuDNN 版本 """ ver_path = get_onnxruntime_version_file() cuda_ver = None cudnn_ver = None try: with open(ver_path, "r", encoding="utf8") as f: for line in f: if "cuda_version" in line: cuda_ver = get_value_from_variable(line, "cuda_version") if "cudnn_version" in line: cudnn_ver = get_value_from_variable(line, "cudnn_version") except Exception as _: pass return cuda_ver, cudnn_ver def get_value_from_variable(content: str, var_name: str) -> str | None: """从字符串 (Python 代码片段) 中找出指定字符串变量的值 Args: content (str): 待查找的内容 var_name (str): 待查找的字符串变量 Returns: (str | None): 返回字符串变量的值 """ pattern = rf'{var_name}\s*=\s*"([^"]+)"' match = re.search(pattern, content) return match.group(1) if match else None def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]: """获取 Torch 的本体, CUDA, cuDNN 版本 Returns: (tuple[str | None, str | None, str | None]): Torch, CUDA, cuDNN 版本 """ try: import torch torch_ver = torch.__version__ cuda_ver = torch.version.cuda cudnn_ver = torch.backends.cudnn.version() return ( str(torch_ver) if torch_ver is not None else None, str(cuda_ver) if cuda_ver is not None else None, str(cudnn_ver) if cudnn_ver is not None else None, ) except Exception as _: return None, None, None def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None: """判断需要安装的 onnxruntime 版本 Args: ignore_ort_install (bool): 当 onnxruntime 未安装时跳过检查 Returns: OrtType: 需要安装的 onnxruntime-gpu 类型 """ # 检测是否安装了 Torch torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver() logger.debug("torch_ver: %s, cuda_ver: %s, cuddn_ver: %s", torch_ver, cuda_ver, cuddn_ver) # 缺少 Torch / CUDA / cuDNN 版本时取消判断 if torch_ver is None or cuda_ver is None or cuddn_ver is None: logger.debug("缺少 Torch / CUDA / cuDNN 版本") if not ignore_ort_install: try: logger.debug("检查 Onnxruntime GPU 是否已安装") _ = importlib.metadata.version("onnxruntime-gpu") except Exception as _: logger.debug("Onnxruntime GPU 未安装, 使用默认版本进行安装") # onnxruntime-gpu 没有安装时 return OrtType.CU130 logger.debug("跳过安装 Onnxruntime GPU") return None # onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位 cuddn_ver = cuddn_ver[0] # 检测是否安装了 onnxruntime-gpu ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version() logger.debug("cuddn_ver: %s, ort_support_cuda_ver: %s, ort_support_cudnn_ver: %s", cuddn_ver, ort_support_cuda_ver, ort_support_cudnn_ver) # 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可 if ort_support_cuda_ver is not None: # 当 onnxruntime 已安装 logger.debug("检测到 Onnxruntime GPU 声明的 CUDA / cuDNN 版本, 开始检测是否匹配 PyTorch 中的 CUDA / cuDNN 版本") # 判断 Torch 中的 CUDA 版本 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison("13.0"): # CUDA >= 13.0 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison("13.0"): return OrtType.CU130 else: return None elif CommonVersionComparison("12.0") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison("13.0"): # 12.0 =< CUDA < 13.0 # 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配 if CommonVersionComparison("12.0") <= CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison("13.0"): # CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配 # 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配 if CommonVersionComparison(ort_support_cudnn_ver) > CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 > torch cuDNN 版本 return OrtType.CU121CUDNN8 elif CommonVersionComparison(ort_support_cudnn_ver) < CommonVersionComparison(cuddn_ver): # ort cuDNN 版本 < torch cuDNN 版本 return OrtType.CU121CUDNN9 else: # 版本相等, 无需重装 return None else: # CUDA 版本非 12.x, 不匹配 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison("8"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 if CommonVersionComparison(ort_support_cuda_ver) < CommonVersionComparison("12.0"): return None else: return OrtType.CU118 else: logger.debug("未检测到 Onnxruntime GPU 声明的 CUDA / cuDNN 版本") if ignore_ort_install: return None logger.debug("确定需要安装的 Onnxruntime GPU 版本") if sys.platform != "win32": # 非 Windows 平台未在 Onnxruntime GPU 中声明支持的 CUDA 版本 (无 onnxruntime/capi/version_info.py) # 所以需要跳过检查, 直接给出版本 logger.debug("非 Windows 版本, 当 Onnxruntime GPU 未安装时给出默认版本") try: _ = importlib.metadata.version("onnxruntime-gpu") return None except Exception as _: # onnxruntime-gpu 没有安装时 return OrtType.CU130 if CommonVersionComparison(cuda_ver) >= CommonVersionComparison("13.0"): # CUDA >= 13.x return OrtType.CU130 elif CommonVersionComparison("12.0") <= CommonVersionComparison(cuda_ver) < CommonVersionComparison("13.0"): # 12.0 <= CUDA < 13.0 if CommonVersionComparison(cuddn_ver) > CommonVersionComparison("8"): return OrtType.CU121CUDNN9 else: return OrtType.CU121CUDNN8 else: # CUDA <= 11.8 return OrtType.CU118 def check_onnxruntime_gpu(use_uv: bool | None = True, ignore_ort_install: bool | None = False): """检查并修复 Onnxruntime GPU 版本问题 Args: use_uv (bool | None): 是否使用 uv 安装依赖 ignore_ort_install (bool | None): 当 onnxruntime 未安装时跳过检查 """ logger.info("检查 Onnxruntime GPU 版本问题中") ver = need_install_ort_ver(ignore_ort_install) logger.debug("需要安装的 Onnxruntime GPU 版本类型: %s", ver) if ver is None: logger.info("Onnxruntime GPU 无版本问题") return custom_env = os.environ.copy() custom_env.pop("PIP_EXTRA_INDEX_URL", None) custom_env.pop("UV_INDEX", None) custom_env.pop("PIP_FIND_LINKS", None) custom_env.pop("UV_FIND_LINKS", None) def _uninstall_onnxruntime_gpu(): run_cmd( [ Path(sys.executable).as_posix(), "-m", "pip", "uninstall", "onnxruntime-gpu", "-y", ] ) try: # TODO: 将 onnxruntime-gpu 的 1.23.2 版本替换成实际属于 CU130 的版本 if ver == OrtType.CU118: custom_env["PIP_INDEX_URL"] = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-11/pypi/simple/" custom_env["UV_DEFAULT_INDEX"] = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-11/pypi/simple/" _uninstall_onnxruntime_gpu() pip_install( "onnxruntime-gpu>=1.18.1", "--no-cache-dir", use_uv=use_uv, custom_env=custom_env, ) elif ver == OrtType.CU121CUDNN9: _uninstall_onnxruntime_gpu() pip_install("onnxruntime-gpu>=1.19.0,<1.23.2", "--no-cache-dir", use_uv=use_uv) elif ver == OrtType.CU121CUDNN8: custom_env["PIP_INDEX_URL"] = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/" custom_env["UV_DEFAULT_INDEX"] = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/" _uninstall_onnxruntime_gpu() pip_install( "onnxruntime-gpu==1.17.1", "--no-cache-dir", use_uv=use_uv, custom_env=custom_env, ) elif ver == OrtType.CU130: _uninstall_onnxruntime_gpu() pip_install("onnxruntime-gpu>=1.23.2", "--no-cache-dir", use_uv=use_uv) except Exception as e: logger.error("修复 Onnxruntime GPU 版本问题时出现错误: %s", e) return logger.info("Onnxruntime GPU 版本问题修复完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/onnxruntime_gpu_check.py
Python
agpl-3.0
11,455
"""Stable Diffusion WebUI 扩展依赖安装工具""" import os import sys import json import traceback from pathlib import Path from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL logger = get_logger( name="SD WebUI Ext Req Installer", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def run_extension_installer(sd_webui_base_path: Path, extension_dir: Path) -> bool: """执行扩展依赖安装脚本 Args: sd_webui_base_path (Path): SD WebUI 跟目录, 用于导入自身模块 extension_dir (Path): 要执行安装脚本的扩展路径 Returns: bool: 扩展依赖安装结果 """ path_installer = extension_dir / "install.py" if not path_installer.is_file(): return try: env = os.environ.copy() py_path = env.get("PYTHONPATH", "") env["PYTHONPATH"] = f"{sd_webui_base_path}{os.pathsep}{py_path}" env["WEBUI_LAUNCH_LIVE_OUTPUT"] = "1" run_cmd( command=[Path(sys.executable).as_posix(), path_installer.as_posix()], custom_env=env, cwd=sd_webui_base_path, ) return True except Exception as e: logger.info("执行 %s 扩展依赖安装脚本时发生错误: %s", extension_dir.name, e) traceback.print_exc() return False def install_extension_requirements( sd_webui_base_path: Path, arg_disable_extra_extensions: bool = False, arg_disable_all_extensions: bool = False, ) -> None: """安装 SD WebUI 扩展依赖 Args: sd_webui_base_path (Path): SD WebUI 根目录 arg_disable_extra_extensions (bool): 是否禁用 SD WebUI 额外扩展 arg_disable_all_extensions (bool): 是否禁用 SD WebUI 所有扩展 """ settings_file = sd_webui_base_path / "config.json" extensions_dir = sd_webui_base_path / "extensions" builtin_extensions_dir = sd_webui_base_path / "extensions-builtin" ext_install_list = [] ext_builtin_install_list = [] settings = {} try: with open(settings_file, "r", encoding="utf8") as file: settings = json.load(file) except Exception as e: logger.warning("Stable Diffusion WebUI 配置文件无效: %s", e) disabled_extensions = set(settings.get("disabled_extensions", [])) disable_all_extensions = settings.get("disable_all_extensions", "none") if disable_all_extensions == "all" or arg_disable_all_extensions: logger.info("已禁用所有 Stable Diffusion WebUI 扩展, 不执行扩展依赖检查") return if extensions_dir.is_dir() and disable_all_extensions != "extra" and not arg_disable_extra_extensions: ext_install_list = [x for x in extensions_dir.glob("*") if x.name not in disabled_extensions and (x / "install.py").is_file()] if builtin_extensions_dir.is_dir(): ext_builtin_install_list = [x for x in builtin_extensions_dir.glob("*") if x.name not in disabled_extensions and (x / "install.py").is_file()] install_list = ext_install_list + ext_builtin_install_list extension_count = len(install_list) if extension_count == 0: logger.info("无待安装依赖的 Stable Diffusion WebUI 扩展") return count = 0 for ext in install_list: count += 1 ext_name = ext.name logger.info("[%s/%s] 执行 %s 扩展的依赖安装脚本中", count, extension_count, ext_name) if run_extension_installer( sd_webui_base_path=sd_webui_base_path, extension_dir=ext, ): logger.info( "[%s/%s] 执行 %s 扩展的依赖安装脚本成功", count, extension_count, ext_name, ) else: logger.warning( "[%s/%s] 执行 %s 扩展的依赖安装脚本失败, 可能会导致该扩展运行异常", count, extension_count, ext_name, ) logger.info("[%s/%s] 安装 Stable Diffusion WebUI 扩展依赖结束", count, extension_count)
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_check/sd_webui_extension_dependency_installer.py
Python
agpl-3.0
4,192
"""依赖环境管理工具""" import os import sys from typing import Any from pathlib import Path from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="Env Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def pip_install( *args: Any, use_uv: bool | None = True, custom_env: dict[str, str] | None = None, cwd: Path | str | None = None, ) -> str: """使用 Pip / uv 安装 Python 软件包 Args: *args (Any): 要安装的 Python 软件包 (可使用 Pip / uv 命令行参数, 如`--upgrade`, `--force-reinstall`) use_uv (bool | None): 使用 uv 代替 Pip 进行安装, 当 uv 安装 Python 软件包失败时, 将回退到 Pip 进行重试 custom_env (dict[str, str] | None): 自定义环境变量 cwd (Path | str | None): 执行 Pip / uv 时的起始路径 Returns: str: 命令的执行输出 Raises: RuntimeError: 当 uv 和 pip 都无法安装软件包时抛出异常 """ if custom_env is None: custom_env = os.environ.copy() cwd = Path(cwd) if not isinstance(cwd, Path) and cwd is not None else cwd if use_uv: try: run_cmd(["uv", "--version"], live=False, custom_env=custom_env) except Exception as _: logger.info("安装 uv 中") run_cmd( [Path(sys.executable).as_posix(), "-m", "pip", "install", "uv"], custom_env=custom_env, ) try: return run_cmd(["uv", "pip", "install", *args], custom_env=custom_env, cwd=cwd) except Exception as e: logger.warning( "检测到 uv 安装 Python 软件包失败, 尝试回退到 Pip 重试 Python 软件包安装: %s", e, ) return run_cmd( [Path(sys.executable).as_posix(), "-m", "pip", "install", *args], custom_env=custom_env, cwd=cwd, ) else: return run_cmd( [Path(sys.executable).as_posix(), "-m", "pip", "install", *args], custom_env=custom_env, cwd=cwd, ) def install_manager_depend( use_uv: bool | None = True, custom_env: dict[str, str] | None = None, custom_sys_pkg_cmd: list[list[str]] | list[str] | None = None, ) -> bool: """安装自身组件依赖 自定义命令的例子: ```python custom_sys_pkg_cmd = [ ["apt", "update"], ["apt", "install", "aria2", "google-perftools", "p7zip-full", "unzip", "tree", "git", "git-lfs", "-y"] ] # 另一种等效形式 custom_sys_pkg_cmd = [ "apt update", "apt install aria2 google-perftools p7zip-full unzip tree git git-lfs -y", ] ``` 这将分别执行两条命令: ``` 1. apt update 2. apt install aria2 google-perftools p7zip-full unzip tree git git-lfs -y ``` Args: use_uv (bool | None): 使用 uv 代替 Pip 进行安装, 当 uv 安装 Python 软件包失败时, 将回退到 Pip 进行重试 custom_env (dict[str, str] | None): 自定义环境变量 custom_sys_pkg_cmd (list[list[str]] | list[str] | None): 自定义调用系统包管理器命令 Returns: bool: 组件安装结果 """ if custom_env is None: custom_env = os.environ.copy() if custom_sys_pkg_cmd is None: custom_sys_pkg_cmd = [ ["apt", "update"], [ "apt", "install", "aria2", "google-perftools", "p7zip-full", "unzip", "tree", "git", "git-lfs", "-y", ], ] try: logger.info("安装自身组件依赖中") pip_install("uv", "--upgrade", use_uv=False, custom_env=custom_env) pip_install( "modelscope", "huggingface_hub", "hf-xet", "requests", "tqdm", "wandb", "--upgrade", use_uv=use_uv, custom_env=custom_env, ) for cmd in custom_sys_pkg_cmd: run_cmd(cmd, custom_env=custom_env) return True except Exception as e: logger.error("安装自身组件依赖失败: %s", e) return False def install_pytorch( torch_package: str | list[str] | None = None, xformers_package: str | list[str] | None = None, pytorch_mirror: str | None = None, use_uv: bool | None = True, ) -> bool: """安装 PyTorch / xFormers Args: torch_package (str | list[str] | None): PyTorch 软件包名称和版本信息, 如`torch==2.0.0 torchvision==0.15.1` / `["torch==2.0.0", "torchvision==0.15.1"]` xformers_package (str | list[str] | None): xFormers 软件包名称和版本信息, 如`xformers==0.0.18` / `["xformers==0.0.18"]` pytorch_mirror (str | None): 指定安装 PyTorch / xFormers 时使用的镜像源 use_uv (bool | None): 是否使用 uv 代替 Pip 进行安装 Returns: bool: 安装 PyTorch / xFormers 成功时返回`True` """ custom_env = os.environ.copy() if pytorch_mirror is not None: logger.info("使用自定义 PyTorch 镜像源: %s", pytorch_mirror) custom_env.pop("PIP_EXTRA_INDEX_URL", None) custom_env.pop("PIP_FIND_LINKS", None) custom_env.pop("UV_INDEX", None) custom_env.pop("UV_FIND_LINKS", None) custom_env["PIP_INDEX_URL"] = pytorch_mirror custom_env["UV_DEFAULT_INDEX"] = pytorch_mirror if torch_package is not None: logger.info("安装 PyTorch 中") torch_package = torch_package.split() if isinstance(torch_package, str) else torch_package try: pip_install(*torch_package, use_uv=use_uv) logger.info("安装 PyTorch 成功") except Exception as e: logger.error("安装 PyTorch 时发生错误: %s", e) return False if xformers_package is not None: logger.info("安装 xFormers 中") xformers_package = xformers_package.split() if isinstance(xformers_package, str) else xformers_package try: pip_install(*xformers_package, use_uv=use_uv) logger.info("安装 xFormers 成功") except Exception as e: logger.error("安装 xFormers 时发生错误: %s", e) return False return True def install_requirements( path: Path | str, use_uv: bool | None = True, custom_env: dict[str, str] | None = None, cwd: Path | str | None = None, ) -> bool: """从 requirements.txt 文件指定安装的依赖 Args: path (Path | str): requirements.txt 文件路径 use_uv (bool | None): 是否使用 uv 代替 Pip 进行安装 custom_env (dict[str, str] | None): 自定义环境变量 cwd (Path | str | None): 执行 Pip / uv 时的起始路径 Returns: bool: 安装依赖成功时返回`True` """ if custom_env is None: custom_env = os.environ.copy() cwd = Path(cwd) if not isinstance(cwd, Path) and cwd is not None else cwd path = Path(path) if not isinstance(path, Path) and path is not None else path try: logger.info("从 %s 安装 Python 软件包中", path) pip_install("-r", path.as_posix(), use_uv=use_uv, custom_env=custom_env, cwd=cwd) logger.info("从 %s 安装 Python 软件包成功", path) return True except Exception as e: logger.info("从 %s 安装 Python 软件包时发生错误: %s", path, e) return False
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/env_manager.py
Python
agpl-3.0
7,772
"""文件操作工具""" import os import uuid import stat import shutil import traceback from pathlib import Path from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="File Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def remove_files(path: str | Path) -> bool: """文件删除工具 Args: path (str | Path): 要删除的文件路径 Returns: bool: 删除结果 """ def _handle_remove_readonly(_func, _path, _): """处理只读文件的错误处理函数""" if os.path.exists(_path): os.chmod(_path, stat.S_IWRITE) _func(_path) try: path_obj = Path(path) if path_obj.is_file(): os.chmod(path_obj, stat.S_IWRITE) path_obj.unlink() return True if path_obj.is_dir(): shutil.rmtree(path_obj, onerror=_handle_remove_readonly) return True logger.error("路径不存在: %s", path) return False except Exception as e: logger.error("删除失败: %s", e) return False def copy_files(src: Path | str, dst: Path | str) -> bool: """复制文件或目录 Args: src (Path | str): 源文件路径 dst (Path | str): 复制文件到指定的路径 Returns: bool: 复制结果 """ try: src_path = Path(src) dst_path = Path(dst) # 检查源是否存在 if not src_path.exists(): logger.error("源路径不存在: %s", src) return False # 如果目标是目录, 创建完整路径 if dst_path.is_dir(): dst_file = dst_path / src_path.name else: dst_file = dst_path # 确保目标目录存在 dst_file.parent.mkdir(parents=True, exist_ok=True) # 复制文件 if src_path.is_file(): shutil.copy2(src, dst_file) else: # 如果是目录, 使用 copytree if dst_file.exists(): shutil.rmtree(dst_file) shutil.copytree(src, dst_file) return True except PermissionError as e: logger.error("权限错误, 请检查文件权限或以管理员身份运行: %s", e) return False except Exception as e: logger.error("复制失败: %s", e) return False def generate_dir_tree( start_path: str | Path, max_depth: int | None = None, show_hidden: bool | None = False, ) -> None: """生成并打印目录树 Args: start_path (str | Path): 要开始遍历的根目录路径 max_depth (int | None): 要遍历的最大深度 show_hidden (bool | None): 是否显示隐藏文件 """ start_path = Path(start_path) if not isinstance(start_path, Path) and start_path is not None else start_path if not start_path.is_dir(): logger.error("目录 %s 不存在", start_path) return print(start_path) # 使用一个列表来传递计数, 因为列表是可变对象, 可以在递归中被修改 counts = [0, 0] # [目录数, 文件数] recursive_tree_builder(start_path, "", counts, 0, max_depth, show_hidden) print(f"\n{counts[0]} 个目录, {counts[1]} 个文件") def recursive_tree_builder( dir_path: Path, prefix: str, counts: list[int], current_depth: int, max_depth: int | None, show_hidden: bool | None, ) -> None: """递归地构建和打印目录树 Args: dir_path (Path): 当前正在遍历的目录路径 prefix (str): 用于当前行打印的前缀字符串 (包含树状连接符) counts (list[int]): 包含目录和文件计数的列表 current_depth (int): 当前的递归深度 max_depth (int | None): 允许的最大递归深度 show_hidden (bool | None): 是否显示隐藏文件 """ connectors_dict = { "T": "├── ", "L": "└── ", "I": "│ ", "S": " ", } if max_depth is not None and current_depth >= max_depth: return try: # 获取目录下所有条目 all_entries = dir_path.iterdir() # 如果不显示隐藏文件, 则过滤掉它们 if not show_hidden: entries_to_process = [e for e in all_entries if not e.name.startswith(".")] else: entries_to_process = list(all_entries) # 按名称排序 entries = sorted(entries_to_process, key=lambda p: p.name) except PermissionError: print(f"{prefix}└── [权限错误, 无法访问]") return num_entries = len(entries) for i, entry in enumerate(entries): is_last = i == num_entries - 1 connector = connectors_dict["L"] if is_last else connectors_dict["T"] print(f"{prefix}{connector}{entry.name}") if entry.is_dir(): counts[0] += 1 # 递归调用的前缀: 如果当前是最后一个条目, 则下一级不再需要垂直线 new_prefix = prefix + (connectors_dict["S"] if is_last else connectors_dict["I"]) recursive_tree_builder(entry, new_prefix, counts, current_depth + 1, max_depth, show_hidden) else: counts[1] += 1 def get_file_list(path: Path | str, resolve: bool | None = False) -> list[Path]: """获取当前路径下的所有文件的绝对路径 Args: path (Path | str): 要获取文件列表的目录 resolve (bool | None): 将路径进行完全解析, 包括链接路径 Returns: list[Path]: 文件列表的绝对路径 """ path = Path(path) if not isinstance(path, Path) and path is not None else path if not path.exists(): return [] if path.is_file(): return [path.resolve() if resolve else path.absolute()] file_list: list[Path] = [] for root, _, files in os.walk(path): for file in files: file_path = Path(root) / file file_list.append(file_path.resolve() if resolve else file_path.absolute()) return file_list def get_sync_files(src_path: Path | str, dst_path: Path | str) -> list[Path]: """获取需要进行同步的文件列表 (增量同步) Args: src_path (Path | str): 同步文件的源路径 dst_path (Path | str): 同步文件到的路径 Returns: list[Path]: 要进行同步的文件 """ from tqdm import tqdm if not isinstance(src_path, Path) and src_path is not None: src_path = Path(src_path) if not isinstance(dst_path, Path) and dst_path is not None: dst_path = Path(dst_path) src_is_file = src_path.is_file() src_files = get_file_list(src_path) logger.info("%s 中的文件数量: %s", src_path, len(src_files)) dst_files = get_file_list(dst_path) logger.info("%s 中的文件数量: %s", dst_path, len(dst_files)) if src_path.is_dir() and dst_path.is_file(): logger.warning("%s 为目录, 而 %s 为文件, 无法进行复制", src_path, dst_path) sync_file_list = [] else: dst_files_set = set(dst_files) # 加快统计速度 sync_file_list = [ x for x in tqdm(src_files, desc="计算需要同步的文件") if (dst_path / x.relative_to(src_path if not src_is_file else src_path.parent)) not in dst_files_set ] logger.info("要进行同步的文件数量: %s", len(sync_file_list)) return sync_file_list def sync_files(src_path: Path, dst_path: Path) -> None: """同步文件 (增量同步) Args: src_path (Path): 同步文件的源路径 dst_path (Path): 同步文件到的路径 """ from tqdm import tqdm logger.info("增量同步文件: %s -> %s", src_path, dst_path) file_list = get_sync_files(src_path, dst_path) if len(file_list) == 0: logger.info("没有需要同步的文件") return for file in tqdm(file_list, desc="同步文件"): dst = dst_path / file.relative_to(src_path) try: dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy(file, dst) except Exception as e: traceback.print_exc() logger.error("同步 %s 到 %s 时发生错误: %s", file, dst, e) if dst.exists(): logger.warning("删除未复制完成的文件: %s", dst) try: os.remove(dst) except Exception as e1: logger.error("删除未复制完成的文件失败: %s", e1) logger.info("同步文件完成") def sync_files_and_create_symlink( src_path: Path | str, link_path: Path | str, src_is_file: bool | None = False, ) -> None: """同步文件并创建软链接 当源路径不存在时, 则尝试创建源路径, 并检查链接路径状态 链接路径若已存在, 并且存在文件, 将检查链接路径中的文件是否存在于源路径中 在链接路径存在但在源路径不存在的文件将被复制 (增量同步) 完成增量同步后将链接路径属性, 若为实际路径则对该路径进行重命名; 如果为链接路径则删除链接 链接路径清理完成后, 在链接路径为源路径创建软链接 Args: src_path (Path | str): 源路径 link_path (Path | str): 软链接路径 src_is_file (bool | None): 源路径是否为文件 """ src_path = Path(src_path) if not isinstance(src_path, Path) and src_path is not None else src_path link_path = Path(link_path) if not isinstance(link_path, Path) and link_path is not None else link_path logger.info("链接路径: %s -> %s", src_path, link_path) try: if src_is_file: src_path.parent.mkdir(parents=True, exist_ok=True) else: src_path.mkdir(parents=True, exist_ok=True) if link_path.exists(): sync_files( src_path=link_path, dst_path=src_path if not src_is_file else src_path.parent, ) if link_path.is_symlink(): link_path.unlink() else: shutil.move( link_path, link_path.parent / str(uuid.uuid4()), ) link_path.symlink_to(src_path) except Exception as e: logger.error("创建 %s -> %s 的路径链接失败: %s", src_path, link_path, e)
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/file_manager.py
Python
agpl-3.0
10,513
"""Git 调用工具""" import os import traceback from pathlib import Path from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR from sd_webui_all_in_one.cmd import run_cmd logger = get_logger( name="Git Warpper", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def clone( repo: str, path: Path | str | None = None, ) -> Path | None: """下载 Git 仓库到本地 Args: repo (str): Git 仓库链接 path (Path | str | None): 下载到本地的路径 Returns: (Path | None): 下载成功时返回路径, 否则返回`None` """ if path is None: path = os.getcwd() path = Path(path) if not isinstance(path, Path) and path is not None else path try: logger.info("下载 %s 到 %s 中", repo, path) run_cmd(["git", "clone", "--recurse-submodules", repo, path.as_posix()]) return path except Exception as e: logger.error("下载 %s 失败: %s", repo, e) return None def update(path: Path | str) -> bool: """更新 Git 仓库 Args: path (Path | str): Git 仓库路径 Returns: bool: 更新 Git 仓库结果 """ path = Path(path) if not isinstance(path, Path) and path is not None else path use_submodule = [] try: logger.info("拉取 %s 更新中", path) if check_point_offset(path): if fix_point_offset(path): logger.error("更新 %s 失败", path) return False if ( len( run_cmd( ["git", "-C", path.as_posix(), "submodule", "status"], live=False, ).strip() ) != 0 ): use_submodule = ["--recurse-submodules"] run_cmd(["git", "-C", path.as_posix(), "submodule", "init"]) run_cmd(["git", "-C", path.as_posix(), "fetch", "--all"] + use_submodule) branch = get_current_branch(path) ref = run_cmd( ["git", "-C", path.as_posix(), "symbolic-ref", "--quiet", "HEAD"], live=False, ) if check_repo_on_origin_remote(path): origin_branch = f"origin/{branch}" else: origin_branch = str.replace(ref, "refs/heads/", "", 1) try: run_cmd( [ "git", "-C", path.as_posix(), "config", "--get", f"branch.{origin_branch}.remote", ], live=False, ) origin_branch = run_cmd( [ "git", "-C", path.as_posix(), "rev-parse", "--abbrev-ref", f"{origin_branch}@{{upstream}}", ], live=False, ) except Exception as _: pass run_cmd(["git", "-C", path.as_posix(), "reset", "--hard", origin_branch] + use_submodule) logger.info("更新 %s 完成", path) return True except Exception as e: logger.error("更新 %s 时发生错误: %s", path.as_posix(), e) return False def check_point_offset(path: Path | str) -> bool: """检查 Git 仓库的指针是否游离 Args: path (Path | str): Git 仓库路径 Returns: bool: 当 Git 指针游离时返回`True` """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: run_cmd(["git", "-C", path.as_posix(), "symbolic-ref", "HEAD"], live=False) return False except Exception as _: return True def fix_point_offset(path: Path | str) -> bool: """修复 Git 仓库的 Git 指针游离 Args: path (Path | str): Git 仓库路径 Returns: bool: 修复结果 """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: logger.info("修复 %s 的 Git 指针游离中", path) # run_cmd(["git", "-C", path.as_posix(), "remote", "prune", "origin"]) run_cmd(["git", "-C", path.as_posix(), "submodule", "init"]) branch_info = run_cmd(["git", "-C", path.as_posix(), "branch", "-a"], live=False) main_branch = None for info in branch_info.split("\n"): if "/HEAD" in info: main_branch = info.split(" -> ").pop().strip().split("/").pop() break if main_branch is None: logger.error("未找到 %s 主分支, 无法修复 Git 指针游离", path) return False logger.info("%s 主分支: %s", path.as_posix(), main_branch) run_cmd(["git", "-C", path.as_posix(), "checkout", main_branch]) run_cmd( [ "git", "-C", path.as_posix(), "reset", "--recurse-submodules", "--hard", f"origin/{main_branch}", ] ) logger.info("修复 %s 的 Git 指针游离完成", path) return True except Exception as e: logger.error("修复 %s 的 Git 指针游离失败: %s", path, e) traceback.print_exc() return False def get_current_branch(path: Path | str) -> str | None: """获取 Git 仓库的当前所处分支 Args: path (Path | str): Git 仓库路径 Returns: (str | None): 仓库所处分支, 获取失败时返回`None` """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: return run_cmd(["git", "-C", path.as_posix(), "branch", "--show-current"], live=False).strip() except Exception as e: logger.error("获取 %s 当前分支失败: %s", path, e) return None def check_repo_on_origin_remote(path: Path | str) -> bool: """检查 Git 仓库的远程源是否在 origin Args: path (Path | str): Git 仓库路径 Returns: bool: 远程源在 origin 时返回`True` """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: current_branch = get_current_branch(path) run_cmd( [ "git", "-C", path.as_posix(), "show-ref", "--verify", "--quiet", f"refs/remotes/origin/{current_branch}", ], live=False, ) return True except Exception as _: return False def check_local_branch_exists( path: Path | str, branch: str, ) -> bool: """检查 Git 仓库是否存在某个本地分支 Args: path (Path | str): Git 仓库路径 branch (str): 要检查的本地分支 Returns: bool: 分支存在时返回`True` """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: run_cmd( [ "git", "-C", path.as_posix(), "show-ref", "--verify", "--quiet", f"refs/heads/{branch}", ], live=False, ) return True except Exception as _: return False def switch_branch( path: Path | str, branch: str, new_url: str | None = None, recurse_submodules: bool | None = False, ) -> bool: """切换 Git 仓库的分支和远程源 Args: path (Path | str): Git 仓库路径 branch (str): 要切换的分支 new_url (str | None): 要切换的远程源 recurse_submodules (bool | None): 是否启用 Git 子模块 Returns: bool: 切换分支结果 """ path = Path(path) if not isinstance(path, Path) and path is not None else path custom_env = os.environ.copy() custom_env.pop("GIT_CONFIG_GLOBAL", None) try: current_url = run_cmd( ["git", "-C", path.as_posix(), "remote", "get-url", "origin"], custom_env=custom_env, live=False, ) except Exception as e: current_url = "None" logger.warning("获取 %s 原有的远程源失败: %s", path, e) use_submodules = ["--recurse-submodules"] if recurse_submodules else [] if new_url is not None: logger.info("替换 %s 远程源: %s -> %s", path, current_url, new_url) try: run_cmd( [ "git", "-C", path.as_posix(), "remote", "set-url", "origin", new_url, ] ) except Exception as e: logger.error("替换 %s 远程源失败: %s", path, e) return False if recurse_submodules: try: run_cmd( [ "git", "-C", path.as_posix(), "submodule", "update", "--init", "--recursive", ] ) except Exception as e: logger.warning("更新 %s 的 Git 子模块信息发生错误: %s", path, e) else: try: run_cmd(["git", "-C", path.as_posix(), "submodule", "deinit", "--all", "-f"]) except Exception as e: logger.warning("更新 %s 的 Git 子模块信息发生错误: %s", path, e) logger.info("拉取 %s 远程源更新中", path) try: run_cmd(["git", "-C", path.as_posix(), "fetch"]) run_cmd(["git", "-C", path.as_posix(), "submodule", "deinit", "--all", "-f"]) if not check_local_branch_exists(path, branch): run_cmd(["git", "-C", path.as_posix(), "branch", branch]) run_cmd(["git", "-C", path.as_posix(), "checkout", branch, "--force"]) logger.info("应用 %s 的远程源最新内容中", path) if recurse_submodules: run_cmd( [ "git", "-C", path.as_posix(), "reset", "--hard", f"origin/{branch}", ] ) run_cmd(["git", "-C", path.as_posix(), "submodule", "deinit", "--all", "-f"]) run_cmd( [ "git", "-C", path.as_posix(), "submodule", "update", "--init", "--recursive", ] ) run_cmd(["git", "-C", path.as_posix(), "reset", "--hard", f"origin/{branch}"] + use_submodules) logger.info("切换 %s 分支到 %s 完成", path, branch) return True except Exception as e: logger.error("切换 %s 分支到 %s 失败: %s", path, branch, e) logger.warning("回退分支切换") try: run_cmd( [ "git", "-C", path.as_posix(), "remote", "set-url", "origin", current_url, ] ) if recurse_submodules: run_cmd( [ "git", "-C", path.as_posix(), "submodule", "deinit", "--all", "-f", ] ) else: run_cmd( [ "git", "-C", path.as_posix(), "submodule", "update", "--init", "--recursive", ] ) except Exception as e1: logger.error("回退分支切换失败: %s", e1) return False def switch_commit( path: Path | str, commit: str, ) -> bool: """切换 Git 仓库到指定提交记录上 Args: path (Path | str): Git 仓库路径 commit (str): Git 仓库提交记录 Returns: bool: 切换结果 """ path = Path(path) if not isinstance(path, Path) and path is not None else path logger.info("切换 %s 的 Git 指针到 %s 版本", path, commit) try: run_cmd(["git", "-C", path.as_posix(), "reset", "--hard", commit]) return True except Exception as e: logger.error("切换 %s 的 Git 指针到 %s 版本时失败: %s", path, commit, e) return False def is_git_repo(path: Path | str) -> bool: """检查该路径是否为 Git 仓库路径 Args: path (Path | str): 要检查的路径 Returns: bool: 当该路径为 Git 仓库时返回`True` """ path = Path(path) if not isinstance(path, Path) and path is not None else path try: run_cmd(["git", "-C", path.as_posix(), "rev-parse", "--git-dir"], live=False) return True except Exception as _: return False def set_git_config( username: str | None = None, email: str | None = None, ) -> bool: """配置 Git 信息 Args: username (str | None): 用户名 email (str | None): 邮箱地址 Returns: bool: 配置成功时返回`True` """ logger.info("配置 Git 信息中") try: if username is not None: run_cmd(["git", "config", "--global", "user.name", username]) if email is not None: run_cmd(["git", "config", "--global", "user.email", email]) return True except Exception as e: logger.error("配置 Git 信息时发生错误: %s", e) return False
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/git_warpper.py
Python
agpl-3.0
14,176
"""Kaggle 工具集""" from pathlib import Path from sd_webui_all_in_one.file_manager import copy_files, generate_dir_tree from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.config import LOGGER_LEVEL, LOGGER_COLOR logger = get_logger( name="Kaggle Tools", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) def get_kaggle_secret(key: str) -> str | None: """获取 Kaggle Secret Args: key (str): Kaggle Secret 名称 Returns: (str | None): Kaggle Secret 名称对应的密钥 """ try: from kaggle_secrets import UserSecretsClient except Exception as e: logger.error("无法导入 Kaggle 工具, 获取 Kaggle Secret 失败: %s", e) return None try: return UserSecretsClient().get_secret(key) except Exception: logger.error("密钥 %s 不存在") return None def import_kaggle_input( output_path: Path | str, ) -> None: """从 Kaggle Input 文件夹中导入文件 Args: output_path (Path|str): 导出文件的路径 """ kaggle_input_path = Path("/kaggle/input") output_path = Path(output_path) if not isinstance(output_path, Path) and output_path is not None else output_path logger.info("从 Kaggle Input 导入文件: %s -> %s", kaggle_input_path, output_path) if kaggle_input_path.is_dir() and any(kaggle_input_path.iterdir()): count = 0 task_sum = sum(1 for _ in kaggle_input_path.iterdir()) for i in kaggle_input_path.iterdir(): count += 1 logger.info("[%s/%s] 导入 %s", count, task_sum, i.name) copy_files(i, output_path) logger.info("Kaggle Input 导入完成") return logger.info("Kaggle Input 无可导入的文件") def display_model_and_dataset_dir( model_path: Path | str = None, dataset_path: Path | str = None, recursive: bool | None = False, show_hidden: bool | None = True, ) -> None: """列出模型文件夹和数据集文件夹的文件列表 Args: model_path (Path | str | None): 要展示的路径 dataset_path (Path | str | None): 要展示的路径 recursive (bool | None): 递归显示子目录的内容 show_hidden (bool | None)`: 显示隐藏文件 """ model_path = Path(model_path) if not isinstance(model_path, Path) and model_path is not None else model_path dataset_path = Path(dataset_path) if not isinstance(dataset_path, Path) and dataset_path is not None else dataset_path if model_path is not None and model_path.is_dir(): logger.info("模型目录中的文件列表") generate_dir_tree( start_path=model_path, max_depth=None if recursive else 1, show_hidden=show_hidden, ) else: logger.info("模型目录不存在") if dataset_path is not None and dataset_path.is_dir(): logger.info("数据集目录中的文件列表") generate_dir_tree( start_path=dataset_path, max_depth=None if recursive else 1, show_hidden=show_hidden, ) else: logger.info("数据集目录不存在")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/kaggle_tools.py
Python
agpl-3.0
3,188
"""日志工具""" import os import sys import copy import inspect import logging class LoggingColoredFormatter(logging.Formatter): """Logging 格式化类 Attributes: color (bool): 是否启用日志颜色 COLORS (dict[str, str]): 颜色类型字典 """ COLORS = { "DEBUG": "\033[0;36m", # CYAN "INFO": "\033[0;32m", # GREEN "WARNING": "\033[0;33m", # YELLOW "ERROR": "\033[0;31m", # RED "CRITICAL": "\033[0;37;41m", # WHITE ON RED "RESET": "\033[0m", # RESET COLOR } def __init__( self, fmt: str | None = None, datefmt: str | None = None, color: bool | None = True, ) -> None: """Logging 初始化 Args: fmt (str | None): 日志消息的格式字符串 datefmt (str | None): 日期 / 时间的显示格式 color (bool | None): 是否启用彩色日志输出. 默认为 True """ super().__init__(fmt, datefmt) self.color = color def format(self, record: logging.LogRecord) -> str: colored_record = copy.copy(record) levelname = colored_record.levelname if self.color: seq = self.COLORS.get(levelname, self.COLORS["RESET"]) colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}" return super().format(colored_record) def get_logger(name: str | None = None, level: int | None = logging.INFO, color: bool | None = True) -> logging.Logger: """获取 Loging 对象 Args: name (str | None): Logging 名称 level (int | None): 日志级别 color (bool | None): 是否启用彩色日志 Returns: logging.Logger: Logging 对象 """ stack = inspect.stack() calling_filename = os.path.basename(stack[1].filename) if name is None: name = calling_filename _logger = logging.getLogger(name) _logger.propagate = False if not _logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( LoggingColoredFormatter( r"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s", r"%Y-%m-%d %H:%M:%S", color=color, ) ) _logger.addHandler(handler) _logger.setLevel(level) _logger.debug("Logger 初始化完成") return _logger
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/logger.py
Python
agpl-3.0
2,415
"""管理工具基础类""" import re import os import subprocess import shlex from pathlib import Path from typing import Literal from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.tunnel import TunnelManager from sd_webui_all_in_one.repo_manager import RepoManager from sd_webui_all_in_one.downloader import download_file, download_archive_and_unpack from sd_webui_all_in_one.optimize.tcmalloc import TCMalloc from sd_webui_all_in_one.utils import check_gpu, in_jupyter, clear_up from sd_webui_all_in_one.colab_tools import is_colab_environment from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL, SD_WEBUI_ALL_IN_ONE_PATCHER_PATH, SD_WEBUI_ALL_IN_ONE_PATCHER from sd_webui_all_in_one.file_manager import copy_files, sync_files_and_create_symlink from sd_webui_all_in_one.kaggle_tools import display_model_and_dataset_dir, import_kaggle_input from sd_webui_all_in_one.cmd import run_cmd from sd_webui_all_in_one.file_manager import remove_files logger = get_logger( name="Base Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class BaseManager: """管理工具基础类 Attributes: workspace (Path): 工作区路径 workfolder (str): 工作区的文件夹名称 repo (RepoManager): 仓库管理器实例, 用于 HuggingFace / ModelScope 仓库操作 tun (TunnelManager): 隧道管理器实例, 用于内网穿透 tcmalloc (TCMalloc): TCMalloc 内存分配器实例 copy_files (Callable): 文件复制函数引用 import_kaggle_input (Callable): Kaggle Input 导入函数引用 display_model_and_dataset_dir (Callable): 展示模型 / 数据集目录函数引用 clear_up (Callable): 清理 Jupyter 输出函数引用 download_file (Callable): 文件下载函数引用 download_archive_and_unpack (Callable): 下载压缩包并解压的函数引用 run_cmd (Callable): Shell 命令执行函数引用 remove_files (Callable): 删除文件函数引用 """ def __init__( self, workspace: str | Path, workfolder: str, hf_token: str | None = None, ms_token: str | None = None, port: int | None = 7860, ) -> None: """管理工具初始化 Args: workspace (str | Path): 工作区路径 workfolder (str): 工作区的文件夹名称 hf_token (str | None): HuggingFace Token ms_token (str | None): ModelScope Token port (int | None): 内网穿透端口 """ self.workspace = Path(workspace) self.workspace.mkdir(parents=True, exist_ok=True) self.workfolder = workfolder self.repo = RepoManager(hf_token, ms_token) self.tun = TunnelManager(workspace, port) self.tcmalloc = TCMalloc(workspace) self.copy_files = copy_files self.import_kaggle_input = import_kaggle_input self.display_model_and_dataset_dir = display_model_and_dataset_dir self.clear_up = clear_up self.download_file = download_file self.download_archive_and_unpack = download_archive_and_unpack self.run_cmd = run_cmd self.remove_files = remove_files if SD_WEBUI_ALL_IN_ONE_PATCHER: logger.debug("配置 SD WebUI All In One 补丁模块") if "PYTHONPATH" in os.environ and os.environ["PYTHONPATH"]: os.environ["PYTHONPATH"] = SD_WEBUI_ALL_IN_ONE_PATCHER_PATH.as_posix() + os.pathsep + os.environ["PYTHONPATH"] else: os.environ["PYTHONPATH"] = SD_WEBUI_ALL_IN_ONE_PATCHER_PATH.as_posix() logger.debug("PYTHONPATH: %s", os.getenv("PYTHONPATH")) def restart_repo_manager( self, hf_token: str | None = None, ms_token: str | None = None, ) -> None: """重新初始化 HuggingFace / ModelScope 仓库管理工具 Args: hf_token (str | None): HugggingFace Token, 不为`None`时配置`HF_TOKEN`环境变量 ms_token (str | None): ModelScope Token, 不为`None`时配置`MODELSCOPE_API_TOKEN`环境变量 """ logger.info("重启 HuggingFace / ModelScope 仓库管理模块") self.repo = RepoManager( hf_token=hf_token, ms_token=ms_token, ) def get_model( self, url: str, path: str | Path, filename: str | None = None, tool: Literal["aria2", "request"] = "aria2", retry: int | None = 3, ) -> Path | None: """下载模型文件到本地中 Args: url (str): 模型文件的下载链接 path (str | Path): 模型文件下载到本地的路径 filename (str | None): 指定下载的模型文件名称 tool (Literal["aria2", "request"]): 下载工具 retry (int | None): 重试下载的次数, 默认为 3 Returns: (Path | None): 文件保存路径 """ return download_file(url=url, path=path, save_name=filename, tool=tool, retry=retry) def get_model_from_list(self, path: str | Path, model_list: list[str, int], retry: int | None = 3) -> None: """从模型列表下载模型 `model_list`需要指定模型下载的链接和下载状态, 例如 ```python model_list = [ ["url1", 0], ["url2", 1], ["url3", 0], ["url4", 1, "file.safetensors"] ] ``` 在这个例子中, 第一个参数指定了模型的下载链接, 第二个参数设置了是否要下载这个模型, 当这个值为 1 时则下载该模型 第三个参数是可选参数, 用于指定下载到本地后的文件名称 则上面的例子中`url2`和`url4`下载链接所指的文件将被下载, 并且`url4`所指的文件将被重命名为`file.safetensors` Args: path (str | Path): 将模型下载到的本地路径 model_list (list[str | int]): 模型列表 retry (int | None): 重试下载的次数, 默认为 3 """ for model in model_list: try: url = model[0] status = model[1] filename = model[2] if len(model) > 2 else None except Exception as e: logger.error("模型下载列表长度不合法: %s\n出现异常的列表:%s", e, model) continue if status >= 1: if filename is None: self.get_model(url=url, path=path, retry=retry) else: self.get_model(url=url, path=path, filename=filename, retry=retry) def check_avaliable_gpu(self) -> bool: """检测当前环境是否有 GPU Returns: bool: 环境有可用 GPU 时返回`True` Raises: RuntimeError: 环境中无 GPU 时引发错误 """ if not check_gpu(): if is_colab_environment(): notice = "没有可用的 GPU, 请在 Colab -> 代码执行程序 > 更改运行时类型 -> 硬件加速器 选择 GPU T4\n如果不能使用 GPU, 请尝试更换账号!" else: notice = "没有可用的 GPU, 请在 kaggle -> Notebook -> Session options -> ACCELERATOR 选择 GPU T4 x 2\n如果不能使用 GPU, 请检查 Kaggle 账号是否绑定了手机号或者尝试更换账号!" raise RuntimeError(notice) return True def link_to_google_drive( self, base_dir: Path, drive_path: Path, links: list[dict[str, str | bool]], ) -> None: """将 Colab 中的文件夹 / 文件链接到 Google Drive 中 挂载额外目录需要使用`link_dir`指定要挂载的路径, 并且使用相对路径指定 若额外链接路径为文件, 需指定`is_file`属性为`True` 例如: ```python links = [ {"link_dir": "models/loras"}, {"link_dir": "custom_nodes"}, {"link_dir": "extra_model_paths.yaml", "is_file": True}, ] ``` Args: base_dir (Path): 链接的根路径 drive_path (Path): 链接到的 Google Drive 的路径 links (list[dict[str, str | bool]]): 要进行链接文件的路径表 """ for link in links: link_dir = link.get("link_dir") is_file = link.get("is_file", False) if link_dir is None: continue full_link_path = base_dir / link_dir full_drive_path = drive_path / link_dir if is_file and (not full_link_path.exists() and not full_drive_path.exists()): # 链接路径指定的是文件并且源文件和链接文件都不存在时则取消链接 continue sync_files_and_create_symlink( src_path=full_drive_path, link_path=full_link_path, src_is_file=is_file, ) def parse_cmd_str_to_list(self, launch_args: str) -> list[str]: """解析命令行参数字符串,返回参数列表 Args: launch_args (str): 命令行参数字符串 Returns: list[str]: 解析后的参数列表 """ if not launch_args: return [] # 去除首尾空格 trimmed_args = launch_args.strip() # 如果参数数量 <= 1, 使用简单分割 if len(trimmed_args.split()) <= 1: arguments = trimmed_args.split() else: # 使用正则表达式处理复杂情况 (包含引号的参数) pattern = r'("[^"]*"|\'[^\']*\'|\S+)' matches = re.findall(pattern, trimmed_args) # 去除参数两端的引号 arguments = [match.strip("\"'") for match in matches] return arguments def parse_cmd_list_to_str(self, cmd_list: list[str]) -> str: """将命令列表转换为命令字符串 Args: cmd_list (list[str]): 命令列表 Returns: str: 命令字符串 """ return shlex.join(cmd_list) def launch( self, name: str, base_path: Path | str, cmd: list[str] | str, display_mode: Literal["terminal", "jupyter"] | None = None, ) -> None: """启动 WebUI Args: name (str): 启动的名称 base_path (Path | str): 启动时得的根目录 cmd (list[str] | str | None): 启动 WebUI 的参数 display_mode (Literal["terminal", "jupyter"] | None): 执行子进程时使用的输出模式 """ if display_mode is None: if in_jupyter(): display_mode = "jupyter" else: display_mode = "terminal" logger.info("启动 %s 中", name) try: if display_mode == "jupyter": with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True, shell=True, cwd=base_path, encoding="utf-8", errors="replace", ) as p: for line in p.stdout: print(line, end="", flush=True) elif display_mode == "terminal": subprocess.run( cmd, shell=True, cwd=base_path, encoding="utf-8", errors="replace", ) else: logger.error("未知的显示模式: %s", display_mode) except KeyboardInterrupt: logger.info("关闭 %s", name)
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/base_manager.py
Python
agpl-3.0
11,907
"""ComfyUI 管理工具""" import os import sys from pathlib import Path from typing import Literal from sd_webui_all_in_one import git_warpper from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.downloader import download_file from sd_webui_all_in_one.mirror_manager import set_mirror from sd_webui_all_in_one.env_check.fix_torch import fix_torch_libomp from sd_webui_all_in_one.env_check.fix_numpy import check_numpy from sd_webui_all_in_one.utils import warning_unexpected_params from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL from sd_webui_all_in_one.optimize.cuda_malloc import set_cuda_malloc from sd_webui_all_in_one.env import configure_env_var, configure_pip from sd_webui_all_in_one.env_check.fix_dependencies import py_dependency_checker from sd_webui_all_in_one.colab_tools import is_colab_environment, mount_google_drive from sd_webui_all_in_one.env_check.onnxruntime_gpu_check import check_onnxruntime_gpu from sd_webui_all_in_one.env_check.comfyui_env_analyze import comfyui_conflict_analyzer from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, install_requirements logger = get_logger( name="ComfyUI Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class ComfyUIManager(BaseManager): """ComfyUI 管理工具""" def mount_drive( self, extras: list[dict[str, str | bool]] = None, ) -> None: """挂载 Google Drive 并创建 ComfyUI 输出文件夹 挂载额外目录需要使用`link_dir`指定要挂载的路径, 并且使用相对路径指定 相对路径的起始位置为`{self.workspace}/{self.workfolder}` 若额外链接路径为文件, 需指定`is_file`属性为`True` 例如: ```python extras = [ {"link_dir": "models/loras"}, {"link_dir": "custom_nodes"}, {"link_dir": "extra_model_paths.yaml", "is_file": True}, ] ``` 默认挂载的目录和文件: `output`, `user`, `input`, `extra_model_paths.yaml` Args: extras (list[dict[str, str | bool]]): 挂载额外目录 Raises: RuntimeError: 挂载 Google Drive 失败 """ if not is_colab_environment(): logger.warning("当前环境非 Colab, 无法挂载 Google Drive") return drive_path = Path("/content/drive") if not (drive_path / "MyDrive").exists(): if not mount_google_drive(drive_path): raise RuntimeError("挂载 Google Drive 失败, 请尝试重新挂载 Google Drive") drive_output = drive_path / "MyDrive" / "comfyui_output" comfyui_path = self.workspace / self.workfolder links: list[dict[str, str | bool]] = [ {"link_dir": "output"}, {"link_dir": "user"}, {"link_dir": "input"}, {"link_dir": "extra_model_paths.yaml", "is_file": True}, ] if extras is not None: links += extras self.link_to_google_drive( base_dir=comfyui_path, drive_path=drive_output, links=links, ) def get_sd_model( self, url: str, filename: str = None, model_type: str | None = "checkpoints", ) -> Path | None: """下载模型 Args: url (str): 模型的下载链接 filename (str | None): 模型下载后保存的名称 model_type (str | None): 模型的类型 Returns: Path | None: 模型保存路径 """ path = self.workspace / self.workfolder / "models" / model_type return self.get_model(url=url, path=path, filename=filename, tool="aria2") def get_sd_model_from_list( self, model_list: list[dict[str, str]], ) -> None: """从模型列表下载模型 `model_list`需要指定`url`(模型下载链接), 可选参数为`type`(模型类型), `filename`(模型保存名称), 例如 ```python model_list = [ {"url": "url1", "type": "checkpoints"}, {"url": "url2", "filename": "file.safetensors"}, {"url": "url3", "type": "loras", "filename": "lora1.safetensors"}, {"url": "url4"}, ] ``` Args: model_list (list[dict[str, str]]): 模型列表 """ for model in model_list: url = model.get("url") filename = model.get("filename") model_type = model.get("type", "checkpoints") self.get_sd_model(url=url, filename=filename, model_type=model_type) def install_config( self, setting: str | None = None, ) -> None: """下载 ComfyUI 配置文件 Args: setting ( str| None): ComfyUI 设置文件下载链接, 下载后将保存在`{self.workspace}/{self.workfolder}/user/default/comfy.settings.json` """ setting_path = self.workspace / self.workfolder / "user" / "default" logger.info("下载配置文件") if setting is not None: download_file( url=setting, path=setting_path, save_name="comfy.settings.json", ) def install_custom_node( self, custom_node: str, ) -> Path | None: """安装 ComfyUI 自定义节点 Args: custom_node (str): 自定义节点下载地址 Returns: (Path | None): 自定义节点安装路径 """ custom_node_path = self.workspace / self.workfolder / "custom_nodes" name = os.path.basename(custom_node) install_path = custom_node_path / name logger.info("安装 %s 自定义节点中", name) p = git_warpper.clone(repo=custom_node, path=install_path) if p is not None: logger.info("安装 %s 自定义节点完成", name) return p logger.error("安装 %s 自定义节点失败", name) return None def install_custom_nodes_from_list( self, custom_node_list: list[str], ) -> None: """安装 ComfyUI 自定义节点 Args: custom_node_list (list[str]): 自定义节点列表 """ logger.info("安装 ComfyUI 自定义节点中") for node in custom_node_list: self.install_custom_node(node) logger.info("安装 ComfyUI 自定义节点完成") def update_custom_nodes(self) -> None: """更新 ComfyUI 自定义节点""" custom_node_path = self.workspace / self.workfolder / "custom_nodes" custom_node_list = [x for x in custom_node_path.iterdir() if x.is_dir() and (x / ".git").is_dir()] for i in custom_node_list: logger.info("更新 %s 自定义节点中", i.name) if git_warpper.update(i): logger.info("更新 %s 自定义节点成功", i.name) else: logger.info("更新 %s 自定义节点失败", i.name) def check_env( self, use_uv: bool | None = True, install_conflict_component_requirement: bool | None = True, requirements_file: str | None = "requirements.txt", ) -> None: """检查 ComfyUI 运行环境 Args: use_uv (bool | None): 使用 uv 安装依赖 install_conflict_component_requirement (bool | None): 检测到冲突依赖时是否按顺序安装组件依赖 requirements_file (str | None): 依赖文件名 """ comfyui_path = self.workspace / self.workfolder requirement_path = comfyui_path / requirements_file py_dependency_checker(requirement_path=requirement_path, name="ComfyUI", use_uv=use_uv) comfyui_conflict_analyzer( comfyui_root_path=comfyui_path, install_conflict_component_requirement=install_conflict_component_requirement, use_uv=use_uv, ) fix_torch_libomp() check_onnxruntime_gpu(use_uv=use_uv, ignore_ort_install=True) check_numpy(use_uv=use_uv) def get_launch_command( self, params: list[str] | str | None = None, ) -> str: """获取 ComfyUI 启动命令 Args: params (list[str] | str | None): 启动 ComfyUI 的参数 Returns: str: 完整的启动 ComfyUI 的命令 """ comfyui_path = self.workspace / self.workfolder cmd = [Path(sys.executable).as_posix(), (comfyui_path / "main.py").as_posix()] if params is not None: if isinstance(params, str): cmd += self.parse_cmd_str_to_list(params) else: cmd += params return self.parse_cmd_list_to_str(cmd) def run( self, params: list[str] | str | None = None, display_mode: Literal["terminal", "jupyter"] | None = None, ) -> None: """启动 ComfyUI Args: params (list[str] | str | None): 启动 ComfyUI 的参数 display_mode (Literal["terminal", "jupyter"] | None): 执行子进程时使用的输出模式 """ self.launch( name="ComfyUI", base_path=self.workspace / self.workfolder, cmd=self.get_launch_command(params), display_mode=display_mode, ) def install( self, torch_ver: str | list[str] | None = None, xformers_ver: str | list[str] | None = None, use_uv: bool | None = True, pypi_index_mirror: str | None = None, pypi_extra_index_mirror: str | None = None, pypi_find_links_mirror: str | None = None, github_mirror: str | list[str] | None = None, huggingface_mirror: str | None = None, pytorch_mirror: str | None = None, comfyui_repo: str | None = None, comfyui_requirements: str | None = None, comfyui_setting: str | None = None, custom_node_list: list[str] | None = None, model_list: list[dict[str, str]] | None = None, check_avaliable_gpu: bool | None = False, enable_tcmalloc: bool | None = True, enable_cuda_malloc: bool | None = True, custom_sys_pkg_cmd: list[list[str]] | list[str] | bool | None = None, huggingface_token: str | None = None, modelscope_token: str | None = None, update_core: bool | None = True, *args, **kwargs, ) -> None: """安装 ComfyUI Args: torch_ver (str | list[str] | None): 指定的 PyTorch 软件包包名, 并包括版本号 xformers_ver (str | list[str] | None): 指定的 xFormers 软件包包名, 并包括版本号 use_uv (bool | None): 使用 uv 替代 Pip 进行 Python 软件包的安装 pypi_index_mirror (str | None): PyPI Index 镜像源链接 pypi_extra_index_mirror (str | None): PyPI Extra Index 镜像源链接 pypi_find_links_mirror (str | None): PyPI Find Links 镜像源链接 github_mirror (str | list[str] | None): Github 镜像源链接或者镜像源链接列表 huggingface_mirror (str | None): HuggingFace 镜像源链接 pytorch_mirror (str | None): PyTorch 镜像源链接 comfyui_repo (str | None): ComfyUI 仓库地址 comfyui_requirements (str | None): ComfyUI 依赖文件名 comfyui_setting (str | None): ComfyUI 设置文件下载链接 custom_node_list (list[str] | None): 自定义节点列表 model_list (list[dict[str, str]] | None): 模型下载列表 check_avaliable_gpu (bool | None): 是否检查可用的 GPU, 当检查时没有可用 GPU 将引发`Exception` enable_tcmalloc (bool | None): 是否启用 TCMalloc 内存优化 enable_cuda_malloc (bool | None): 启用 CUDA 显存优化 custom_sys_pkg_cmd (list[list[str]] | list[str] | bool | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能 huggingface_token (str | None): 配置 HuggingFace Token modelscope_token (str | None): 配置 ModelScope Token update_core (bool | None): 安装时更新内核和扩展 Raises: Exception: GPU 不可用 """ warning_unexpected_params( message="ComfyUIManager.install() 接收到不期望参数, 请检查参数输入是否正确", args=args, kwargs=kwargs, ) logger.info("开始安装 ComfyUI") if custom_sys_pkg_cmd is False: custom_sys_pkg_cmd = [] elif custom_sys_pkg_cmd is True: custom_sys_pkg_cmd = None os.chdir(self.workspace) comfyui_path = self.workspace / self.workfolder comfyui_repo = "https://github.com/comfyanonymous/ComfyUI" if comfyui_repo is None else comfyui_repo comfyui_setting = "https://github.com/licyk/sd-webui-all-in-one/raw/main/config/comfy.settings.json" if comfyui_setting is None else comfyui_setting requirements_path = comfyui_path / ("requirements.txt" if comfyui_requirements is None else comfyui_requirements) if check_avaliable_gpu: self.check_avaliable_gpu() set_mirror( pypi_index_mirror=pypi_index_mirror, pypi_extra_index_mirror=pypi_extra_index_mirror, pypi_find_links_mirror=pypi_find_links_mirror, github_mirror=github_mirror, huggingface_mirror=huggingface_mirror, ) configure_pip() configure_env_var() install_manager_depend( use_uv=use_uv, custom_sys_pkg_cmd=custom_sys_pkg_cmd, ) git_warpper.clone(comfyui_repo, comfyui_path) if custom_node_list is not None: self.install_custom_nodes_from_list(custom_node_list) if update_core: git_warpper.update(comfyui_path) self.update_custom_nodes() install_pytorch( torch_package=torch_ver, xformers_package=xformers_ver, pytorch_mirror=pytorch_mirror, use_uv=use_uv, ) install_requirements( path=requirements_path, use_uv=use_uv, cwd=comfyui_path, ) self.install_config(comfyui_setting) if model_list is not None: self.get_sd_model_from_list(model_list) self.restart_repo_manager( hf_token=huggingface_token, ms_token=modelscope_token, ) if enable_tcmalloc: self.tcmalloc.configure_tcmalloc() if enable_cuda_malloc: set_cuda_malloc() logger.info("ComfyUI 安装完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/comfyui_manager.py
Python
agpl-3.0
14,927
"""Fooocus 管理工具""" import os import sys import json from pathlib import Path from typing import Any, Literal from sd_webui_all_in_one import git_warpper from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.mirror_manager import set_mirror from sd_webui_all_in_one.env_check.fix_torch import fix_torch_libomp from sd_webui_all_in_one.utils import warning_unexpected_params from sd_webui_all_in_one.env_check.fix_numpy import check_numpy from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL from sd_webui_all_in_one.optimize.cuda_malloc import set_cuda_malloc from sd_webui_all_in_one.env import configure_env_var, configure_pip from sd_webui_all_in_one.downloader import MultiThreadDownloader, download_file from sd_webui_all_in_one.env_check.fix_dependencies import py_dependency_checker from sd_webui_all_in_one.colab_tools import is_colab_environment, mount_google_drive from sd_webui_all_in_one.env_check.onnxruntime_gpu_check import check_onnxruntime_gpu from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, install_requirements logger = get_logger( name="Fooocus Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class FooocusManager(BaseManager): """Fooocus 管理工具""" def mount_drive( self, extras: list[dict[str, str | bool]] = None, ) -> None: """挂载 Google Drive 并创建 Fooocus 输出文件夹 挂载额外目录需要使用`link_dir`指定要挂载的路径, 并且使用相对路径指定 相对路径的起始位置为`{self.workspace}/{self.workfolder}` 若额外链接路径为文件, 需指定`is_file`属性为`True` 例如: ```python extras = [ {"link_dir": "models/loras"}, {"link_dir": "custom_nodes"}, {"link_dir": "extra_model_paths.yaml", "is_file": True}, ] ``` 默认挂载的目录和文件: `outputs`, `presets`, `language`, `wildcards`, `config.txt` Args: extras (list[dict[str, str | bool]]): 挂载额外目录 Raises: RuntimeError: 挂载 Google Drive 失败 """ if not is_colab_environment(): logger.warning("当前环境非 Colab, 无法挂载 Google Drive") return drive_path = Path("/content/drive") if not (drive_path / "MyDrive").exists(): if not mount_google_drive(drive_path): raise RuntimeError("挂载 Google Drive 失败, 请尝试重新挂载 Google Drive") drive_output = drive_path / "MyDrive" / "fooocus_output" fooocus_path = self.workspace / self.workfolder links: list[dict[str, str | bool]] = [ {"link_dir": "outputs"}, {"link_dir": "presets"}, {"link_dir": "language"}, {"link_dir": "wildcards"}, {"link_dir": "config.txt", "is_file": True}, ] if extras is not None: links += extras self.link_to_google_drive( base_dir=fooocus_path, drive_path=drive_output, links=links, ) def get_sd_model( self, url: str, filename: str = None, model_type: str | None = "checkpoints", ) -> Path | None: """下载模型 Args: url (str): 模型的下载链接 filename (str | None): 模型下载后保存的名称 model_type (str | None): 模型的类型 Returns: (Path | None): 模型保存路径 """ path = self.workspace / self.workfolder / "models" / model_type return self.get_model(url=url, path=path, filename=filename, tool="aria2") def get_sd_model_from_list( self, model_list: list[dict[str, str]], ) -> None: """从模型列表下载模型 `model_list`需要指定`url`(模型下载链接), 可选参数为`type`(模型类型), `filename`(模型保存名称), 例如 ```python model_list = [ {"url": "url1", "type": "checkpoints"}, {"url": "url2", "filename": "file.safetensors"}, {"url": "url3", "type": "loras", "filename": "lora1.safetensors"}, {"url": "url4"}, ] ``` Args: model_list (list[dict[str, str]]): 模型列表 """ for model in model_list: url = model.get("url") filename = model.get("filename") model_type = model.get("type", "checkpoints") self.get_sd_model(url=url, filename=filename, model_type=model_type) def install_config( self, preset: str | None = None, translation: str | None = None, ) -> None: """下载 Fooocus 配置文件 Args: preset (str | None): Fooocus 预设文件下载链接, 下载后将保存在`{self.workspace}/{self.workfolder}/presets/custom.json` path_config (str | None): Fooocus 路径配置文件下载链接, 下载后将保存在`{self.workspace}/{self.workfolder}/config.txt` translation (str | None): Fooocus 翻译文件下载链接, 下载后将保存在`{self.workspace}/{self.workfolder}/language/zh.json` """ path = self.workspace / self.workfolder preset_path = path / "presets" language_path = path / "language" logger.info("下载配置文件") if preset is not None: download_file(url=preset, path=preset_path, save_name="custom.json") if translation is not None: download_file(url=translation, path=language_path, save_name="zh.json") def pre_download_model( self, path: str | Path, thread_num: int | None = 16, downloader: Literal["aria2", "request", "mix"] = "mix", ) -> None: """根据 Fooocus 配置文件预下载模型 Args: path (str | Path): Fooocus 配置文件路径 thread_num (int | None): 下载模型的线程数 downloader (Literal["aria2", "request", "mix"]): 预下载模型时使用的下载器 (`aria2`, `request`, `mix`) """ path = Path(path) if not isinstance(path, Path) and path is not None else path if path.exists(): try: with open(path, "r", encoding="utf8") as file: data = json.load(file) except Exception as e: logger.warning("打开 Fooocus 配置文件时出现错误: %s", e) data = {} else: data = {} if downloader == "aria2": sd_model_downloader = "aria2" vae_downloader = "aria2" embedding_downloader = "aria2" lora_downloader = "aria2" elif downloader == "requests": sd_model_downloader = "requests" vae_downloader = "requests" embedding_downloader = "requests" lora_downloader = "requests" elif downloader == "mix": sd_model_downloader = "aria2" vae_downloader = "aria2" embedding_downloader = "requests" lora_downloader = "requests" else: sd_model_downloader = "aria2" vae_downloader = "aria2" embedding_downloader = "aria2" lora_downloader = "aria2" sd_model_list: dict[str, str] = data.get("checkpoint_downloads", {}) lora_list: dict[str, str] = data.get("lora_downloads", {}) vae_list: dict[str, str] = data.get("vae_downloads", {}) embedding_list: dict[str, str] = data.get("embeddings_downloads", {}) fooocus_path = self.workspace / self.workfolder sd_model_path = fooocus_path / "models" / "checkpoints" lora_path = fooocus_path / "models" / "loras" vae_path = fooocus_path / "models" / "vae" embedding_path = fooocus_path / "models" / "embeddings" downloader_params: list[dict[str, Any]] = [] downloader_params += [ { "url": sd_model_list.get(i), "path": sd_model_path, "save_name": i, "tool": sd_model_downloader, } for i in sd_model_list ] downloader_params += [ { "url": lora_list.get(i), "path": lora_path, "save_name": i, "tool": lora_downloader, } for i in lora_list ] downloader_params += [ { "url": vae_list.get(i), "path": vae_path, "save_name": i, "tool": vae_downloader, } for i in vae_list ] downloader_params += [ { "url": embedding_list.get(i), "path": embedding_path, "save_name": i, "tool": embedding_downloader, } for i in embedding_list ] model_downloader = MultiThreadDownloader( download_func=download_file, download_kwargs_list=downloader_params, ) model_downloader.start(num_threads=thread_num) logger.info("预下载 Fooocus 模型完成") def check_env( self, use_uv: bool | None = True, requirements_file: str | None = "requirements_versions.txt", ) -> None: """检查 Fooocus 运行环境 Args: use_uv (bool | None): 使用 uv 安装依赖 requirements_file (str | None): 依赖文件名 """ sd_webui_path = self.workspace / self.workfolder requirement_path = sd_webui_path / requirements_file py_dependency_checker( requirement_path=requirement_path, name="Fooocus", use_uv=use_uv, ) fix_torch_libomp() check_onnxruntime_gpu(use_uv=use_uv, ignore_ort_install=True) check_numpy(use_uv=use_uv) def get_launch_command( self, params: list[str] | str | None = None, ) -> str: """获取 Fooocus 启动命令 Args: params (list[str] | str | None): 启动 Fooocus 的参数 Returns: str: 完整的启动 Fooocus 的命令 """ fooocus_path = self.workspace / self.workfolder cmd = [Path(sys.executable).as_posix(), (fooocus_path / "launch.py").as_posix()] if params is not None: if isinstance(params, str): cmd += self.parse_cmd_str_to_list(params) else: cmd += params return self.parse_cmd_list_to_str(cmd) def run( self, params: list[str] | str | None = None, display_mode: Literal["terminal", "jupyter"] | None = None, ) -> None: """启动 Fooocus Args: params (list[str] | str | None): Fooocus 启动参数 display_mode (Literal["terminal", "jupyter"] | None): 执行子进程时使用的输出模式 """ self.launch( name="Fooocus", base_path=self.workspace / self.workfolder, cmd=self.get_launch_command(params), display_mode=display_mode, ) def install( self, torch_ver: str | list[str] | None = None, xformers_ver: str | list[str] | None = None, use_uv: bool | None = True, pypi_index_mirror: str | None = None, pypi_extra_index_mirror: str | None = None, pypi_find_links_mirror: str | None = None, github_mirror: str | list[str] | None = None, huggingface_mirror: str | None = None, pytorch_mirror: str | None = None, fooocus_repo: str | None = None, fooocus_requirements: str | None = None, fooocus_preset: str | None = None, fooocus_translation: str | None = None, model_downloader: Literal["aria2", "request", "mix"] = "mix", download_model_thread: int | None = 16, check_avaliable_gpu: bool | None = False, enable_tcmalloc: bool | None = True, enable_cuda_malloc: bool | None = True, custom_sys_pkg_cmd: list[list[str]] | list[str] | bool | None = None, huggingface_token: str | None = None, modelscope_token: str | None = None, update_core: bool | None = True, *args, **kwargs, ) -> None: """安装 Fooocus Args: torch_ver (str | list[str] | None): 指定的 PyTorch 软件包包名, 并包括版本号 xformers_ver (str | list[str] | None): 指定的 xFormers 软件包包名, 并包括版本号 use_uv (bool | None): 使用 uv 替代 Pip 进行 Python 软件包的安装 pypi_index_mirror (str | None): PyPI Index 镜像源链接 pypi_extra_index_mirror (str | None): PyPI Extra Index 镜像源链接 pypi_find_links_mirror (str | None): PyPI Find Links 镜像源链接 github_mirror (str | list[str] | None): Github 镜像源链接或者镜像源链接列表 huggingface_mirror (str | None): HuggingFace 镜像源链接 pytorch_mirror (str | None): PyTorch 镜像源链接 fooocus_repo (str | None): Fooocus 仓库地址 fooocus_requirements (str | None): Fooocus 依赖文件名 fooocus_preset (str | None): Fooocus 预设文件下载链接 fooocus_translation (str | None): Fooocus 翻译文件下载地址 model_downloader (Literal["aria2", "request", "mix"]): 预下载模型时使用的模型下载器 download_model_thread (int | None): 预下载模型的线程 check_avaliable_gpu (bool | None): 是否检查可用的 GPU, 当检查时没有可用 GPU 将引发`Exception` enable_tcmalloc (bool | None): 是否启用 TCMalloc 内存优化 enable_cuda_malloc (bool | None): 启用 CUDA 显存优化 custom_sys_pkg_cmd (list[list[str]] | list[str] | bool | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能 huggingface_token (str | None): 配置 HuggingFace Token modelscope_token (str | None): 配置 ModelScope Token update_core (bool | None): 安装时更新内核和扩展 Raises: Exception: GPU 不可用 """ warning_unexpected_params( message="FooocusManager.install() 接收到不期望参数, 请检查参数输入是否正确", args=args, kwargs=kwargs, ) logger.info("开始安装 Fooocus") if custom_sys_pkg_cmd is False: custom_sys_pkg_cmd = [] elif custom_sys_pkg_cmd is True: custom_sys_pkg_cmd = None os.chdir(self.workspace) fooocus_path = self.workspace / self.workfolder fooocus_repo = "https://github.com/lllyasviel/Fooocus" if fooocus_repo is None else fooocus_repo fooocus_preset = "https://github.com/licyk/sd-webui-all-in-one/raw/main/config/fooocus_config.json" if fooocus_preset is None else fooocus_preset fooocus_translation = "https://github.com/licyk/sd-webui-all-in-one/raw/main/config/fooocus_zh_cn.json" if fooocus_translation is None else fooocus_translation requirements_path = fooocus_path / ("requirements_versions.txt" if fooocus_requirements is None else fooocus_requirements) config_file = fooocus_path / "presets" / "custom.json" if check_avaliable_gpu: self.check_avaliable_gpu() logger.info("Fooocus 内核分支: %s", fooocus_repo) logger.info("Fooocus 预设配置: %s", fooocus_preset) logger.info("Fooocus 翻译配置: %s", fooocus_translation) set_mirror( pypi_index_mirror=pypi_index_mirror, pypi_extra_index_mirror=pypi_extra_index_mirror, pypi_find_links_mirror=pypi_find_links_mirror, github_mirror=github_mirror, huggingface_mirror=huggingface_mirror, ) configure_pip() configure_env_var() install_manager_depend( use_uv=use_uv, custom_sys_pkg_cmd=custom_sys_pkg_cmd, ) git_warpper.clone(fooocus_repo, fooocus_path) if update_core: git_warpper.update(fooocus_path) install_pytorch( torch_package=torch_ver, xformers_package=xformers_ver, pytorch_mirror=pytorch_mirror, use_uv=use_uv, ) install_requirements( path=requirements_path, use_uv=use_uv, cwd=fooocus_path, ) self.install_config( preset=fooocus_preset, translation=fooocus_translation, ) self.restart_repo_manager( hf_token=huggingface_token, ms_token=modelscope_token, ) if enable_tcmalloc: self.tcmalloc.configure_tcmalloc() if enable_cuda_malloc: set_cuda_malloc() self.pre_download_model( path=config_file, thread_num=download_model_thread, downloader=model_downloader, ) logger.info("Fooocus 安装完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/fooocus_manager.py
Python
agpl-3.0
17,444
"""InvokeAI 管理工具""" import os import importlib.metadata from pathlib import Path from typing_extensions import Literal from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.mirror_manager import set_mirror from sd_webui_all_in_one.file_manager import get_file_list from sd_webui_all_in_one.env_check.fix_torch import fix_torch_libomp from sd_webui_all_in_one.env_check.fix_numpy import check_numpy from sd_webui_all_in_one.utils import warning_unexpected_params from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL from sd_webui_all_in_one.optimize.cuda_malloc import set_cuda_malloc from sd_webui_all_in_one.env import configure_env_var, configure_pip from sd_webui_all_in_one.colab_tools import is_colab_environment, mount_google_drive from sd_webui_all_in_one.env_check.onnxruntime_gpu_check import check_onnxruntime_gpu from sd_webui_all_in_one.package_analyzer.ver_cmp import version_decrement, version_increment from sd_webui_all_in_one.pytorch_mirror import get_pytorch_mirror_dict, get_pytorch_mirror_type from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, pip_install from sd_webui_all_in_one.package_analyzer.pkg_check import get_package_name, get_package_version, is_package_has_version logger = get_logger( name="InvokeAI Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class InvokeAIComponentManager: """InvokeAI 组件管理器 Attributes: pytorch_mirror_dict (dict[str, str] | None): PyTorch 镜像源字典, 需包含不同镜像源类型对应的镜像地址 """ def __init__(self, pytorch_mirror_dict: dict[str, str] = None) -> None: """InvokeAI 组件管理器初始化 Args: pytorch_mirror_dict (dict[str, str] | None): PyTorch 镜像源字典, 需包含不同镜像源类型对应的镜像地址 """ if pytorch_mirror_dict is None: pytorch_mirror_dict = get_pytorch_mirror_dict() self.pytorch_mirror_dict = pytorch_mirror_dict def update_pytorch_mirror_dict(self, pytorch_mirror_dict: dict[str, str]) -> None: """更新 PyTorch 镜像源字典 Args: pytorch_mirror_dict (dict[str, str]): PyTorch 镜像源字典, 需包含不同镜像源类型对应的镜像地址 """ logger.info("更新 PyTorch 镜像源信息") self.pytorch_mirror_dict = pytorch_mirror_dict def get_pytorch_mirror_url(self, mirror_type: str) -> str | None: """获取 PyTorch 类型对应的镜像源 Args: mirror_type (str): PyTorch 类型 Returns: (str | None): 对应的 PyTorch 镜像源 """ return self.pytorch_mirror_dict.get(mirror_type) def get_invokeai_require_torch_version(self) -> str: """获取 InvokeAI 依赖的 PyTorch 版本 Returns: str: PyTorch 版本 """ try: invokeai_requires = importlib.metadata.requires("invokeai") except Exception as _: return "2.2.2" torch_version = "torch==2.2.2" for require in invokeai_requires: if get_package_name(require) == "torch" and is_package_has_version(require): torch_version = require.split(";")[0] break if torch_version.startswith("torch>") and not torch_version.startswith("torch>="): return version_increment(get_package_version(torch_version)) elif torch_version.startswith("torch<") and not torch_version.startswith("torch<="): return version_decrement(get_package_version(torch_version)) elif torch_version.startswith("torch!="): return version_increment(get_package_version(torch_version)) else: return get_package_version(torch_version) def get_pytorch_mirror_type_for_ivnokeai( self, device_type: Literal["cuda", "rocm", "xpu", "cpu"], ) -> str: """获取 InvokeAI 安装 PyTorch 所需的 PyTorch 镜像源类型 Args: device_type (Literal["cuda", "rocm", "xpu", "cpu"]): 显卡设备类型 Returns: str: PyTorch 镜像源类型 """ torch_ver = self.get_invokeai_require_torch_version() return get_pytorch_mirror_type(torch_ver=torch_ver, device_type=device_type) def get_pytorch_for_invokeai(self) -> str: """获取 InvokeAI 所依赖的 PyTorch 包版本声明 Returns: str: PyTorch 包版本声明 """ pytorch_ver = [] try: invokeai_requires = importlib.metadata.requires("invokeai") except Exception as _: invokeai_requires = [] torch_added = False torchvision_added = False torchaudio_added = False for require in invokeai_requires: require = require.split(";")[0].strip() package_name = get_package_name(require) if package_name == "torch" and not torch_added: pytorch_ver.append(require) torch_added = True if package_name == "torchvision" and not torchvision_added: pytorch_ver.append(require) torchvision_added = True if package_name == "torchaudio" and not torchaudio_added: pytorch_ver.append(require) torchaudio_added = True return " ".join([str(x).strip() for x in pytorch_ver]) def get_xformers_for_invokeai(self) -> str: """获取 InvokeAI 所依赖的 xFormers 包版本声明 Returns: str: xFormers 包版本声明 """ pytorch_ver = [] try: invokeai_requires = importlib.metadata.requires("invokeai") except Exception as _: invokeai_requires = [] xformers_added = False for require in invokeai_requires: require = require.split(";")[0].strip() package_name = get_package_name(require) if package_name == "xformers" and not xformers_added: pytorch_ver.append(require) xformers_added = True return " ".join([str(x).strip() for x in pytorch_ver]) def sync_invokeai_component( self, device_type: str, use_uv: bool | None = True, ) -> None: """同步 InvokeAI 组件 Args: device_type (str): 显卡设备类型 use_uv (bool | None): 是否使用 uv 安装 Python 软件包 Returns: bool: 同步组件结果 """ logger.info("获取安装配置") invokeai_ver = importlib.metadata.version("invokeai") torch_ver = self.get_invokeai_require_torch_version() pytorch_mirror_type = get_pytorch_mirror_type( torch_ver=torch_ver, device_type=device_type, ) pytorch_mirror = self.get_pytorch_mirror_url(pytorch_mirror_type) pytorch_package = self.get_pytorch_for_invokeai() xformers_package = self.get_xformers_for_invokeai() logger.debug("InvokeAI 所需的 PyTorch 版本: %s", torch_ver) logger.debug("InvokeAI 使用的 PyTorch 镜像源类型: %s", pytorch_mirror_type) logger.debug("PyTorch 镜像源: %s", pytorch_mirror) logger.debug("安装的 PyTorch: %s", pytorch_package) logger.debug("安装的 xFormers: %s", xformers_package) pytorch_package_args = [] if pytorch_mirror_type in ["cpu", "xpu", "ipex_legacy_arc", "rocm62", "other"]: for i in pytorch_package.split(): pytorch_package_args.append(i.strip()) else: for i in pytorch_package.split(): pytorch_package_args.append(i.strip()) for i in xformers_package.split(): pytorch_package_args.append(i.strip()) try: logger.info("同步 PyTorch 组件中") if pytorch_mirror is not None: install_pytorch( torch_package=pytorch_package_args, pytorch_mirror=pytorch_mirror, use_uv=use_uv, ) else: install_pytorch( torch_package=pytorch_package_args, use_uv=use_uv, ) logger.info("同步 InvokeAI 其他组件中") pip_install(f"invokeai=={invokeai_ver}", use_uv=use_uv) logger.info("同步 InvokeAI 组件完成") return True except Exception as e: logger.error("同步 InvokeAI 组件时发生了错误: %s", e) return False def install_invokeai( self, device_type: str, upgrade: bool | None = False, use_uv: bool | None = True, ) -> None: """安装 InvokeAI Args: device_type (str): 显卡设备类型 upgrade (bool | None): 更新 InvokeAI use_uv (bool | None): 是否使用 uv 安装 Python 软件包 """ logger.info("安装 InvokeAI 核心中") try: if upgrade: pip_install("invokeai", "--no-deps", "--upgrade", use_uv=use_uv) else: pip_install("invokeai", "--no-deps", use_uv=use_uv) self.sync_invokeai_component( device_type=device_type, use_uv=use_uv, ) except Exception as e: logger.error("安装 InvokeAI 失败: %s", e) class InvokeAIManager(BaseManager): """InvokeAI 管理模块 Attributes: component (InvokeAIComponentManager): InvokeAI 组件管理器 """ def __init__( self, workspace: str | Path, workfolder: str, hf_token: str | None = None, ms_token: str | None = None, port: int | None = 9090, ) -> None: """管理工具初始化 Args: workspace (str | Path): 工作区路径 workfolder (str): 工作区的文件夹名称 hf_token (str | None): HuggingFace Token ms_token (str | None): ModelScope Token port (int | None): 内网穿透端口 """ super().__init__( workspace=workspace, workfolder=workfolder, hf_token=hf_token, ms_token=ms_token, port=port, ) self.component = InvokeAIComponentManager() def mount_drive(self) -> None: """挂载 Google Drive 并创建 InvokeAI 输出文件夹, 并设置 INVOKEAI_ROOT 环境变量指定 InvokeAI 输出目录 Raises: RuntimeError: 挂载 Google Drive 失败 """ if not is_colab_environment(): logger.warning("当前环境非 Colab, 无法挂载 Google Drive") return drive_path = Path("/content/drive") if not (drive_path / "MyDrive").exists(): if not mount_google_drive(drive_path): raise RuntimeError("挂载 Google Drive 失败, 请尝试重新挂载 Google Drive") invokeai_output = drive_path / "MyDrive" / "invokeai_output" invokeai_output.mkdir(parents=True, exist_ok=True) os.environ["INVOKEAI_ROOT"] = invokeai_output.as_posix() def import_model_to_invokeai( self, model_list: list[str], ) -> None: """将模型列表导入到 InvokeAI 中 Args: model_list (list[str]): 模型路径列表 """ try: logger.info("导入 InvokeAI 模块中") import asyncio from invokeai.app.services.model_manager.model_manager_default import ( ModelManagerService, ) from invokeai.app.services.model_install.model_install_common import ( InstallStatus, ) from invokeai.app.services.model_records.model_records_sql import ( ModelRecordServiceSQL, ) from invokeai.app.services.download.download_default import ( DownloadQueueService, ) from invokeai.app.services.events.events_fastapievents import ( FastAPIEventService, ) from invokeai.app.services.config.config_default import get_config from invokeai.app.services.shared.sqlite.sqlite_util import init_db from invokeai.app.services.image_files.image_files_disk import ( DiskImageFileStorage, ) from invokeai.app.services.invoker import Invoker except Exception as e: logger.error("导入 InvokeAI 模块失败, 无法自动导入模型: %s", e) return def _get_invokeai_model_manager() -> ModelManagerService: logger.info("初始化 InvokeAI 模型管理服务中") configuration = get_config() output_folder = configuration.outputs_path image_files = DiskImageFileStorage(f"{output_folder}/images") db = init_db(config=configuration, logger=logger, image_files=image_files) event_handler_id = 1234 loop = asyncio.get_event_loop() events = FastAPIEventService(event_handler_id, loop=loop) model_manager = ModelManagerService.build_model_manager( app_config=configuration, model_record_service=ModelRecordServiceSQL(db=db, logger=logger), download_queue=DownloadQueueService(app_config=configuration, event_bus=events), events=FastAPIEventService(event_handler_id, loop=loop), ) logger.info("初始化 InvokeAI 模型管理服务完成") return model_manager def _import_model(model_manager: ModelManagerService, inplace: bool, model_path: str | Path) -> bool: model_path = Path(model_path) file_name = model_path.name try: logger.info("导入 %s 模型到 InvokeAI 中", file_name) job = model_manager.install.heuristic_import(source=model_path.as_posix(), inplace=inplace) result = model_manager.install.wait_for_job(job) if result.status == InstallStatus.COMPLETED: logger.info("导入 %s 模型到 InvokeAI 成功", file_name) return True else: logger.error( "导入 %s 模型到 InvokeAI 时出现了错误: %s", file_name, result.error, ) return False except Exception as e: logger.error("导入 %s 模型到 InvokeAI 时出现了错误: %s", file_name, e) return False install_model_to_local = False install_result = [] count = 0 task_sum = len(model_list) if task_sum == 0: logger.info("无需要导入的模型") return logger.info("InvokeAI 根目录: %s", os.environ.get("INVOKEAI_ROOT")) try: model_manager = _get_invokeai_model_manager() logger.info("启动 InvokeAI 模型管理服务") model_manager.start(Invoker) except Exception as e: logger.error("启动 InvokeAI 模型管理服务失败, 无法导入模型: %s", e) return logger.info("就地安装 (仅本地) 模式: %s", ("禁用" if install_model_to_local else "启用")) for model in model_list: count += 1 file_name = os.path.basename(model) logger.info("[%s/%s] 添加模型: %s", count, task_sum, file_name) result = _import_model( model_manager=model_manager, inplace=not install_model_to_local, model_path=model, ) install_result.append([model, file_name, result]) logger.info("关闭 InvokeAI 模型管理服务") try: model_manager.stop(Invoker) except Exception as e: logger.error("关闭 InvokeAI 模型管理服务出现错误: %s", e) logger.info("导入 InvokeAI 模型结果") print("-" * 70) for _, file, status in install_result: status = "导入成功" if status else "导入失败" print(f"- {file}: {status}") print("-" * 70) has_failed = False for _, _, x in install_result: if not x: has_failed = True break if has_failed: logger.warning("导入失败的模型列表和模型路径") print("-" * 70) for model, file_name, status in install_result: if not status: print(f"- {file_name}: {model}") print("-" * 70) logger.warning("导入失败的模型可尝试通过在 InvokeAI 的模型管理 -> 添加模型 -> 链接和本地路径, 手动输入模型路径并添加") logger.info("导入模型结束") def import_model(self) -> None: """导入模型到 InvokeAI 中""" model_path = self.workspace / self.workfolder / "sd-models" model_list = get_file_list(model_path) try: self.mount_drive() except Exception as e: logger.error("挂载 Google Drive 失败, 无法导入模型: %s", e) return self.import_model_to_invokeai(model_list) def get_sd_model( self, url: str, filename: str = None, ) -> Path | None: """下载模型 Args: url (str): 模型的下载链接 filename (str | None): 模型下载后保存的名称 model_type (str | None): 模型的类型 Returns: (Path | None): 模型保存路径 """ path = self.workspace / self.workfolder / "sd-models" return self.get_model(url=url, path=path, filename=filename, tool="aria2") def get_sd_model_from_list( self, model_list: list[str], retry: int | None = 3, ) -> None: """从模型列表下载模型 Args: model_list (list[str]): 模型列表 retry (int | None): 重试下载的次数, 默认为 3 """ new_model_list = [[model, 1] for model in model_list] self.get_model_from_list( path=self.workspace / self.workfolder / "sd-models", model_list=new_model_list, retry=retry, ) def check_env( self, use_uv: bool | None = True, ) -> None: """检查 InvokeAI 运行环境 Args: use_uv (bool | None): 使用 uv 安装依赖 """ fix_torch_libomp() check_onnxruntime_gpu(use_uv=use_uv, ignore_ort_install=True) check_numpy(use_uv=use_uv) def run(self) -> None: """启动 InvokeAI""" from invokeai.app.run_app import run_app logger.info("启动 InvokeAI 中") try: run_app() except KeyboardInterrupt: logger.info("关闭 InvokeAI") def install( self, device_type: Literal["cuda", "rocm", "xpu", "cpu"] = "cuda", use_uv: bool | None = True, pypi_index_mirror: str | None = None, pypi_extra_index_mirror: str | None = None, pypi_find_links_mirror: str | None = None, github_mirror: str | list[str] | None = None, huggingface_mirror: str | None = None, pytorch_mirror_dict: dict[str, str] | None = None, model_list: list[str] | None = None, check_avaliable_gpu: bool | None = False, enable_tcmalloc: bool | None = True, enable_cuda_malloc: bool | None = True, custom_sys_pkg_cmd: list[list[str]] | list[str] | bool | None = None, huggingface_token: str | None = None, modelscope_token: str | None = None, update_core: bool | None = True, *args, **kwargs, ) -> None: """安装 InvokeAI Args: device_type (Literal["cuda", "rocm", "xpu", "cpu"]): 显卡设备类型 use_uv (bool | None): 使用 uv 替代 Pip 进行 Python 软件包的安装 pypi_index_mirror (str | None): PyPI Index 镜像源链接 pypi_extra_index_mirror (str | None): PyPI Extra Index 镜像源链接 pypi_find_links_mirror (str | None): PyPI Find Links 镜像源链接 github_mirror (str | list | None): Github 镜像源链接或者镜像源链接列表 huggingface_mirror (str | None): HuggingFace 镜像源链接 pytorch_mirror_dict (dict[str, str] | None): PyTorch 镜像源字典, 需包含不同镜像源对应的 PyTorch 镜像源链接 model_list (list[str] | None): 模型下载列表 check_avaliable_gpu (bool | None): 是否检查可用的 GPU, 当检查时没有可用 GPU 将引发`Exception` enable_tcmalloc (bool | None): 是否启用 TCMalloc 内存优化 enable_cuda_malloc (bool | None): 启用 CUDA 显存优化 custom_sys_pkg_cmd (list[list[str]] | list[str] | bool | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能ol | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能 huggingface_token (str | None): 配置 HuggingFace Token modelscope_token (str | None): 配置 ModelScope Token update_core (bool | None): 安装时更新内核和扩展 Raises: Exception: GPU 不可用 """ warning_unexpected_params( message="InvokeAIManager.install() 接收到不期望参数, 请检查参数输入是否正确", args=args, kwargs=kwargs, ) logger.info("开始安装 InvokeAI") if custom_sys_pkg_cmd is False: custom_sys_pkg_cmd = [] elif custom_sys_pkg_cmd is True: custom_sys_pkg_cmd = None os.chdir(self.workspace) if check_avaliable_gpu: self.check_avaliable_gpu() set_mirror( pypi_index_mirror=pypi_index_mirror, pypi_extra_index_mirror=pypi_extra_index_mirror, pypi_find_links_mirror=pypi_find_links_mirror, github_mirror=github_mirror, huggingface_mirror=huggingface_mirror, ) configure_pip() configure_env_var() install_manager_depend( use_uv=use_uv, custom_sys_pkg_cmd=custom_sys_pkg_cmd, ) if pytorch_mirror_dict is not None: self.component.update_pytorch_mirror_dict(pytorch_mirror_dict) self.component.install_invokeai( device_type=device_type, upgrade=update_core, use_uv=use_uv, ) if model_list is not None: self.get_sd_model_from_list(model_list=model_list) self.restart_repo_manager( hf_token=huggingface_token, ms_token=modelscope_token, ) if enable_tcmalloc: self.tcmalloc.configure_tcmalloc() if enable_cuda_malloc: set_cuda_malloc() logger.info("InvokeAI 安装完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/invokeai_manager.py
Python
agpl-3.0
23,553
"""SD Scripts 管理工具""" import os from pathlib import Path from sd_webui_all_in_one import git_warpper from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.mirror_manager import set_mirror from sd_webui_all_in_one.git_warpper import set_git_config from sd_webui_all_in_one.env_check.fix_torch import fix_torch_libomp from sd_webui_all_in_one.env_check.fix_numpy import check_numpy from sd_webui_all_in_one.utils import warning_unexpected_params from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL from sd_webui_all_in_one.optimize.cuda_malloc import set_cuda_malloc from sd_webui_all_in_one.env_check.fix_dependencies import py_dependency_checker from sd_webui_all_in_one.env_check.onnxruntime_gpu_check import check_onnxruntime_gpu from sd_webui_all_in_one.env import config_wandb_token, configure_env_var, configure_pip from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, install_requirements, pip_install logger = get_logger( name="SD Scripts Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class SDScriptsManager(BaseManager): """sd-scripts 管理工具""" def check_env( self, use_uv: bool | None = True, requirements_file: str | None = "requirements.txt", ) -> None: """检查 sd-scripts 运行环境 Args: use_uv (bool | None): 使用 uv 安装依赖 requirements_file (str | None): 依赖文件名 """ sd_webui_path = self.workspace / self.workfolder requirement_path = sd_webui_path / requirements_file py_dependency_checker( requirement_path=requirement_path, name="sd-scripts", use_uv=use_uv, ) fix_torch_libomp() check_onnxruntime_gpu(use_uv=use_uv, ignore_ort_install=False) check_numpy(use_uv=use_uv) def install( self, torch_ver: str | list[str] | None = None, xformers_ver: str | list[str] | None = None, git_branch: str | None = None, git_commit: str | None = None, model_path: str | Path = None, model_list: list[str, int] | None = None, use_uv: bool | None = True, pypi_index_mirror: str | None = None, pypi_extra_index_mirror: str | None = None, pypi_find_links_mirror: str | None = None, github_mirror: str | list[str] | None = None, huggingface_mirror: str | None = None, pytorch_mirror: str | None = None, sd_scripts_repo: str | None = None, sd_scripts_requirements: str | None = None, retry: int | None = 3, huggingface_token: str | None = None, modelscope_token: str | None = None, wandb_token: str | None = None, git_username: str | None = None, git_email: str | None = None, check_avaliable_gpu: bool | None = False, enable_tcmalloc: bool | None = True, enable_cuda_malloc: bool | None = True, custom_sys_pkg_cmd: list[list[str]] | list[str] | bool | None = None, update_core: bool | None = True, *args, **kwargs, ) -> None: """安装 sd-scripts 和其余环境 配置并安装 sd-scripts 及其相关依赖环境, 包括 PyTorch、xFormers 等, 并可选择性下载模型文件. SDScriptsManager.install() 将会以下几件事 ``` 1. 配置 PyPI / Github / HuggingFace 镜像源 2. 配置 Pip / uv 3. 安装管理工具自身依赖 4. 安装 sd-scripts 5. 安装 PyTorch / xFormers 6. 安装 sd-scripts 的依赖 7. 下载模型 8. 配置 HuggingFace / ModelScope / WandB Token 环境变量 9. 配置其他工具 ``` Args: torch_ver (str | list[str] | None): 指定的 PyTorch 软件包包名, 并包括版本号 xformers_ver (str | list[str] | None): 指定的 xFormers 软件包包名, 并包括版本号 git_branch (str | None): 指定要切换 sd-scripts 的分支 git_commit (str | None): 指定要切换到 sd-scripts 的提交记录 model_path (str | Path | None): 指定模型下载的路径 model_list (list[str, int] | None): 模型下载列表 use_uv (bool | None): 使用 uv 替代 Pip 进行 Python 软件包的安装 pypi_index_mirror (str | None): PyPI Index 镜像源链接 pypi_extra_index_mirror (str | None): PyPI Extra Index 镜像源链接 pypi_find_links_mirror (str | None): PyPI Find Links 镜像源链接 github_mirror (str | list[str] | None): Github 镜像源链接或者镜像源链接列表 huggingface_mirror (str | None): HuggingFace 镜像源链接 pytorch_mirror (str | None): PyTorch 镜像源链接 sd_scripts_repo (str | None): sd-scripts 仓库地址, 未指定时默认为`https://github.com/kohya-ss/sd-scripts` sd_scripts_requirements (str | None): sd-scripts 的依赖文件名, 未指定时默认为 requirements.txt retry (int | None): 设置下载模型失败时重试次数 huggingface_token (str | None): 配置 HuggingFace Token modelscope_token (str | None): 配置 ModelScope Token wandb_token (str | None): 配置 WandB Token git_username (str | None): Git 用户名 git_email (str | None): Git 邮箱 check_avaliable_gpu (bool | None): 检查是否有可用的 GPU, 当 GPU 不可用时引发`Exception` enable_tcmalloc (bool | None): 启用 TCMalloc 内存优化 enable_cuda_malloc (bool | None): 启用 CUDA 显存优化 custom_sys_pkg_cmd (list[list[str]] | list[str] | bool | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能 update_core (bool | None): 安装时更新内核和扩展 Raises: Exception: GPU 不可用 """ warning_unexpected_params( message="SDScriptsManager.install() 接收到不期望参数, 请检查参数输入是否正确", args=args, kwargs=kwargs, ) logger.info("开始安装 sd-scripts") if custom_sys_pkg_cmd is False: custom_sys_pkg_cmd = [] elif custom_sys_pkg_cmd is True: custom_sys_pkg_cmd = None os.chdir(self.workspace) sd_scripts_path = self.workspace / self.workfolder requirement_path = sd_scripts_path / (sd_scripts_requirements if sd_scripts_requirements is not None else "requirements.txt") sd_scripts_repo = sd_scripts_repo if sd_scripts_repo is not None else "https://github.com/kohya-ss/sd-scripts" model_path = model_path if model_path is not None else (self.workspace / "sd-models") model_list = model_list if model_list else [] # 检查是否有可用的 GPU if check_avaliable_gpu: self.check_avaliable_gpu() # 配置镜像源 set_mirror( pypi_index_mirror=pypi_index_mirror, pypi_extra_index_mirror=pypi_extra_index_mirror, pypi_find_links_mirror=pypi_find_links_mirror, github_mirror=github_mirror, huggingface_mirror=huggingface_mirror, ) configure_pip() # 配置 Pip / uv configure_env_var() install_manager_depend( use_uv=use_uv, custom_sys_pkg_cmd=custom_sys_pkg_cmd, ) # 准备 Notebook 的运行依赖 # 下载 sd-scripts git_warpper.clone( repo=sd_scripts_repo, path=sd_scripts_path, ) if update_core: git_warpper.update(sd_scripts_path) # 更新 sd-scripts # 切换指定的 sd-scripts 分支 if git_branch is not None: git_warpper.switch_branch(path=sd_scripts_path, branch=git_branch) # 切换到指定的 sd-scripts 提交记录 if git_commit is not None: git_warpper.switch_commit(path=sd_scripts_path, commit=git_commit) # 安装 PyTorch 和 xFormers install_pytorch( torch_package=torch_ver, xformers_package=xformers_ver, pytorch_mirror=pytorch_mirror, use_uv=use_uv, ) # 安装 sd-scripts 的依赖 install_requirements( path=requirement_path, use_uv=use_uv, cwd=sd_scripts_path, ) # 安装使用 sd-scripts 进行训练所需的其他软件包 logger.info("安装其他 Python 模块中") try: pip_install("lycoris-lora", "dadaptation", "open-clip-torch", use_uv=use_uv) except Exception as e: logger.error("安装额外 Python 软件包时发生错误: %s", e) # 更新 urllib3 try: pip_install("urllib3", "--upgrade", use_uv=use_uv) except Exception as e: logger.error("更新 urllib3 时发生错误: %s", e) check_numpy(use_uv=use_uv) self.get_model_from_list(path=model_path, model_list=model_list, retry=retry) self.restart_repo_manager( hf_token=huggingface_token, ms_token=modelscope_token, ) config_wandb_token(wandb_token) set_git_config( username=git_username, email=git_email, ) if enable_tcmalloc: self.tcmalloc.configure_tcmalloc() if enable_cuda_malloc: set_cuda_malloc() logger.info("sd-scripts 安装完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/sd_scripts_manager.py
Python
agpl-3.0
9,738
"""SD Trainer 管理工具""" import os import sys import traceback import importlib.metadata from pathlib import Path from typing import Literal from sd_webui_all_in_one import git_warpper from sd_webui_all_in_one.logger import get_logger from sd_webui_all_in_one.manager.base_manager import BaseManager from sd_webui_all_in_one.mirror_manager import set_mirror from sd_webui_all_in_one.env_check.fix_torch import fix_torch_libomp from sd_webui_all_in_one.utils import warning_unexpected_params from sd_webui_all_in_one.env_check.fix_numpy import check_numpy from sd_webui_all_in_one.config import LOGGER_COLOR, LOGGER_LEVEL from sd_webui_all_in_one.optimize.cuda_malloc import set_cuda_malloc from sd_webui_all_in_one.env import configure_env_var, configure_pip from sd_webui_all_in_one.env_check.fix_dependencies import py_dependency_checker from sd_webui_all_in_one.package_analyzer.py_ver_cmp import PyWhlVersionComparison from sd_webui_all_in_one.colab_tools import is_colab_environment, mount_google_drive from sd_webui_all_in_one.env_check.onnxruntime_gpu_check import check_onnxruntime_gpu from sd_webui_all_in_one.env_manager import install_manager_depend, install_pytorch, install_requirements, pip_install logger = get_logger( name="SD Trainer Manager", level=LOGGER_LEVEL, color=LOGGER_COLOR, ) class SDTrainerManager(BaseManager): """SD Trainer 管理工具""" def mount_drive( self, extras: list[dict[str, str | bool]] = None, ) -> None: """挂载 Google Drive 并创建 SD Trainer 输出文件夹 挂载额外目录需要使用`link_dir`指定要挂载的路径, 并且使用相对路径指定 相对路径的起始位置为`{self.workspace}/{self.workfolder}` 若额外链接路径为文件, 需指定`is_file`属性为`True` 例如: ```python extras = [ {"link_dir": "models/loras"}, {"link_dir": "custom_nodes"}, {"link_dir": "extra_model_paths.yaml", "is_file": True}, ] ``` 默认挂载的目录和文件: `outputs`, `output`, `config`, `train`, `logs` Args: extras (list[dict[str, str | bool]]): 挂载额外目录 Raises: RuntimeError: 挂载 Google Drive 失败 """ if not is_colab_environment(): logger.warning("当前环境非 Colab, 无法挂载 Google Drive") return drive_path = Path("/content/drive") if not (drive_path / "MyDrive").exists(): if not mount_google_drive(drive_path): raise RuntimeError("挂载 Google Drive 失败, 请尝试重新挂载 Google Drive") drive_output = drive_path / "MyDrive" / "sd_trainer_output" sd_trainer_path = self.workspace / self.workfolder links: list[dict[str, str | bool]] = [ {"link_dir": "outputs"}, {"link_dir": "output"}, {"link_dir": "config"}, {"link_dir": "train"}, {"link_dir": "logs"}, ] if extras is not None: links += extras self.link_to_google_drive( base_dir=sd_trainer_path, drive_path=drive_output, links=links, ) def get_sd_model( self, url: str, filename: str = None, ) -> Path | None: """下载模型 Args: url (str): 模型的下载链接 filename (str | None): 模型下载后保存的名称 Returns: (Path | None): 模型保存路径 """ path = self.workspace / self.workfolder / "sd-models" return self.get_model(url=url, path=path, filename=filename, tool="aria2") def get_sd_model_from_list( self, model_list: list[dict[str, str]], ) -> None: """从模型列表下载模型 `model_list`需要指定`url`(模型下载链接), 可选参数为`filename`(模型保存名称), 例如 ```python model_list = [ {"url": "url1", "type": "checkpoints"}, {"url": "url2", "filename": "file.safetensors"}, {"url": "url4"}, ] ``` Args: model_list (list[dict[str, str]]): 模型列表 """ for model in model_list: url = model.get("url") filename = model.get("filename") self.get_sd_model(url=url, filename=filename) def check_protobuf( self, use_uv: bool | None = True, ) -> None: """检查 protobuf 版本问题 Args: use_uv (bool | None): 使用 uv 安装依赖 """ logger.info("检查 protobuf 版本问题中") try: ver = importlib.metadata.version("protobuf") if PyWhlVersionComparison(ver) != PyWhlVersionComparison("3.20.0"): logger.info("重新安装 protobuf 中") pip_install("protobuf==3.20.0", use_uv=use_uv) logger.info("重新安装 protobuf 成功") return logger.info("protobuf 检查完成") except Exception as e: traceback.print_exc() logger.error("检查 protobuf 时发送错误: %s", e) def check_env( self, use_uv: bool | None = True, requirements_file: str | None = "requirements.txt", ) -> None: """检查 SD Trainer 运行环境 Args: use_uv (bool | None): 使用 uv 安装依赖 requirements_file (str | None): 依赖文件名 """ sd_trainer_path = self.workspace / self.workfolder requirement_path = sd_trainer_path / requirements_file py_dependency_checker(requirement_path=requirement_path, name="SD Trainer", use_uv=use_uv) fix_torch_libomp() check_onnxruntime_gpu(use_uv=use_uv, ignore_ort_install=False) check_numpy(use_uv=use_uv) self.check_protobuf(use_uv=use_uv) def get_launch_command( self, params: list[str] | str | None = None, ) -> str: """获取 SD Trainer 启动命令 Args: params (list[str] | str | None): 启动 SD Trainer 的参数 Returns: str: 完整的启动 SD Trainer 的命令 """ sd_trainer_path = self.workspace / self.workfolder if (sd_trainer_path / "gui.py").exists(): scripts_name = "gui.py" elif (sd_trainer_path / "kohya_gui.py").exists(): scripts_name = "kohya_gui.py" else: scripts_name = "gui.py" cmd = [Path(sys.executable).as_posix(), (sd_trainer_path / scripts_name).as_posix()] if params is not None: if isinstance(params, str): cmd += self.parse_cmd_str_to_list(params) else: cmd += params return self.parse_cmd_list_to_str(cmd) def run( self, params: list[str] | str | None = None, display_mode: Literal["terminal", "jupyter"] | None = None, ) -> None: """启动 SD Trainer Args: params (list[str] | str | None): 启动 SD Trainer 的参数 display_mode (Literal["terminal", "jupyter"] | None): 执行子进程时使用的输出模式 """ self.launch( name="SD Trainer", base_path=self.workspace / self.workfolder, cmd=self.get_launch_command(params), display_mode=display_mode, ) def install( self, torch_ver: str | list[str] | None = None, xformers_ver: str | list[str] | None = None, use_uv: bool | None = True, pypi_index_mirror: str | None = None, pypi_extra_index_mirror: str | None = None, pypi_find_links_mirror: str | None = None, github_mirror: str | list[str] | None = None, huggingface_mirror: str | None = None, pytorch_mirror: str | None = None, sd_trainer_repo: str | None = None, sd_trainer_requirements: str | None = None, model_list: list[dict[str, str]] | None = None, check_avaliable_gpu: bool | None = False, enable_tcmalloc: bool | None = True, enable_cuda_malloc: bool | None = True, custom_sys_pkg_cmd: list[list[str]] | list[str] | bool | None = None, huggingface_token: str | None = None, modelscope_token: str | None = None, update_core: bool | None = True, *args, **kwargs, ) -> None: """安装 SD Trainer Args: torch_ver (str | list[str] | None): 指定的 PyTorch 软件包包名, 并包括版本号 xformers_ver (str | list[str] | None): 指定的 xFormers 软件包包名, 并包括版本号 use_uv (bool | None): 使用 uv 替代 Pip 进行 Python 软件包的安装 pypi_index_mirror (str | None): PyPI Index 镜像源链接 pypi_extra_index_mirror (str | None): PyPI Extra Index 镜像源链接 pypi_find_links_mirror (str | None): PyPI Find Links 镜像源链接 github_mirror (str | list[str] | None): Github 镜像源链接或者镜像源链接列表 huggingface_mirror (str | None): HuggingFace 镜像源链接 pytorch_mirror (str | None): PyTorch 镜像源链接 sd_trainer_repo (str | None): SD Trainer 仓库地址 sd_trainer_requirements (str | None): SD Trainer 依赖文件名 model_list (list[dict[str, str]] | None): 模型下载列表 check_avaliable_gpu (bool | None): 是否检查可用的 GPU, 当检查时没有可用 GPU 将引发`Exception` enable_tcmalloc (bool | None): 是否启用 TCMalloc 内存优化 enable_cuda_malloc (bool | None): 启用 CUDA 显存优化 custom_sys_pkg_cmd (list[list[str]] | list[str] | bool | None): 自定义调用系统包管理器命令, 设置为 True / None 为使用默认的调用命令, 设置为 False 则禁用该功能 huggingface_token (str | None): 配置 HuggingFace Token modelscope_token (str | None): 配置 ModelScope Token update_core (bool | None): 安装时更新内核和扩展 Raises: Exception: GPU 不可用 """ warning_unexpected_params( message="SDTrainerManager.install() 接收到不期望参数, 请检查参数输入是否正确", args=args, kwargs=kwargs, ) logger.info("开始安装 SD Trainer") if custom_sys_pkg_cmd is False: custom_sys_pkg_cmd = [] elif custom_sys_pkg_cmd is True: custom_sys_pkg_cmd = None os.chdir(self.workspace) sd_trainer_path = self.workspace / self.workfolder sd_trainer_repo = "https://github.com/Akegarasu/lora-scripts" if sd_trainer_repo is None else sd_trainer_repo requirements_path = sd_trainer_path / ("requirements.txt" if sd_trainer_requirements is None else sd_trainer_requirements) if check_avaliable_gpu: self.check_avaliable_gpu() set_mirror( pypi_index_mirror=pypi_index_mirror, pypi_extra_index_mirror=pypi_extra_index_mirror, pypi_find_links_mirror=pypi_find_links_mirror, github_mirror=github_mirror, huggingface_mirror=huggingface_mirror, ) configure_pip() configure_env_var() install_manager_depend( use_uv=use_uv, custom_sys_pkg_cmd=custom_sys_pkg_cmd, ) git_warpper.clone(sd_trainer_repo, sd_trainer_path) if update_core: git_warpper.update(sd_trainer_path) install_pytorch( torch_package=torch_ver, xformers_package=xformers_ver, pytorch_mirror=pytorch_mirror, use_uv=use_uv, ) install_requirements( path=requirements_path, use_uv=use_uv, cwd=sd_trainer_path, ) if model_list is not None: self.get_sd_model_from_list(model_list) self.restart_repo_manager( hf_token=huggingface_token, ms_token=modelscope_token, ) if enable_tcmalloc: self.tcmalloc.configure_tcmalloc() if enable_cuda_malloc: set_cuda_malloc() logger.info("SD Trainer 安装完成")
2301_81996401/sd-webui-all-in-one
sd_webui_all_in_one/manager/sd_trainer_manager.py
Python
agpl-3.0
12,441