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
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter class SpiderQunaerSpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, or item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Request or item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class SpiderQunaerDownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/middlewares.py
Python
unknown
3,660
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface import pandas as pd import pymysql from sqlalchemy import create_engine, NVARCHAR, VARCHAR, TEXT, DATETIME, FLOAT, INTEGER from itemadapter import ItemAdapter from spider_qunaer.items import * from warehouse.models import Scenery, Evaluate class SpiderQunaerPipeline(object): def process_item(self, item, spider): item.save() # print(f"保存:{item}") return item
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/pipelines.py
Python
unknown
634
# Scrapy settings for spider_qunaer project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html import os import sys import django sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'hunan_web.settings' # 项目名.settings django.setup() BOT_NAME = 'spider_qunaer' SPIDER_MODULES = ['spider_qunaer.spiders'] NEWSPIDER_MODULE = 'spider_qunaer.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'spider_qunaer (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'spider_qunaer.middlewares.SpiderQunaerSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'spider_qunaer.middlewares.SpiderQunaerDownloaderMiddleware': 543, #} # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'spider_qunaer.pipelines.SpiderQunaerPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/settings.py
Python
unknown
3,447
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/spiders/__init__.py
Python
unknown
161
from copy import deepcopy import scrapy from scrapy import Selector from spider_qunaer import items from warehouse import models class QunaerSpider(scrapy.Spider): name = 'qunaer' start_urls = ['https://travel.qunar.com/p-cs298890-xian-jingdian'] page_num = 1 def parse(self, response): item_scenery = items.SpiderSceneryItem() scenery_list = response.xpath("//ul[@class='list_item clrfix']/li") for i in scenery_list: item_scenery["scenery_name"] = i.xpath("./div/div/a/span/text()").extract_first() item_scenery["rank"] = i.xpath("./div/div/div/span[2]/span/text()").extract_first() item_scenery["people_percent"] = i.xpath("./div/div[2]/span/span/text()").extract_first() scenery = models.Scenery.objects.filter(scenery_name=item_scenery["scenery_name"]).first() if scenery: scenery.evaluates.all().delete() scenery.delete() detail_url = i.xpath("./a/@href").extract_first() if not models.Scenery.objects.filter(scenery_name=item_scenery["scenery_name"]).first(): yield scrapy.Request(detail_url, callback=self.get_detail, encoding="utf-8", dont_filter=True, meta={"item_scenery": deepcopy(item_scenery)}) if self.page_num < 500: self.page_num += 1 yield scrapy.Request(url=f"{self.start_urls[0]}-1-{self.page_num}", callback=self.parse) def get_detail(self, response): item_scenery = response.meta["item_scenery"] # 检查响应类型 if response.headers.get('Content-Type') == b'application/json': data = response.json() # 解析JSON响应 item_scenery["score"] = data.get("score", 0) # 根据实际JSON结构更新 item_scenery["play_time"] = data.get("play_time", None) item_scenery["city"] = data.get("city", "") else: # 对于HTML响应,使用XPath提取数据 score = response.xpath( '//*[@id="js_mainleft"]/div[4]/div/div[2]/div[1]/div[1]/span[1]/text()').extract_first() item_scenery["score"] = float(score) if score else 0 play_time = response.xpath('//div[@class="time"]/text()').extract_first() item_scenery["play_time"] = play_time.split(":")[1] if play_time else None item_scenery["city"] = response.xpath('//td[@class="td_l"]/dl[1]/dd/span/text()').extract_first() yield item_scenery # 第一页评论 self.get_evalute(response) for path in response.xpath("//div[@class='b_paging']/a")[:50]: # 取前50个评论链接 evalute_path = path.xpath("./@href").extract_first() if evalute_path: yield scrapy.Request(evalute_path, callback=self.get_evalute, encoding="utf-8", dont_filter=True, meta={"item_scenery": deepcopy(item_scenery)}) def get_evalute(self, response): item_scenery = response.meta["item_scenery"] # 检查是否为JSON响应 if response.headers.get('Content-Type') == b'application/json': data = response.json() # 解析JSON响应 for evalute in data.get("evaluates", []): # 假设 JSON 中包含 'evaluates' 键 item_evalute = items.SpiderEvaluteItem() item_evalute["content"] = evalute.get("content", "").replace("阅读全部", "").replace("\n", "").replace( "\r", "") item_evalute['send_time'] = evalute.get("send_time", "") item_evalute['user_name'] = evalute.get("user_name", "") item_evalute['score'] = evalute.get("score", 0) item_evalute['scenery_name'] = item_scenery['scenery_name'] yield item_evalute item_scenery.instance.evaluates.add(item_evalute.instance) else: evalute_list = response.xpath("//ul[@id='comment_box']/li") if not evalute_list: return None for evalute in evalute_list: item_evalute = items.SpiderEvaluteItem() item_evalute["content"] = evalute.xpath("./div[1]/div[1]/div[@class='e_comment_content']").xpath( 'string(.)').extract_first().replace("阅读全部", "").replace("\n", "").replace("\r", "") item_evalute['send_time'] = evalute.xpath("./div[1]/div[1]/div[5]/ul/li[1]/text()").extract_first() item_evalute['user_name'] = evalute.xpath("./div[2]/div[2]/a/text()").extract_first() score = evalute.xpath("./div[1]/div[1]/div[2]/span/span/@class").extract_first() if score: score = score.split("star_")[-1] item_evalute['score'] = score if score else 0 item_evalute['scenery_name'] = item_scenery['scenery_name'] yield item_evalute item_scenery.instance.evaluates.add(item_evalute.instance)
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/spiders/qunaer.py
Python
unknown
5,066
from django.contrib import admin # Register your models here.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/warehouse/admin.py
Python
unknown
63
from django.apps import AppConfig class WarehouseConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'warehouse'
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/warehouse/apps.py
Python
unknown
150
from django.db import models # Create your models here. class Evaluate(models.Model): eid = models.AutoField(primary_key=True) content = models.TextField(blank=True, null=True) send_time = models.DateField(blank=True, null=True) user_name = models.CharField(max_length=32, blank=True, null=True) score = models.IntegerField(blank=True, null=True) scenery_name = models.CharField(max_length=32, blank=True, null=True) class Scenery(models.Model): sid = models.AutoField(primary_key=True) city = models.CharField(max_length=64, blank=True, null=True) people_percent = models.CharField(max_length=32, blank=True, null=True) play_time = models.CharField(max_length=64, blank=True, null=True) rank = models.IntegerField(blank=True, null=True) scenery_name = models.CharField(max_length=64, blank=True, null=True) score = models.FloatField(blank=True, null=True) evaluates = models.ManyToManyField(Evaluate) class SpiderLog(models.Model): id = models.AutoField(primary_key=True) spider_time = models.DateTimeField(auto_now_add=True) class xian_poi(models.Model): name = models.CharField(max_length=255) lng = models.DecimalField(max_digits=10, decimal_places=6) lat = models.DecimalField(max_digits=10, decimal_places=6) address = models.TextField() province = models.CharField(max_length=100) city = models.CharField(max_length=100) area = models.CharField(max_length=100) # 区县字段 street_id = models.CharField(max_length=100, blank=True, null=True) telephone = models.CharField(max_length=100, blank=True, null=True) detail = models.IntegerField() uid = models.CharField(max_length=100) tag = models.TextField(blank=True, null=True) type = models.CharField(max_length=100) overall_rating = models.FloatField(blank=True, null=True) comment_num = models.IntegerField(blank=True, null=True) query_category = models.CharField(max_length=50) poi_category = models.CharField(max_length=50) created_at = models.DateTimeField() class Meta: db_table = 'warehouse_xian_poi' managed = False # 禁止Django管理该表的迁移
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/warehouse/models.py
Python
unknown
2,186
from django.test import TestCase # Create your tests here.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/warehouse/tests.py
Python
unknown
60
from django.shortcuts import render # Create your views here.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/warehouse/views.py
Python
unknown
63
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class XianPoiItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/items.py
Python
unknown
263
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter class XianPoiSpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, or item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Request or item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class XianPoiDownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/middlewares.py
Python
unknown
3,650
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface import json import pymysql from itemadapter import ItemAdapter from scrapy.exceptions import DropItem from scrapy.utils.project import get_project_settings from scrapy.exceptions import CloseSpider class JsonWriterPipeline: def open_spider(self, spider): self.file = open('xian_poi.json', 'w', encoding='utf-8') self.file.write("[\n") # 开始JSON数组 self.count = 0 def close_spider(self, spider): self.file.write("\n]") # 结束JSON数组 self.file.close() spider.logger.info(f"总共保存了 {self.count} 条数据到JSON文件") def process_item(self, item, spider): if self.count > 0: self.file.write(",\n") line = json.dumps(dict(item), ensure_ascii=False) self.file.write(line) self.count += 1 return item class MySQLPipeline: def __init__(self): self.settings = get_project_settings() self.conn = None self.cursor = None self.processed_uids = set() # 用于去重 def open_spider(self, spider): try: self.conn = pymysql.connect( host=self.settings.get('MYSQL_HOST'), user=self.settings.get('MYSQL_USER'), password=self.settings.get('MYSQL_PASSWORD'), db=self.settings.get('MYSQL_DB'), charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) self.cursor = self.conn.cursor() self.create_table() except Exception as e: spider.logger.error(f"MySQL连接失败: {e}") raise CloseSpider("MySQL连接失败") def create_table(self): self.cursor.execute(""" CREATE TABLE IF NOT EXISTS xian_poi ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), lng DECIMAL(10,6), lat DECIMAL(10,6), address TEXT, province VARCHAR(100), city VARCHAR(100), area VARCHAR(100), street_id VARCHAR(100), telephone VARCHAR(100), detail INT, uid VARCHAR(100), tag TEXT, type VARCHAR(100), overall_rating FLOAT, comment_num INT, query_category VARCHAR(50), -- 新增查询分类字段 poi_category VARCHAR(50), -- 用于存储清洗后的分类 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY (uid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) self.conn.commit() def process_item(self, item, spider): # 基于UID去重 if item['uid'] in self.processed_uids: raise DropItem(f"重复数据: {item['uid']}") self.processed_uids.add(item['uid']) try: self.cursor.execute(""" INSERT INTO xian_poi ( name, lng, lat, address, province, city, area, street_id, telephone, detail, uid, tag, type, overall_rating, comment_num, query_category ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE name=VALUES(name), address=VALUES(address), telephone=VALUES(telephone) """, ( item['name'], item['lng'], item['lat'], item['address'], item['province'], item['city'], item['area'], item['street_id'], item['telephone'], item['detail'], item['uid'], item['tag'], item['type'], item.get('overall_rating'), item.get('comment_num'), item['query_category'] )) self.conn.commit() except Exception as e: spider.logger.error(f"MySQL插入失败: {e}") self.conn.rollback() raise DropItem(f"MySQL插入失败: {e}") return item def close_spider(self, spider): if self.conn: # 更新POI分类 self.cursor.execute(""" UPDATE xian_poi SET poi_category = CASE WHEN tag LIKE '%景点%' OR tag LIKE '%风景区%' OR tag LIKE '%旅游区%' THEN '景点' WHEN tag LIKE '%博物馆%' OR tag LIKE '%遗址%' OR tag LIKE '%古迹%' THEN '文物古迹' WHEN tag LIKE '%公园%' OR tag LIKE '%植物园%' THEN '公园' WHEN tag LIKE '%游乐园%' OR tag LIKE '%水上乐园%' THEN '游乐园' WHEN tag LIKE '%寺庙%' OR tag LIKE '%教堂%' THEN '寺庙' WHEN tag LIKE '%动物园%' OR tag LIKE '%水族馆%' THEN '动物园' ELSE query_category END """) self.conn.commit() self.conn.close()
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/pipelines.py
Python
unknown
5,075
# Scrapy settings for xian_poi project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'xian_poi' SPIDER_MODULES = ['xian_poi.spiders'] NEWSPIDER_MODULE = 'xian_poi.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'xian_poi (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'xian_poi.middlewares.XianPoiSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'xian_poi.middlewares.XianPoiDownloaderMiddleware': 543, #} # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'xian_poi.pipelines.XianPoiPipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' # 配置请求头 DEFAULT_REQUEST_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "Accept": "application/json, text/plain, */*", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", } # 配置并发请求数和延时 CONCURRENT_REQUESTS = 3 DOWNLOAD_DELAY = 1 # 下载延时,单位秒 # MySQL配置 MYSQL_HOST = 'localhost' MYSQL_USER = 'root' MYSQL_PASSWORD = '123456' MYSQL_DB = 'xian_web'
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/settings.py
Python
unknown
3,575
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/spiders/__init__.py
Python
unknown
161
import scrapy import json import urllib.parse import pymysql from scrapy.utils.project import get_project_settings from scrapy.exceptions import CloseSpider class BaiduMapSpider(scrapy.Spider): name = 'baidu_map' allowed_domains = ['api.map.baidu.com'] custom_settings = { 'ITEM_PIPELINES': { 'xian_poi.pipelines.JsonWriterPipeline': 300, 'xian_poi.pipelines.MySQLPipeline': 400, }, 'DOWNLOAD_DELAY': 0.8, 'CONCURRENT_REQUESTS': 2, 'RETRY_TIMES': 3 } def start_requests(self): # 细分查询关键词(参考论文表1分类) queries = [ "景点", "文物古迹", "博物馆", "公园", "游乐园", "寺庙", "风景区", "植物园", "动物园", "水族馆", "教堂" ] base_url = "http://api.map.baidu.com/place/v2/search" for query in queries: params = { "query": query, "region": "西安市", "output": "json", "ak": "SGEyhSS0Fir6EBEoarGXd8UubB75a1YI", "page_size": 20, "scope": 2, # 获取详细信息 "page_num": 0 } url = f"{base_url}?{urllib.parse.urlencode(params)}" yield scrapy.Request(url, callback=self.parse, meta={'query': query, 'page_num': 0}) def parse(self, response): data = json.loads(response.text) if data.get("status") != 0: self.logger.error(f"API请求失败: {data}") return # 首次请求时获取总页数 if response.meta.get('page_num') == 0: total = data.get('total', 0) page_size = 20 total_pages = min((total + page_size - 1) // page_size, 50) # 限制最多50页 # 生成后续分页请求 for page in range(1, total_pages): params = { "query": response.meta['query'], "region": "西安市", "output": "json", "ak": "SGEyhSS0Fir6EBEoarGXd8UubB75a1YI", "page_size": 20, "scope": 2, "page_num": page } url = f"{response.url.split('?')[0]}?{urllib.parse.urlencode(params)}" yield scrapy.Request(url, callback=self.parse, meta={'query': response.meta['query'], 'page_num': page}) # 提取数据 for poi in data.get("results", []): item = { "name": poi.get("name"), "lng": poi.get("location", {}).get("lng"), "lat": poi.get("location", {}).get("lat"), "address": poi.get("address"), "province": poi.get("province"), "city": poi.get("city"), "area": poi.get("area"), "street_id": poi.get("street_id"), "telephone": poi.get("telephone"), "detail": poi.get("detail"), "uid": poi.get("uid"), "tag": poi.get("detail_info", {}).get("tag"), "type": poi.get("detail_info", {}).get("type"), "overall_rating": poi.get("detail_info", {}).get("overall_rating"), "comment_num": poi.get("detail_info", {}).get("comment_num"), "query_category": response.meta['query'] # 记录查询分类 } # 西安坐标范围验证 if (108.8 < item['lng'] < 109.5) and (33.9 < item['lat'] < 34.5): yield item else: self.logger.warning(f"坐标超出西安范围: {item['name']} ({item['lng']}, {item['lat']})")
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/xian_poi/spiders/baidu_map.py
Python
unknown
3,888
import pandas as pd # 读取 user_profiles.csv 文件 df = pd.read_csv('user_profiles.csv') # 查看所有列名称 print("列名称列表:") print(df.columns.tolist()) # 查看前5行数据(可选) print("\n示例数据:") print(df.head())
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/数据处理/csv_col.py
Python
unknown
251
import pandas as pd import re # 假设数据已加载到DataFrame中 df = pd.read_csv('warehouse_scenery.csv') def convert_playtime_to_hours(play_time): if pd.isna(play_time): return None # 处理缺失值 # 尝试处理范围值(如"3小时 - 4小时") if '-' in str(play_time): times = str(play_time).split('-') start = parse_single_time(times[0].strip()) end = parse_single_time(times[1].strip()) if start is not None and end is not None: return (start + end) / 2 # 取平均值 return None return parse_single_time(play_time) def parse_single_time(time_str): if pd.isna(time_str): return None # 处理中文单位 time_str = str(time_str) # 尝试提取数值和单位 match = re.match(r'([\d.]+)\s*([a-zA-Z\u4e00-\u9fff]+)?', time_str) if not match: return None value, unit = match.groups() value = float(value) # 如果没有单位,假设是小时 if unit is None: return value # 根据单位转换 unit = unit.lower() if any(word in unit for word in ['hour', 'h', '小时', '时']): return value elif any(word in unit for word in ['minute', 'min', '分钟', '分']): return value / 60 elif any(word in unit for word in ['day', 'd', '天']): return value * 24 else: return None # 未知单位 # 应用转换函数 df['playtime_hours'] = df['play_time'].apply(convert_playtime_to_hours) # 检查转换结果 print(df[['play_time', 'playtime_hours']].head()) # 保存清洗后的数据 df.to_csv('cleaned_warehouse_scenery.csv', index=False)
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/数据处理/data_clean.py
Python
unknown
1,666
import pymysql import csv conn = pymysql.connect(host='localhost', user='root', password='123456', db='xian_web', charset='utf8mb4') with conn.cursor() as cursor: cursor.execute("SELECT * FROM warehouse_xian_poi") with open('warehouse_xian_poi.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerow([i[0] for i in cursor.description]) # 写列名 writer.writerows(cursor)
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/数据处理/data_export.py
Python
unknown
459
import pandas as pd import matplotlib.pyplot as plt from matplotlib import font_manager # 1. 字体配置(解决中文显示问题) plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 更美观的字体 plt.rcParams['axes.unicode_minus'] = False # 2. 数据读取与处理 file_path = 'warehouse_xian_poi.csv' df = pd.read_csv(file_path) type_proportions = df['type'].value_counts(normalize=True) * 100 # 转为百分比 # 3. 颜色优化(匹配原图风格) colors = { 'scope': '#1f77b4', # 主蓝色 'shopping': '#ff7f0e', # 橙色 'category3': '#2ca02c', # 绿色 'category4': '#d62728' # 红色 } # 4. 可视化优化 fig, ax = plt.subplots(figsize=(12, 10)) # 环形图参数优化 wedges, texts, autotexts = ax.pie( type_proportions, labels=type_proportions.index, colors=[colors.get(x, '#9467bd') for x in type_proportions.index], # 颜色映射 startangle=90, wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2}, autopct='%1.1f%%', pctdistance=0.75, # 调整百分比位置 textprops={'fontsize': 12, 'fontweight': 'bold'} ) # 5. 标签防重叠处理 plt.setp(autotexts, bbox=dict(boxstyle="round,pad=0.2", fc="white", ec="gray", alpha=0.8)) # 6. 添加图例(替代拥挤的饼图标签) ax.legend(wedges, [f"{l} ({s:.1f}%)" for l, s in zip(type_proportions.index, type_proportions)], title="POI类型", loc="center left", bbox_to_anchor=(1, 0.5), fontsize=12) # 7. 标题和布局优化 plt.title('西安POI类型占比分布', fontsize=18, pad=20, fontweight='bold') plt.tight_layout(rect=[0, 0, 0.85, 1]) # 为图例留空间 plt.savefig('optimized_poi_distribution.png', dpi=300, bbox_inches='tight') plt.show() # import pandas as pd # # # 读取 CSV 文件 # file_path = 'warehouse_xian_poi.csv' # df = pd.read_csv(file_path) # # # 计算每种 type 的数量和比例 # type_counts = df['type'].value_counts() # type_proportions = df['type'].value_counts(normalize=True) # # # 打印结果 # print("每种 type 的数量:") # print(type_counts) # print("\n每种 type 的比例:") # print(type_proportions) # # # 如果你想以百分比形式显示(可选) # print("\n每种 type 的百分比:") # print(type_proportions.apply(lambda x: f"{x:.2%}")) # import pandas as pd # # # 读取 CSV 文件 # file_path = 'warehouse_xian_poi.csv' # df = pd.read_csv(file_path) # # # 获取列 'query_category' 的唯一值 # unique_values = df['query_category'].unique() # # # 打印唯一值及其数量 # print("Unique values in 'query_category':", unique_values) # print("Number of unique values:", len(unique_values))
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/数据处理/get_unique.py
Python
unknown
2,719
import pandas as pd # 读取 CSV 文件 df = pd.read_csv('warehouse_evaluate.csv') # 确保 send_time 是 datetime 类型(如果不是,先转换) df['send_time'] = pd.to_datetime(df['send_time']) # 计算最小和最大时间 min_time = df['send_time'].min() max_time = df['send_time'].max() print(f"最小值(最早时间): {min_time}") print(f"最大值(最晚时间): {max_time}")
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/数据处理/timespan.py
Python
unknown
401
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation # 读取用户评价数据 user_data = pd.read_csv('warehouse_evaluate.csv') # 文本向量化 vectorizer = CountVectorizer(stop_words='english') X = vectorizer.fit_transform(user_data['content']) # LDA模型 lda = LatentDirichletAllocation(n_components=5, random_state=42) # 假设提取5个主题 lda.fit(X) # 查看主题关键词 for index, topic in enumerate(lda.components_): print(f'Topic {index}:') print([vectorizer.get_feature_names()[i] for i in topic.argsort()[-10:]])
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/用户画像建模和分析/comment_lda.py
Python
unknown
633
# -*- coding: utf-8 -*- import pandas as pd import ast from collections import Counter import matplotlib.pyplot as plt import seaborn as sns # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # ==================== 1. 数据加载与预处理 ==================== def load_data(file_path): """加载并解析数据(适配你的实际列名)""" df = pd.read_csv(file_path) # 重命名列(确保列名统一) df = df.rename(columns={ 'Unnamed: 0': 'user_name', 'interest_cluster': 'cluster' # 将interest_cluster重命名为cluster以适配后续代码 }) # 解析interests和activity列(从字符串转字典) df['interests'] = df['interests'].apply(ast.literal_eval) df['activity'] = df['activity'].apply(ast.literal_eval) # 展开activity字典到单独列 activity_df = pd.json_normalize(df['activity']) df = pd.concat([df.drop(['activity'], axis=1), activity_df], axis=1) return df # ==================== 2. 聚类分析工具函数 ==================== def analyze_clusters(df): """分析每个聚类的特征""" results = {} # 分析每个聚类的关键词 for cluster in sorted(df['cluster'].unique()): cluster_data = df[df['cluster'] == cluster] # 合并所有用户的关键词 all_words = [] for words_dict in cluster_data['interests']: all_words.extend(words_dict.keys()) # 统计高频词 word_counts = Counter(all_words) top_words = word_counts.most_common(10) # 收集统计结果 results[cluster] = { 'sample_size': len(cluster_data), 'top_keywords': top_words, 'price_dist': cluster_data['price_level'].value_counts().to_dict(), 'avg_sentiment': cluster_data['sentiment'].mean(), 'avg_reviews': cluster_data['total_reviews'].mean(), 'avg_active_years': cluster_data['active_years'].mean(), 'avg_days_since_last': cluster_data['days_since_last'].mean() } return results # ==================== 3. 可视化函数 ==================== def plot_cluster_stats(results): """绘制聚类统计图表""" # 准备数据 clusters = sorted(results.keys()) # 创建2x2的子图布局 fig, axes = plt.subplots(2, 2, figsize=(15, 10)) axes = axes.flatten() # 指标列表 metrics = [ ('avg_sentiment', '平均情感分'), ('avg_reviews', '平均评论数'), ('avg_active_years', '平均活跃年数'), ('avg_days_since_last', '平均最近活跃天数') ] for i, (metric, title) in enumerate(metrics): if i >= len(axes): # 防止指标数量超过子图数量 break values = [results[c][metric] for c in clusters] sns.barplot(x=list(clusters), y=values, ax=axes[i], palette='viridis') axes[i].set_title(title) axes[i].set_xlabel('聚类分组') axes[i].set_ylabel(title) plt.tight_layout() plt.savefig('cluster_comparison.png', dpi=300) plt.show() # ==================== 4. 主执行流程 ==================== if __name__ == "__main__": # 加载数据 df = load_data('user_profiles.csv') # 检查数据 print("数据前5行预览:") print(df.head()) print("\n列名验证:", df.columns.tolist()) # 分析聚类特征 cluster_results = analyze_clusters(df) # 打印关键结果 print("\n" + "=" * 50 + "\n聚类分析结果汇总\n" + "=" * 50) for cluster, stats in cluster_results.items(): print(f"\nCluster {cluster} (样本数: {stats['sample_size']})") print("-" * 40) print(f"TOP关键词: {[word for word, count in stats['top_keywords']]}") print(f"消费水平分布: {stats['price_dist']}") print(f"平均情感分: {stats['avg_sentiment']:.2f}") print(f"平均评论数: {stats['avg_reviews']:.1f}") print(f"平均活跃年数: {stats['avg_active_years']:.1f}") print(f"平均最近活跃天数: {stats['avg_days_since_last']:.1f}") # 可视化 plot_cluster_stats(cluster_results) # 保存详细结果 pd.DataFrame.from_dict(cluster_results, orient='index').to_csv('cluster_analysis_details.csv') print("\n分析结果已保存到 cluster_analysis_details.csv") # 生成关键词词云(按聚类分组) for cluster in df['cluster'].unique(): cluster_words = ' '.join([' '.join(list(d.keys())) for d in df[df['cluster'] == cluster]['interests']]) if cluster_words.strip(): wordcloud = WordCloud( font_path='simhei.ttf', width=800, height=400, background_color='white' ).generate(cluster_words) plt.figure(figsize=(10, 5)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.title(f'Cluster {cluster} 关键词词云') plt.savefig(f'cluster_{cluster}_wordcloud.png', bbox_inches='tight', dpi=300) plt.close() print(f"Cluster {cluster} 词云已保存")
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/用户画像建模和分析/user_cluster_res.py
Python
unknown
5,211
# -*- coding: utf-8 -*- """ 用户画像分析系统 - 最终修正版 """ # ==================== 1. 导入所有必需库 ==================== from collections import Counter from wordcloud import WordCloud import pandas as pd import numpy as np import jieba import re import matplotlib.pyplot as plt from datetime import datetime from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn.decomposition import PCA import os # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # ==================== 2. 数据加载与预处理 ==================== def load_and_clean_data(): """加载并彻底清洗数据""" # 加载数据 df_eval = pd.read_csv('warehouse_evaluate.csv') df_scenery = pd.read_csv('warehouse_scenery.csv') df_poi = pd.read_csv('warehouse_xian_poi.csv') # 清理用户名为空的数据 df_eval = df_eval.dropna(subset=['user_name']) df_eval['user_name'] = df_eval['user_name'].astype(str) # 合并景点信息 df_scenery = df_scenery.merge( df_poi[['name', 'tag', 'type', 'lng', 'lat']], left_on='scenery_name', right_on='name', how='left' ).drop(columns=['name']) # 处理评分数据 df_scenery['score'] = pd.to_numeric(df_scenery['score'], errors='coerce') df_scenery = df_scenery.dropna(subset=['score']) # 处理评论时间 df_eval['send_time'] = pd.to_datetime(df_eval['send_time'], errors='coerce') df_eval = df_eval.dropna(subset=['send_time']) df_eval['review_year'] = df_eval['send_time'].dt.year return df_eval, df_scenery # ==================== 3. 用户画像构建 ==================== class UserProfiler: def __init__(self, df_eval, df_scenery): self.df_eval = df_eval self.df_scenery = df_scenery self.user_profiles = {} def _clean_text(self, text): """文本清洗函数""" if not isinstance(text, str): return '' # 移除特殊字符和标点 text = re.sub(r'[^\w\s\u4e00-\u9fa5]', '', text) return text.strip() def extract_keywords(self, text): """安全的中文关键词提取""" text = self._clean_text(text) if not text: return '' try: words = [word for word in jieba.lcut(text) if len(word) > 1 and re.match(r'^[\u4e00-\u9fa5]+$', word)] return ' '.join(words) except: return '' def analyze_interests(self): """安全的用户兴趣分析""" # 确保没有空用户名 valid_users = self.df_eval[self.df_eval['user_name'].notna()] # 构建用户-兴趣矩阵 user_keywords = valid_users.groupby('user_name')['content'].apply( lambda x: ' '.join([self.extract_keywords(text) for text in x if pd.notna(text)]) ) # 过滤空内容 user_keywords = user_keywords[user_keywords.str.len() > 0] # TF-IDF向量化 tfidf = TfidfVectorizer( max_features=100, token_pattern=r'(?u)\b\w+\b', min_df=2 # 忽略只出现一次的词语 ) try: X_tfidf = tfidf.fit_transform(user_keywords) # 兴趣聚类 pca = PCA(n_components=2) X_pca = pca.fit_transform(X_tfidf.toarray()) kmeans = KMeans(n_clusters=3, n_init='auto').fit(X_pca) # 可视化 plt.figure(figsize=(10, 6)) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=kmeans.labels_, alpha=0.5) plt.title("用户兴趣聚类分布") plt.savefig('user_interest_clusters.png', bbox_inches='tight', dpi=300) return user_keywords, tfidf, kmeans except Exception as e: print(f"兴趣分析出错: {str(e)}") return pd.Series(dtype=object), None, None def analyze_consumption(self): """消费水平分析""" try: # 确保score列有效 valid_data = self.df_scenery.dropna(subset=['score']).copy() valid_data['price_level'] = pd.qcut( valid_data['score'].rank(method='first'), q=3, labels=['低', '中', '高'], duplicates='drop' ) # 合并有效数据 user_price = self.df_eval.merge( valid_data[['scenery_name', 'price_level']], on='scenery_name', how='left' ).groupby('user_name')['price_level'].apply( lambda x: Counter(x.dropna()).most_common(1)[0][0] if not x.dropna().empty else '未知' ) return user_price except Exception as e: print(f"消费分析出错: {str(e)}") return pd.Series(dtype=object) def generate_wordcloud(self, interests): """生成词云""" try: if not interests: print("无有效兴趣数据生成词云") return text = ' '.join([i for i in interests if i]) if not text.strip(): print("兴趣文本为空") return wc = WordCloud( font_path='simhei.ttf', width=800, height=400, background_color='white', collocations=False # 避免重复词语 ).generate(text) plt.figure(figsize=(12, 6)) plt.imshow(wc, interpolation='bilinear') plt.axis('off') plt.savefig('user_interests_wordcloud.png', bbox_inches='tight', dpi=300) except Exception as e: print(f"生成词云出错: {str(e)}") def build_profiles(self): """构建完整用户画像""" # 各维度分析 user_keywords, tfidf, kmeans = self.analyze_interests() user_price = self.analyze_consumption() # 情感分析 pos_words = ['好', '美', '满意', '推荐', '喜欢'] neg_words = ['差', '无聊', '贵', '失望', '坑'] def sentiment_score(text): text = self._clean_text(text) if not text: return 0 pos = sum(text.count(word) for word in pos_words) neg = sum(text.count(word) for word in neg_words) return (pos - neg) / (pos + neg + 1e-6) self.df_eval['sentiment'] = self.df_eval['content'].apply(sentiment_score) user_sentiment = self.df_eval.groupby('user_name')['sentiment'].mean() # 活跃度分析 user_activity = self.df_eval.groupby('user_name').agg( total_reviews=('eid', 'count'), last_review=('send_time', 'max'), review_years=('review_year', lambda x: len(set(x))) ) user_activity['days_since_last'] = (datetime.now() - user_activity['last_review']).dt.days # 整合画像 all_interests = [] for user in self.df_eval['user_name'].unique(): try: # 兴趣关键词 if user in user_keywords.index and tfidf: feature_indices = tfidf.transform([user_keywords[user]]).nonzero()[1] interests = dict(Counter( tfidf.get_feature_names_out()[i] for i in feature_indices ).most_common(5)) else: interests = {} # 完整画像 profile = { 'interests': interests, 'interest_cluster': int(kmeans.labels_[user_keywords.index.get_loc(user)]) if user in user_keywords.index and kmeans else -1, 'price_level': user_price.get(user, '未知'), 'sentiment': user_sentiment.get(user, 0), 'activity': { 'total_reviews': int(user_activity.loc[user, 'total_reviews']), 'active_years': int(user_activity.loc[user, 'review_years']), 'days_since_last': int(user_activity.loc[user, 'days_since_last']) } if user in user_activity.index else {} } self.user_profiles[user] = profile # 收集兴趣词 if interests: all_interests.extend(interests.keys()) except Exception as e: print(f"处理用户 {user} 时出错: {str(e)}") continue # 生成词云 self.generate_wordcloud(all_interests) # 保存结果 if self.user_profiles: pd.DataFrame.from_dict(self.user_profiles, orient='index').to_csv('user_profiles.csv') print(f"成功生成 {len(self.user_profiles)} 个用户画像") else: print("警告: 未生成任何有效用户画像") # ==================== 4. 主执行流程 ==================== if __name__ == "__main__": # 加载并清洗数据 df_eval, df_scenery = load_and_clean_data() # 检查数据有效性 if df_eval.empty or df_scenery.empty: print("错误: 数据加载失败或数据为空") else: print(f"有效用户数据: {len(df_eval)} 条") print(f"有效景点数据: {len(df_scenery)} 条") # 构建用户画像 profiler = UserProfiler(df_eval, df_scenery) profiler.build_profiles()
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/用户画像建模和分析/user_profile.py
Python
unknown
9,502
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde from matplotlib.patches import Ellipse import cartopy.crs as ccrs import cartopy.feature as cfeature from pyproj import Transformer import geopandas as gpd from shapely.geometry import Point import matplotlib.gridspec as gridspec # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # ==================== 1. 数据加载与预处理 ==================== def load_data(): """加载并清洗西安POI数据""" try: df = pd.read_csv('warehouse_xian_poi.csv') print(f"原始数据量: {len(df)}条") # 数据清洗 df = df.dropna(subset=['lng', 'lat', 'query_category']) print(f"去除空值后: {len(df)}条") # 筛选旅游相关类别 tourism_types = ['景点', '文物古迹', '博物馆', '公园', '游乐园', '寺庙', '植物园', '动物园', '水族馆', '教堂'] df_tourism = df[df['query_category'].isin(tourism_types)].copy() print(f"筛选旅游类别后: {len(df_tourism)}条") # 转换为GeoDataFrame geometry = [Point(xy) for xy in zip(df_tourism['lng'], df_tourism['lat'])] gdf = gpd.GeoDataFrame(df_tourism, geometry=geometry, crs="EPSG:4326") return gdf except Exception as e: print(f"数据加载出错: {str(e)}") return gpd.GeoDataFrame() # ==================== 2. 标准差椭圆计算 ==================== def calculate_ellipse_params(gdf): """计算各类别标准差椭圆参数""" if gdf.empty: return pd.DataFrame() # 坐标转换(WGS84转UTM Zone 49N) transformer = Transformer.from_crs(4326, 32649) def _ellipse(group): if len(group) < 2: return pd.Series(dtype=float) # 转换为平面坐标 coords = np.array([transformer.transform(point.y, point.x) for point in group.geometry]) x, y = coords[:, 0], coords[:, 1] # 计算椭圆参数 cov = np.cov(x - x.mean(), y - y.mean()) eigvals, eigvecs = np.linalg.eig(cov) major = 2 * np.sqrt(eigvals[0]) minor = 2 * np.sqrt(eigvals[1]) angle = np.degrees(np.arctan2(*eigvecs[:, 0][::-1])) % 180 # 计算中心点 center = group.geometry.union_all().centroid return pd.Series({ 'center_lng': center.x, 'center_lat': center.y, 'major_axis': major, 'minor_axis': minor, 'angle': angle, 'area': np.pi * major * minor / 1e6, # 转换为平方公里 'count': len(group) }) return gdf.groupby('query_category', group_keys=False).apply(_ellipse) # ==================== 3. 可视化函数 ==================== def plot_combined_map(gdf, ellipse_params): """在西安地图上同时显示标准差椭圆和核密度""" if gdf.empty: return # 创建地图画布 plt.figure(figsize=(16, 12)) ax = plt.axes(projection=ccrs.PlateCarree()) # 设置西安地图范围(包含周边区域) ax.set_extent([108.7, 109.3, 33.9, 34.5]) # 扩大显示范围 # 添加专业地图元素 ax.add_feature(cfeature.LAND.with_scale('50m'), facecolor='#f5f5f5') ax.add_feature(cfeature.RIVERS.with_scale('50m'), edgecolor='#66b3ff', linewidth=1) ax.add_feature(cfeature.LAKES.with_scale('50m'), edgecolor='#66b3ff', facecolor='#a6cee3') ax.gridlines(draw_labels=True, linestyle='--', alpha=0.5) # ===== 1. 绘制核密度 ===== # 计算整体核密度 kde = gaussian_kde(np.vstack([gdf.geometry.x, gdf.geometry.y])) xi, yi = np.mgrid[108.7:109.3:200j, 33.9:34.5:200j] zi = kde(np.vstack([xi.flatten(), yi.flatten()])) # 绘制核密度热力图(使用半透明紫色调) levels = np.linspace(zi.min(), zi.max(), 10) cs = ax.contourf(xi, yi, zi.reshape(xi.shape), levels=levels, cmap='Purples', alpha=0.5, transform=ccrs.PlateCarree()) # ===== 2. 绘制标准差椭圆 ===== colors = plt.cm.tab20(np.linspace(0, 1, len(ellipse_params))) for idx, (category, row) in enumerate(ellipse_params.iterrows()): # 绘制椭圆 ellipse = Ellipse( (row['center_lng'], row['center_lat']), width=row['minor_axis'] / 50000, height=row['major_axis'] / 50000, angle=row['angle'], edgecolor=colors[idx], facecolor='none', linewidth=2, transform=ccrs.PlateCarree(), label=f"{category} (n={int(row['count'])})" ) ax.add_patch(ellipse) # 标记中心点 ax.plot(row['center_lng'], row['center_lat'], 'o', color=colors[idx], markersize=8, transform=ccrs.PlateCarree()) # 添加图例和标题 plt.legend(title='景点类别(数量)', loc='upper right', fontsize=9) plt.title('西安市旅游景点空间分布\n(核密度与标准差椭圆)', pad=20, fontsize=16) # 添加比例尺和指北针 def add_scale_bar(): ax.plot([108.75, 108.85], [33.92, 33.92], color='black', linewidth=2, transform=ccrs.PlateCarree()) ax.text(108.8, 33.91, '10 km', ha='center', transform=ccrs.PlateCarree()) def add_north_arrow(): ax.annotate('↑ N', xy=(0.95, 0.95), xycoords='axes fraction', ha='center', va='center', fontsize=12, bbox=dict(boxstyle='round', facecolor='white')) add_scale_bar() add_north_arrow() # 添加颜色条 cbar = plt.colorbar(cs, orientation='vertical', shrink=0.6, pad=0.02) cbar.set_label('景点分布密度', rotation=270, labelpad=15) plt.savefig('xian_tourism_combined_map.png', dpi=300, bbox_inches='tight') plt.show() # ==================== 主执行流程 ==================== if __name__ == "__main__": # 1. 数据加载 gdf = load_data() if not gdf.empty: # 2. 计算标准差椭圆参数 ellipse_params = calculate_ellipse_params(gdf) print("\n标准差椭圆参数表:") print(ellipse_params.round(1)) # 3. 绘制综合地图 plot_combined_map(gdf, ellipse_params) # 4. 保存结果 ellipse_params.to_excel('xian_ellipse_params.xlsx') else: print("执行失败:无有效数据")
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/空间分析/sce_clu_all.py
Python
unknown
6,498
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde from matplotlib.patches import Ellipse import cartopy.crs as ccrs import cartopy.feature as cfeature from pyproj import Transformer from sklearn.cluster import DBSCAN from libpysal.weights import DistanceBand from esda.moran import Moran import geopandas as gpd from shapely.geometry import Point # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # ==================== 1. 数据加载与预处理 ==================== def load_data(): """加载并清洗西安POI数据""" try: df = pd.read_csv('warehouse_xian_poi.csv') print(f"原始数据量: {len(df)}条") # 数据清洗 df = df.dropna(subset=['lng', 'lat', 'type']) print(f"去除空值后: {len(df)}条") # 筛选旅游相关类别 tourism_types = ['scope'] # 根据实际数据调整 df_tourism = df[df['type'].isin(tourism_types)].copy() print(f"筛选旅游类别后: {len(df_tourism)}条") # 验证坐标范围(西安主城区) df_tourism = df_tourism[ (df_tourism['lng'] > 108.7) & (df_tourism['lng'] < 109.3) & (df_tourism['lat'] > 33.9) & (df_tourism['lat'] < 34.5) ] print(f"最终有效数据量: {len(df_tourism)}条") # 转换为GeoDataFrame geometry = [Point(xy) for xy in zip(df_tourism['lng'], df_tourism['lat'])] gdf = gpd.GeoDataFrame(df_tourism, geometry=geometry, crs="EPSG:4326") return gdf except Exception as e: print(f"数据加载出错: {str(e)}") return gpd.GeoDataFrame() # ==================== 2. 空间分析核心功能 ==================== def spatial_analysis(gdf): """执行完整的空间分析流程""" if gdf.empty: return None, None, None # 坐标转换(WGS84转UTM Zone 49N) transformer = Transformer.from_crs(4326, 32649) coords = np.array([transformer.transform(point.y, point.x) for point in gdf.geometry]) gdf['x'], gdf['y'] = coords[:, 0], coords[:, 1] # 1. 标准差椭圆计算 def calc_ellipse(x, y): cov = np.cov(x - x.mean(), y - y.mean()) eigvals, eigvecs = np.linalg.eig(cov) major = 2 * np.sqrt(eigvals[0]) minor = 2 * np.sqrt(eigvals[1]) angle = np.degrees(np.arctan2(*eigvecs[:, 0][::-1])) return major, minor, angle major, minor, angle = calc_ellipse(gdf['x'], gdf['y']) center = gdf.geometry.unary_union.centroid center_lng, center_lat = center.x, center.y # 2. 核密度估计 kde = gaussian_kde(np.vstack([gdf.geometry.x, gdf.geometry.y])) gdf['density'] = kde(np.vstack([gdf.geometry.x, gdf.geometry.y])) # 3. DBSCAN空间聚类 coords_rad = np.radians(np.column_stack([gdf.geometry.y, gdf.geometry.x])) dbscan = DBSCAN(eps=0.002, min_samples=5, metric='haversine').fit(coords_rad) gdf['cluster'] = dbscan.labels_ # 4. 空间自相关分析(使用投影坐标) try: w = DistanceBand.from_dataframe(gdf.to_crs(epsg=32649), threshold=2000) # 2km阈值 moran = Moran(gdf['density'].values, w) print(f"Moran's I: {moran.I:.3f} (p-value: {moran.p_sim:.3f})") except Exception as e: print(f"空间自相关分析失败: {str(e)}") moran = None return gdf, (major, minor, angle, center_lng, center_lat), moran # ==================== 3. 增强可视化 ==================== def plot_analysis_results(gdf, ellipse_params, moran=None): """绘制综合空间分析结果""" if gdf.empty: return # 创建地图画布 fig = plt.figure(figsize=(18, 12)) proj = ccrs.PlateCarree() # 1. 主图:空间分布与椭圆 ax1 = fig.add_subplot(221, projection=proj) ax1.set_extent([108.85, 109.15, 34.15, 34.45], crs=proj) # 地图底图 ax1.add_feature(cfeature.LAND.with_scale('50m'), facecolor='#f5f5f5') ax1.add_feature(cfeature.RIVERS.with_scale('50m'), edgecolor='#66b3ff') ax1.gridlines(draw_labels=True, linestyle='--', alpha=0.5) # 绘制核密度热力图 xi, yi = np.mgrid[108.85:109.15:200j, 34.15:34.45:200j] zi = gaussian_kde(np.vstack([gdf.geometry.x, gdf.geometry.y]))(np.vstack([xi.flatten(), yi.flatten()])) ax1.contourf(xi, yi, zi.reshape(xi.shape), levels=15, cmap='RdYlBu_r', alpha=0.6, transform=proj) # 绘制标准差椭圆 major, minor, angle, clng, clat = ellipse_params ellipse = Ellipse( (clng, clat), width=minor / 50000, height=major / 50000, angle=angle, edgecolor='#e63946', facecolor='none', linewidth=2, transform=proj, label='Std Ellipse' ) ax1.add_patch(ellipse) ax1.plot(clng, clat, 'ro', markersize=8, transform=proj) # 2. 子图1:聚类结果 ax2 = fig.add_subplot(222, projection=proj) ax2.set_extent([108.85, 109.15, 34.15, 34.45], crs=proj) ax2.set_title('DBSCAN Clustering Results', pad=15) # 按聚类分组绘制 for cluster in gdf['cluster'].unique(): if cluster == -1: # 噪声点 color = 'gray' alpha = 0.3 else: color = plt.cm.tab20(cluster % 20) alpha = 0.7 cluster_data = gdf[gdf['cluster'] == cluster] ax2.scatter(cluster_data.geometry.x, cluster_data.geometry.y, c=[color], s=15, alpha=alpha, transform=proj, label=f'Cluster {cluster}') # 3. 子图3:参数表格 ax3 = fig.add_subplot(223) ax3.axis('off') params = [ ["Center", f"{clng:.3f}°E, {clat:.3f}°N"], ["Major Axis", f"{major / 1000:.1f} km"], ["Minor Axis", f"{minor / 1000:.1f} km"], ["Orientation", f"{angle:.1f}°"], ["Area", f"{np.pi * major * minor / 1e6:.1f} km²"], ["Clusters", f"{len(gdf['cluster'].unique())} (incl. noise)"] ] if moran: params.append(["Moran's I", f"{moran.I:.3f} (p={moran.p_sim:.3f})"]) table = ax3.table(cellText=params, loc='center', cellLoc='left', colWidths=[0.3, 0.7]) table.auto_set_font_size(False) table.set_fontsize(12) table.scale(1, 2) # 全局设置 plt.suptitle('Xi\'an Tourism POI Spatial Analysis', fontsize=16, y=0.95) plt.tight_layout() plt.savefig('xian_poi_full_analysis.png', dpi=300, bbox_inches='tight') plt.show() # ==================== 主执行流程 ==================== if __name__ == "__main__": # 1. 数据加载 gdf = load_data() if not gdf.empty: # 2. 空间分析 gdf, ellipse_params, moran = spatial_analysis(gdf) # 3. 可视化 plot_analysis_results(gdf, ellipse_params, moran) # 保存分析结果 gdf.to_file('xian_poi_analysis_results.geojson', driver='GeoJSON') else: print("执行失败:无有效数据")
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/空间分析/sce_cluster.py
Python
unknown
6,950
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>推荐路线</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .route-step { margin-bottom: 15px; padding: 10px; background: #f5f5f5; border-radius: 5px; } .step-instruction { font-weight: bold; } .step-detail { color: #666; margin-left: 15px; } </style> </head> <body> <h1>推荐路线查询</h1> <label for="start">起点坐标 (纬度,经度): </label> <input type="text" id="start" placeholder="34.106054,109.343291"><br><br> <label for="end">终点坐标 (纬度,经度): </label> <input type="text" id="end" placeholder="34.107256,109.342358"><br><br> <button onclick="getRoute()">获取推荐路线</button> <h2>推荐路线详情</h2> <div id="result"></div> <script> function handleRouteResponse(data) { const routeInfo = formatRoute(data); document.getElementById('result').innerHTML = routeInfo; } function getRoute() { const start = document.getElementById('start').value; const end = document.getElementById('end').value; // 移除旧的script标签(如果存在) const oldScript = document.getElementById('baiduApiScript'); if (oldScript) oldScript.remove(); // 创建新的JSONP请求 const script = document.createElement('script'); script.id = 'baiduApiScript'; script.src = `https://api.map.baidu.com/direction/v2/driving?origin=${start}&destination=${end}&ak=SGEyhSS0Fir6EBEoarGXd8UubB75a1YI&callback=handleRouteResponse`; document.body.appendChild(script); } function formatRoute(data) { if (data.status !== 0) { return `<div class="error">错误: ${data.message || '无法获取路线信息'}</div>`; } const route = data.result.routes[0]; let output = ` <div class="route-summary"> <h3>路线概览</h3> <p><strong>总距离:</strong> ${(route.distance/1000).toFixed(2)}公里</p> <p><strong>预计时间:</strong> ${Math.floor(route.duration/60)}分钟</p> <p><strong>路线标签:</strong> ${route.tag || '无'}</p> </div> <h3>详细步骤</h3> `; route.steps.forEach((step, index) => { const directionText = getDirectionText(step.direction); output += ` <div class="route-step"> <div class="step-instruction">步骤 ${index+1}: ${directionText} ${step.road_name || '无名路'}</div> <div class="step-detail"> <p>距离: ${step.distance}米</p> <p>预计时间: ${step.duration}秒</p> <p>道路类型: ${getRoadType(step.road_type)}</p> </div> </div> `; }); return output; } // 辅助函数:将方向代码转换为文字 function getDirectionText(direction) { const directions = { 0: '正北', 1: '东北', 2: '正东', 3: '东南', 4: '正南', 5: '西南', 6: '正西', 7: '西北', 8: '正北', 9: '西北', 10: '西', 11: '西南', 12: '南', 13: '东南', 14: '东', 15: '东北' }; return directions[direction] || `方向(${direction})`; } // 辅助函数:将道路类型代码转换为文字 function getRoadType(type) { const types = { 0: '高速', 1: '城市快速路', 2: '国道', 3: '省道', 4: '县道', 5: '乡村道路', 6: '其他道路', 7: '步行道路', 8: '轮渡', 9: '其他' }; return types[type] || `未知道路类型(${type})`; } </script> </body> </html>
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/路线推荐/hudong.html
HTML
unknown
4,103
import requests def get_route(start_location, end_location, ak): url = f"http://api.map.baidu.com/direction/v2/transit?origin={start_location}&destination={end_location}&ak={ak}" response = requests.get(url) return response.json() # 示例调用 start = "34.105781,109.343251" # 蓝关古道的位置 end = "34.123456,109.123456" ak = "SGEyhSS0Fir6EBEoarGXd8UubB75a1YI" route = get_route(start, end, ak) print(route)
2301_78696cqk/Django_pyecharts_scrapy
xian_poi/路线推荐/route_rec.py
Python
unknown
431
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="送心"> <meta name="description" content="这是送心的测试网站,用于展示基本的HTML结构。"> <meta name="keywords" content="送心, 测试网站, HTML, 示例"> <title>送心的TEST网站</title> </head> <body> <header> <h1> <strong> 送心 </strong> <img src="1.jpg" width="50" height="50" alt="照片"> <a href="jianli.html">送心的简历</a> </h1> <hr> </header> <main> <h1> <strong> 这是我学习的路 </strong>这是我的<font color="red" size="7">第一个测试内容</font> </h1> <table border="1" cellpadding="8" cellspacing="3"> <tr> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> <tr> <td>送心</td> <td>22</td> <td>12</td> </tr> <tr> <td>小明</td> <td>23</td> <td>13</td> </tr> <tr> <td>小红</td> <td>24</td> <td>14</td> </table> <hr> <ul type="circle"> <li>123</li> <li>456</li> </ul> <ul type="disc"> <li>789</li> <li>123</li> </ul> <ul type="square"> <li>456</li> <li>789</li> </ul> <ol type="circle"> <li>123</li> <li>456</li> <li>789</li> </ol> <dl> <dt>水果手机</dt> <dd>1 yuan </dd> <dd>可以拍黑白照片</dd> </dl> <h2>必应搜索</h2> <form action="https://baidu.com/s" method="get"> 搜索:<input type="text" name="wd" placeholder="请输入你要搜索的内容"> <input type="submit" value="搜索"> <input type="password" name="ps"> </form> 男<input type="radio" name="gender" value="male" checked> 女<input type="radio" name="gender" value="female"> <hr> 读书<input type="checkbox" id="reading" name="hobby" value="reading" checked > 运动<input type="checkbox" id="sport" name="hobby" value="sport"> 旅行<input type="checkbox" id="travel" name="hobby" value="travel"> <hr> 账号:<input type="text" ><br> 密码:<input type="password"><br> <input type="button" value="提交"> <input type="button" value="重置"> <hr> <form> 账号: <input type="text" name="username" required placeholder="请输入你的账号" pattern="[a-zA-Z0-9]{6,12}" title="用户名必须是6-12位的字母或者数字"><br> <input type="submit"> </form> </main> </body> </html>
2301_79851282/frontend
00HTML基础/index.html
HTML
unknown
2,890
.rgb{ color:rgb(240, 6, 6); } .hex{ color: #eb46e0;; } .background-color { background-color: #eb5620; } .border-color { border:3px solid #665620; } .text-opacity { color:rgba(235,70,224,0.2); } .opacity { opacity:0.5; }
2301_79851282/frontend
01CSS/02颜色/global.css
CSS
unknown
273
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css"> </head> <body> <!--颜色,这里介绍RGB和Hex两种--> <div class="rgb">用RGB表示颜色</div> <div class="hex">用Hex表示颜色</div> <!--颜色可以赋给任何需要以颜色为值的语句--> <div class="background-color text-opacity">背景颜色</div> <div class="border-color opacity">opacity边款颜色</div> </body> </html>
2301_79851282/frontend
01CSS/02颜色/index.html
HTML
unknown
600
@font-face { font-family: "MaShanZheng"; src: url("./MaShanZheng-Regual.ttf"); } .text-1 { font-family: MaShanZheng, 'sans-serif'; } .text-2 { font-size: 24px; line-height: 32px; } .text-3 { font-weight: 700; font-style: italic; text-decoration: line-through; }
2301_79851282/frontend
01CSS/03文本/global.css
CSS
unknown
314
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css" type="text/css"> </head> <body> <!--文本--> <p class="text-1">文本样式1</p> <p class="text-2">文本样式2</p> <p class="text-3">文本样式3</p> </body> </html>
2301_79851282/frontend
01CSS/03文本/index.html
HTML
unknown
414
.box-model { /* margin-right: 18px; padding-top: 8px; */ /* margin: 6px 12px; */ margin: 12px 8px 24px 16px; /* 边框*/ border: 2px solid black; /*宽度和高度*/ width: 80px; height: 120px; }
2301_79851282/frontend
01CSS/04盒子模型/global.css
CSS
unknown
262
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css" type="text/css"> </head> <body> <div class="box-model">盒子模型</div> </body> </html>
2301_79851282/frontend
01CSS/04盒子模型/index.html
HTML
unknown
319
.inline { display: inline; } .inline-block { display: inline-block; width: 100px; height:220px; background-color: lightblue; } .none { display: none; }
2301_79851282/frontend
01CSS/05布局/global.css
CSS
unknown
190
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css"> </head> <body> <div class="inline">我会独占一行</div> <p class="inline">我会独占一行</p> <h1 clas="inline">我会独占一行</h1> <span>我不会独占一行</span> <a>我不会独占一行</a> <span class="inline-block">我本来不能设置宽高</span> <div class="none">我会隐藏起来</div> </body> </html>
2301_79851282/frontend
01CSS/05布局/index.html
HTML
unknown
594
.flex { display: flex; /* flex-direction: column; */ height: 120px; background-color: blue; justify-content: flex-end; align-items:first end; } /* .item { flex: 1px; } .item-2 { flex:2px } */
2301_79851282/frontend
01CSS/06弹性布局/global.css
CSS
unknown
260
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css"> </head> <body> <div class="flex"> <div class="item">项目</div> <div class="item-2">项目</div> <div class="item-3">项目</div> </div> </body> </html>
2301_79851282/frontend
01CSS/06弹性布局/index.html
HTML
unknown
416
.grid { display: grid; /* grid-template-rows: 100px 200px 300px; grid-template-columns: 1fr 2fr; */ grid-template-columns: repeat(4,1fr); grid-auto-flow: 100px; grid-auto-columns: 1fr; grid-gap: 12px; }
2301_79851282/frontend
01CSS/07网格布局/global.css
CSS
unknown
240
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css"> </head> <body> <!--网格布局--> <div class="grid"> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> <div>网格项目</div> </div> </body> </html>
2301_79851282/frontend
01CSS/07网格布局/index.html
HTML
unknown
717
/* .static { position:static; } */ .relative { position:relative; height: 200px; background-color: violet; } .absolute { position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
2301_79851282/frontend
01CSS/08定位/global.css
CSS
unknown
245
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css"> </head> <body> <!--定位--> <div class="relative"> <div class="absolute">图片</div> </div> <!-- <div class="fixed">c</div> <div class="static">d</div> --> </body> </html>
2301_79851282/frontend
01CSS/08定位/index.html
HTML
unknown
443
h4 { color: red; } .class{ color: aqua; } #id{ color: black; } .purple{ color: purple; } .orange{ color: orange; } .yellow{ color: yellow; } .red{ color: red; } /* .parent .child{ color: aquamarine; } */ .parent{ .child{ color: aquamarine; } } .violet { color: blue; } .text-lg{ font-size: 24px; } .text-center{ text-align: center; }
2301_79851282/frontend
01CSS/选择器/global.css
CSS
unknown
456
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="global.css" type="text/css"> </head> <body> <!--元素选择器,类选择器,ID选择器--> <h4>元素选择器</h4> <p class="class">类选择器</p> <p id="id">ID选择器</p> <!--类选择器是最常见的--> <p class="purple">我希望这段是紫色的</p> <p class="orange">我希望这段是橙色的</p> <p class="yellow">我希望这段是黄色的</p> <!--不同元素选择器也可以共享同一个类选择器的样式--> <div class="red">div类选择器</div> <nav class="red">nav类选择器</nav> <footer class="red">footer类选择器</footer> <!--层级关系--> <div class="parent"> <div class="child">父级中的子级可区别于同类的其他元素</div> </div> <div class="child">同名的其他元素</div> <!--在同一个元素上分配多个类--> <div class="violet text-lg text-center">复杂的样式</div> </body> </html>
2301_79851282/frontend
01CSS/选择器/index.html
HTML
unknown
1,180
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./main.css"> </head> <body> <h1>Coffee Order</h1> <ul id="orders"> <!-- <li class="order" id="1"> <p> Name: <span class="name">John</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">Coffee</span> <input type="text" class="drink nonedit"> </p> <button data-id="1" class="delete-order">Delete</button> <button class="edit-order">Edit</button> <button class="save-edit nonedit">Save</button> <button class="cancel-edit nonedit">Cancel</button> </li> <li class="order" id="2"> <p> Name: <span class="name">Emily</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">Mocha</span> <input type="text" class="drink nonedit"> </p> <button data-id="2" class="delete-order">Delete</button> <button class="edit-order">Edit</button> <button class="save-edit nonedit">Save</button> <button class="cancel-edit nonedit">Cancel</button> </li> --> </ul> <h4>Add a Coffee Order</h4> <p>name: <input type="text" id="name"></p> <p>drink: <input type="text" id="drink"></p> <button id="add-order">Add!</button> <script src="./jquery-3.5.1.js"></script> <script src="./script.js"></script> </body> </html>
2301_79534346/CoffeeOrder
CoffeeOrder/CoffeeOrder/src/public/index.html
HTML
apache-2.0
1,811
* { padding: 0; margin: 10px; } #orders { list-style-type: none; margin: 0; } #orders .order { background-color: #c4c4c4; padding: 5px; } #orders .nonedit { display: none; } #orders .edit { display: none; } button { padding: 5px 10px; }
2301_79534346/CoffeeOrder
CoffeeOrder/CoffeeOrder/src/public/main.css
CSS
apache-2.0
277
$(function () { let $name = $('#name') let $drink = $('#drink') let $orders = $('#orders') function addOrder(order) { $orders.append(`<li class="order" id="${order.id}"> <p> Name: <span class="name">${order.name}</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">${order.drink}</span> <input type="text" class="drink nonedit"> </p> <!--<button data-id="${order.id}" class="delete-order">Delete</button> <button data-id="${order.id}" class="edit-order">Edit</button> <button data-id="${order.id}" class="save-edit nonedit">Save</button> <button data-id="${order.id}" class="cancel-edit nonedit">Cancel</button>--> </li>`) } $.ajax({ url: '/orders', type: 'GET', dataType: 'json', success: function (data) { console.log(data) //let orders = JSON.parse(data)这里的data已经是js对象了,而且是个对象数组 $.each(data, function (index, order) { addOrder(order) }) }, error: function () { alert('error in GET') } }) $('#add-order').on('click', function () { if($name.val() === '' || $drink.val() === ''){ alert('Please input name and drink') return } $.ajax({ url: '/orders', type: 'POST', dataType: 'json', //服务器返回的数据类型 contentType: 'application/json', //发送的数据类型 data: JSON.stringify({ name: $name.val(), drink: $drink.val() }), success: function (data) { console.log(data) addOrder(data) }, error: function () { alert('error in POST') } }) //清空输入框 $name.val('') $drink.val('') }) /* $orders.delegate('.delete-order', 'click', function () { $li = $(this).closest('.order') $.ajax({ url: `/orders/${$li.attr('id')}`, type: 'DELETE', success: function () { $li.slideUp(300, function () { $li.remove() // 从DOM中移除元素,slideUp()不会移除而是添加了display:none }) }, error: function () { alert('error in DELETE') } }) }) $orders.delegate('.edit-order', 'click', function () { $li = $(this).closest('.order') $li.find('input.name').val($li.find('span.name').text()) $li.find('input.drink').val($li.find('span.drink').text()) $li.find('span,.edit-order').addClass('edit') $li.find('.nonedit').removeClass('nonedit') }) $orders.delegate('.cancel-edit', 'click', function () { $li = $(this).closest('.order') $li.find('span,.edit-order').removeClass('edit') $li.find('input,.save-edit,.cancel-edit').addClass('nonedit') }) $orders.delegate('.save-edit', 'click', function () { $li = $(this).closest('.order') $.ajax({ url: `/orders/${$li.attr('id')}`, type: 'PUT', dataType: 'json', contentType: 'application/json', data: JSON.stringify({ name: $li.find('input.name').val(), drink: $li.find('input.drink').val() }), success: function () { $li.find('span.name').text($li.find('input.name').val()) $li.find('span.drink').text($li.find('input.drink').val()) $li.find('span,.edit-order').removeClass('edit') $li.find('input,.save-edit,.cancel-edit').addClass('nonedit') }, error: function () { alert('error in PUT') } }) })*/ })
2301_79534346/CoffeeOrder
CoffeeOrder/CoffeeOrder/src/public/script.js
JavaScript
apache-2.0
4,073
package cc.lecaicai.mcp.server.computer; import cc.lecaicai.mcp.server.computer.domain.service.ComputerService; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.tool.ToolCallbackProvider; import org.springframework.ai.tool.method.MethodToolCallbackProvider; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @Slf4j @SpringBootApplication //这个启动类为何要这么写,它继承的这个CommandLineRunner又是干什么的,如何在一个mcp server中起作用 //能否描述一下用java开发MCPserver的过程 public class McpServerComputerApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(McpServerComputerApplication.class, args); } //这个配置类的作用是什么 @Bean public ToolCallbackProvider computerTools(ComputerService computerService){ return MethodToolCallbackProvider.builder().toolObjects(computerService).build(); } @Override public void run(String... args) throws Exception{ log.info("mcp server computer success!"); } }
2301_79945976/mcp-server-computer
src/main/java/cc/lecaicai/mcp/server/computer/McpServerComputerApplication.java
Java
unknown
1,263
package cc.lecaicai.mcp.server.computer.domain.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import lombok.Data; @Data @JsonInclude(JsonInclude.Include.NON_NULL)//这个注解是干嘛用的 public class ComputerFunctionRequest { //这两个注解又是干啥用的,这个类存在对mcp服务的意义在何 @JsonProperty(required = true, value = "computer") @JsonPropertyDescription("电脑名称") private String computer; }
2301_79945976/mcp-server-computer
src/main/java/cc/lecaicai/mcp/server/computer/domain/model/ComputerFunctionRequest.java
Java
unknown
583
package cc.lecaicai.mcp.server.computer.domain.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import lombok.Data; //同样也解释一下这个类是干啥的 @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class ComputerFunctionResponse { @JsonProperty(required = true, value = "osName") @JsonPropertyDescription("操作系统名称") private String osName; @JsonProperty(required = true, value = "osVersion") @JsonPropertyDescription("操作系统版本") private String osVersion; @JsonProperty(required = true, value = "osArch") @JsonPropertyDescription("操作系统架构") private String osArch; @JsonProperty(required = true, value = "userName") @JsonPropertyDescription("用户的账户名称") private String userName; @JsonProperty(required = true, value = "userHome") @JsonPropertyDescription("用户的主目录") private String userHome; @JsonProperty(required = true, value = "userDir") @JsonPropertyDescription("用户的当前工作目录") private String userDir; @JsonProperty(required = true, value = "javaVersion") @JsonPropertyDescription("Java 运行时环境版本") private String javaVersion; @JsonProperty(required = true, value = "osInfo") @JsonPropertyDescription("系统信息") private String osInfo; }
2301_79945976/mcp-server-computer
src/main/java/cc/lecaicai/mcp/server/computer/domain/model/ComputerFunctionResponse.java
Java
unknown
1,481
package cc.lecaicai.mcp.server.computer.domain.service; import cc.lecaicai.mcp.server.computer.domain.model.ComputerFunctionRequest; import cc.lecaicai.mcp.server.computer.domain.model.ComputerFunctionResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.tool.annotation.Tool; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; @Slf4j @Service public class ComputerService { @Tool(description = "获取电脑配置") public ComputerFunctionResponse queryConfig(ComputerFunctionRequest request){ log.info("获取电脑配置信息 :{}",request.getComputer()); Properties properties = System.getProperties(); //操作系统名称 String osName = properties.getProperty("os.name"); // 操作系统版本 String osVersion = properties.getProperty("os.version"); // 操作系统架构 String osArch = properties.getProperty("os.arch"); // 用户的账户名称 String userName = properties.getProperty("user.name"); // 用户的主目录 String userHome = properties.getProperty("user.home"); // 用户的当前工作目录 String userDir = properties.getProperty("user.dir"); // Java 运行时环境版本 String javaVersion = properties.getProperty("java.version"); String osInfo = ""; if (osName.toLowerCase().contains("win")) { osInfo = getWindowsSpecificInfo(); }else if (osName.toLowerCase().contains("mac")) { osInfo = getMacSpecificInfo(); }else if (osName.toLowerCase().contains("nix") || osName.toLowerCase().contains("nux")) { osInfo = getLinuxSpecificInfo(); } ComputerFunctionResponse response = new ComputerFunctionResponse(); response.setOsName(osName); response.setOsVersion(osVersion); response.setOsArch(osArch); response.setUserName(userName); response.setUserHome(userHome); response.setUserDir(userDir); response.setJavaVersion(javaVersion); response.setOsInfo(osInfo); return response; } private String getWindowsSpecificInfo() { //解释一下是如何获取WIndos特定的系统信息的,各个系统之间又有什么区别 StringBuilder cache = new StringBuilder(); try { Process process = Runtime.getRuntime().exec("systeminfo"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null){ cache.append(line); } } catch (IOException e) { e.printStackTrace(); } return cache.toString(); } private String getMacSpecificInfo() { StringBuilder cache = new StringBuilder(); // macOS特定的系统信息获取 try { Process process = Runtime.getRuntime().exec("system_profiler SPHardwareDataType"); java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { cache.append(line); } } catch (Exception e) { e.printStackTrace(); } return cache.toString(); } private String getLinuxSpecificInfo() { StringBuilder cache = new StringBuilder(); // Linux特定的系统信息获取 try { Process process = Runtime.getRuntime().exec("lshw -short"); java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { cache.append(line); } } catch (Exception e) { e.printStackTrace(); } return cache.toString(); } }
2301_79945976/mcp-server-computer
src/main/java/cc/lecaicai/mcp/server/computer/domain/service/ComputerService.java
Java
unknown
4,125
package cn.bugstack.knowledge; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2301_79945976/mcp-project
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/Application.java
Java
unknown
314
package cn.bugstack.knowledge.config; import org.springframework.ai.ollama.OllamaEmbeddingModel; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.ai.vectorstore.pgvector.PgVectorStore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class OllamaConfig { @Bean("ollamaSimpleVectorStore") public SimpleVectorStore vectorStore(OllamaApi ollamaApi) { OllamaEmbeddingModel embeddingModel = OllamaEmbeddingModel .builder() .ollamaApi(ollamaApi) .defaultOptions(OllamaOptions.builder().model("nomic-embed-text").build()) .build(); return SimpleVectorStore.builder(embeddingModel).build(); } /** * -- 删除旧的表(如果存在) * DROP TABLE IF EXISTS public.vector_store_ollama_deepseek; * * -- 创建新的表,使用UUID作为主键 * CREATE TABLE public.vector_store_ollama_deepseek ( * id UUID PRIMARY KEY DEFAULT gen_random_uuid(), * content TEXT NOT NULL, * metadata JSONB, * embedding VECTOR(768) * ); * * SELECT * FROM vector_store_ollama_deepseek */ @Bean("ollamaPgVectorStore") public PgVectorStore pgVectorStore(OllamaApi ollamaApi, JdbcTemplate jdbcTemplate) { OllamaEmbeddingModel embeddingModel = OllamaEmbeddingModel .builder() .ollamaApi(ollamaApi) .defaultOptions(OllamaOptions.builder().model("nomic-embed-text").build()) .build(); return PgVectorStore.builder(jdbcTemplate, embeddingModel) .vectorTableName("vector_store_ollama_deepseek") .build(); } }
2301_79945976/mcp-project
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/config/OllamaConfig.java
Java
unknown
1,963
package cn.bugstack.knowledge.config; import io.micrometer.observation.ObservationRegistry; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.DefaultChatClientBuilder; import org.springframework.ai.chat.client.observation.ChatClientObservationConvention; import org.springframework.ai.openai.OpenAiChatModel; import org.springframework.ai.openai.OpenAiEmbeddingModel; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.ai.vectorstore.pgvector.PgVectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class OpenAIConfig { @Bean public TokenTextSplitter tokenTextSplitter() { return new TokenTextSplitter(); } @Bean public OpenAiApi openAiApi(@Value("${spring.ai.openai.base-url}") String baseUrl, @Value("${spring.ai.openai.api-key}") String apikey) { return OpenAiApi.builder() .baseUrl(baseUrl) .apiKey(apikey) .build(); } @Bean("openAiSimpleVectorStore") public SimpleVectorStore vectorStore(OpenAiApi openAiApi) { OpenAiEmbeddingModel embeddingModel = new OpenAiEmbeddingModel(openAiApi); return SimpleVectorStore.builder(embeddingModel).build(); } /** * -- 删除旧的表(如果存在) * DROP TABLE IF EXISTS public.vector_store_openai; * * -- 创建新的表,使用UUID作为主键 * CREATE TABLE public.vector_store_openai ( * id UUID PRIMARY KEY DEFAULT gen_random_uuid(), * content TEXT NOT NULL, * metadata JSONB, * embedding VECTOR(1536) * ); * * SELECT * FROM vector_store_openai */ @Bean("openAiPgVectorStore") public PgVectorStore pgVectorStore(OpenAiApi openAiApi, JdbcTemplate jdbcTemplate) { OpenAiEmbeddingModel embeddingModel = new OpenAiEmbeddingModel(openAiApi); return PgVectorStore.builder(jdbcTemplate, embeddingModel) .vectorTableName("vector_store_openai") .build(); } @Bean public ChatClient.Builder chatClientBuilder(OpenAiChatModel openAiChatModel) { return new DefaultChatClientBuilder(openAiChatModel, ObservationRegistry.NOOP, (ChatClientObservationConvention) null); } }
2301_79945976/mcp-project
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/config/OpenAIConfig.java
Java
unknown
2,607
curl http://117.72.115.188:11434/api/generate \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-r1:1.5b", "prompt": "1+1", "stream": false }'
2301_79945976/mcp-project
docs/dev-ops/api/curl_local.sh
Shell
unknown
190
curl http://58a39caa684c41bf9bed-deepseek-r1-llm-api.gcs-xy1a.jdcloud.com/api/generate \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-r1:1.5b", "prompt": "1+1", "stream": false }'
2301_79945976/mcp-project
docs/dev-ops/api/curl_yun.sh
Shell
unknown
231
.chat-item { @apply flex items-center gap-2 p-2 hover:bg-gray-100 rounded cursor-pointer transition-colors; } .chat-item.selected { @apply bg-blue-50; /* 或使用深色背景如bg-gray-200 */ } .chat-item-content { @apply flex-1 truncate; } .chat-actions { @apply flex items-center justify-end opacity-0 transition-opacity w-8; } .chat-item:hover.chat-actions { @apply opacity-100; } .context-menu { @apply absolute bg-white border rounded-lg shadow-lg py-1 z-50; min-width: 120px; } .context-menu-item { @apply px-4 py-2 hover:bg-gray-100 text-sm flex items-center gap-2; } .markdown-body { font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji; font-size: 16px; line-height: 1.5; word-wrap: break-word; } .markdown-body pre { background-color: #f6f8fa; border-radius: 6px; padding: 16px; overflow-x: auto; } .markdown-body code { background-color: rgba(175,184,193,0.2); border-radius: 6px; padding: 0.2em 0.4em; font-size: 85%; } .markdown-body pre code { background-color: transparent; padding: 0; font-size: 100%; } .markdown-body h1,.markdown-body h2,.markdown-body h3, .markdown-body h4,.markdown-body h5,.markdown-body h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; } .markdown-body h1 { font-size: 2em; } .markdown-body h2 { font-size: 1.5em; } .markdown-body h3 { font-size: 1.25em; } .markdown-body ul,.markdown-body ol { padding-left: 2em; } .markdown-body ul { list-style-type: disc; } .markdown-body ol { list-style-type: decimal; } .markdown-body table { border-spacing: 0; border-collapse: collapse; margin-top: 0; margin-bottom: 16px; } .markdown-body table th,.markdown-body table td { padding: 6px 13px; border: 1px solid #d0d7de; } .markdown-body table tr:nth-child(2n) { background-color: #f6f8fa; } .chat-actions button { margin-left: 4px; /* Add some space between buttons */ } /* 下拉菜单过渡动画 */ #uploadMenu { transition: all 0.2s ease-out; transform-origin: top right; } #uploadMenu a { transition: background-color 0.2s ease; }
2301_79945976/mcp-project
docs/dev-ops/nginx/html/css/index.css
CSS
unknown
2,351
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>解析仓库</title> <style> body { font-family: 'Microsoft YaHei', '微软雅黑', sans-serif; background-color: #f0f0f0; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .container { background-color: white; padding: 2rem; border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); text-align: center; width: 300px; } h1 { color: #333; margin-bottom: 1.5rem; } .form-group { margin-bottom: 1rem; } input { width: 100%; padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; font-size: 1rem; box-sizing: border-box; } button { background-color: #1E90FF; color: white; border: none; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 4px; cursor: pointer; transition: background-color 0.3s; width: 100%; } button:hover { background-color: #4169E1; } #status { margin-top: 1rem; font-weight: bold; } .overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center; } .loading-spinner { border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> </head> <body> <div class="container"> <h1>上传Git仓库</h1> <form id="uploadForm"> <div class="form-group"> <input type="text" id="repoUrl" placeholder="Git仓库地址" required> </div> <div class="form-group"> <input type="text" id="userName" placeholder="用户名" required> </div> <div class="form-group"> <input type="password" id="token" placeholder="密码/Token" required> </div> <button type="submit">提交</button> </form> <div id="status"></div> </div> <div class="overlay" id="loadingOverlay"> <div class="loading-spinner"></div> </div> <script> const loadingOverlay = document.getElementById('loadingOverlay'); document.getElementById('uploadForm').addEventListener('submit', function(e) { e.preventDefault(); const repoUrl = document.getElementById('repoUrl').value; const userName = document.getElementById('userName').value; const token = document.getElementById('token').value; loadingOverlay.style.display = 'flex'; document.getElementById('status').textContent = ''; fetch('http://localhost:8090/api/v1/rag/analyze_git_repository', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `repoUrl=${encodeURIComponent(repoUrl)}&userName=${encodeURIComponent(userName)}&token=${encodeURIComponent(token)}` }) .then(response => response.json()) .then(data => { loadingOverlay.style.display = 'none'; if (data.code === '0000') { document.getElementById('status').textContent = '上传成功'; // 成功提示并关闭窗口 setTimeout(() => { alert('上传成功,窗口即将关闭'); window.close(); }, 500); } else { document.getElementById('status').textContent = '上传失败'; } }) .catch(error => { loadingOverlay.style.display = 'none'; document.getElementById('status').textContent = '上传仓库时出错'; }); }); </script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/git.html
HTML
unknown
4,562
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AiRagKnowledge - By 小傅哥</title> <script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/highlight.js/highlight.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js/styles/github.min.css"> <link rel="stylesheet" href="css/index.css"> </head> <body class="h-screen flex flex-col bg-gray-50"> <!-- Top Navigation --> <nav class="border-b bg-white px-4 py-2 flex items-center gap-2"> <button id="toggleSidebar" class="p-2 hover:bg-gray-100 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 sidebar-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path id="sidebarIconPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /> </svg> </button> <button id="newChatBtn" class="flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /> </svg> 新聊天 </button> <div class="flex-1 flex items-center gap-4"> <select id="aiModel" class="px-3 py-2 border rounded-lg flex-1 max-w-xs"> <option value="ollama" model="deepseek-r1:1.5b">deepseek-r1:1.5b</option> <option value="openai" model="gpt-4o">gpt-4o</option> </select> <select id="ragSelect" class="px-3 py-2 border rounded-lg flex-1 max-w-xs"> <option value="">选择一个知识库</option> </select> </div> <div class="flex items-center gap-2"> <div class="relative group"> <button id="uploadMenuButton" class="p-2 hover:bg-gray-100 rounded-lg flex items-center gap-1"> 🐙上传知识 <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" /> </svg> </button> <!-- 下拉菜单 --> <div class="hidden absolute right-0 mt-2 w-48 bg-white border rounded-md shadow-lg z-50" id="uploadMenu"> <a href="upload.html" target="_blank" class="block px-4 py-2 text-gray-700 hover:bg-gray-100"> 📁 上传文件 </a> <a href="git.html" target="_blank" class="block px-4 py-2 text-gray-700 hover:bg-gray-100"> ⎇ 解析仓库(Git) </a> </div> </div> </div> </nav> <div class="flex-1 flex overflow-hidden"> <!-- 侧边栏结构 --> <aside id="sidebar" class="w-64 bg-white border-r overflow-y-auto transition-all duration-300 ease-in-out"> <div class="p-4"> <h2 class="font-bold mb-2 text-lg">聊天列表</h2> <ul id="chatList" class="space-y-1"> <!-- 聊天列表项结构修改 --> </ul> </div> </aside> <!-- Main Content --> <div class="flex-1 flex flex-col overflow-hidden"> <!-- Chat Area --> <main class="flex-1 overflow-auto p-4" id="chatArea"> <div id="welcomeMessage" class="flex items-center justify-center h-full"> <div class="bg-white p-6 rounded-lg shadow-md text-center"> <div class="flex items-center gap-2 justify-center text-gray-500 mb-4"> <span class="w-2 h-2 bg-green-500 rounded-full"></span> Ollama 正在运行 🐏 </div> <p class="text-gray-600">开始新的对话吧!</p> </div> </div> </main> <!-- Input Area --> <div class="p-4"> <div class="max-w-4xl mx-auto"> <div class="border rounded-lg bg-white"> <div class="flex flex-col"> <textarea id="messageInput" class="w-full px-3 py-2 min-h-[100px] focus:outline-none resize-none" placeholder="输入一条消息..."></textarea> <div class="flex items-center justify-between px-3 py-2 border-t"> <div class="flex items-center gap-2"> <button class="p-2 hover:bg-gray-100 rounded-lg">🌐</button> </div> <button id="submitBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2"> 提交 <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /> </svg> </button> </div> </div> </div> </div> </div> </div> </div> <script src="js/index.js"></script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/index.html
HTML
unknown
5,824
const chatArea = document.getElementById('chatArea'); const messageInput = document.getElementById('messageInput'); const submitBtn = document.getElementById('submitBtn'); const newChatBtn = document.getElementById('newChatBtn'); const chatList = document.getElementById('chatList'); const welcomeMessage = document.getElementById('welcomeMessage'); const toggleSidebarBtn = document.getElementById('toggleSidebar'); const sidebar = document.getElementById('sidebar'); let currentEventSource = null; let currentChatId = null; // 获取知识库列表 document.addEventListener('DOMContentLoaded', function() { // 获取知识库列表 const loadRagOptions = () => { const ragSelect = document.getElementById('ragSelect'); fetch('http://localhost:8090/api/v1/rag/query_rag_tag_list') .then(response => response.json()) .then(data => { if (data.code === '0000' && data.data) { // 清空现有选项(保留第一个默认选项) while (ragSelect.options.length > 1) { ragSelect.remove(1); } // 添加新选项 data.data.forEach(tag => { const option = new Option(`Rag:${tag}`, tag); ragSelect.add(option); }); } }) .catch(error => { console.error('获取知识库列表失败:', error); }); }; // 初始化加载 loadRagOptions(); }); function createNewChat() { const chatId = Date.now().toString(); currentChatId = chatId; localStorage.setItem('currentChatId', chatId); // 修改数据结构为包含name和messages的对象 localStorage.setItem(`chat_${chatId}`, JSON.stringify({ name: '新聊天', messages: [] })); updateChatList(); clearChatArea(); } function deleteChat(chatId) { if (confirm('确定要删除这个聊天记录吗?')) { localStorage.removeItem(`chat_${chatId}`); // Remove the chat from localStorage if (currentChatId === chatId) { // If the current chat is being deleted createNewChat(); // Create a new chat } updateChatList(); // Update the chat list to reflect changes } } function updateChatList() { chatList.innerHTML = ''; const chats = Object.keys(localStorage) .filter(key => key.startsWith('chat_')); const currentChatIndex = chats.findIndex(key => key.split('_')[1] === currentChatId); if (currentChatIndex!== -1) { const currentChat = chats[currentChatIndex]; chats.splice(currentChatIndex, 1); chats.unshift(currentChat); } chats.forEach(chatKey => { let chatData = JSON.parse(localStorage.getItem(chatKey)); const chatId = chatKey.split('_')[1]; // 数据迁移:将旧数组格式转换为新对象格式 if (Array.isArray(chatData)) { chatData = { name: `聊天 ${new Date(parseInt(chatId)).toLocaleDateString()}`, messages: chatData }; localStorage.setItem(chatKey, JSON.stringify(chatData)); } const li = document.createElement('li'); li.className = `chat-item flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg cursor-pointer transition-colors ${chatId === currentChatId? 'bg-blue-50' : ''}`; li.innerHTML = ` <div class="flex-1"> <div class="text-sm font-medium">${chatData.name}</div> <div class="text-xs text-gray-400">${new Date(parseInt(chatId)).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })}</div> </div> <div class="chat-actions flex items-center gap-1 opacity-0 transition-opacity duration-200"> <button class="p-1 hover:bg-gray-200 rounded text-gray-500" onclick="renameChat('${chatId}')">重命名</button> <button class="p-1 hover:bg-red-200 rounded text-red-500" onclick="deleteChat('${chatId}')">删除</button> </div> `; li.addEventListener('click', (e) => { if (!e.target.closest('.chat-actions')) { loadChat(chatId); } }); li.addEventListener('mouseenter', () => { li.querySelector('.chat-actions').classList.remove('opacity-0'); }); li.addEventListener('mouseleave', () => { li.querySelector('.chat-actions').classList.add('opacity-0'); }); chatList.appendChild(li); }); } let currentContextMenu = null; // 优化后的上下文菜单 function showChatContextMenu(event, chatId) { event.stopPropagation(); closeContextMenu(); const buttonRect = event.target.closest('button').getBoundingClientRect(); const menu = document.createElement('div'); menu.className = 'context-menu'; menu.style.position = 'fixed'; menu.style.left = `${buttonRect.left}px`; menu.style.top = `${buttonRect.bottom + 4}px`; menu.innerHTML = ` <div class="context-menu-item" onclick="renameChat('${chatId}')"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/> </svg> 重命名 </div> <div class="context-menu-item text-red-500" onclick="deleteChat('${chatId}')"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/> </svg> 删除 </div> `; document.body.appendChild(menu); currentContextMenu = menu; // 点击外部关闭菜单 setTimeout(() => { document.addEventListener('click', closeContextMenu, { once: true }); }); } function closeContextMenu() { if (currentContextMenu) { currentContextMenu.remove(); currentContextMenu = null; } } function renameChat(chatId) { const chatKey = `chat_${chatId}`; const chatData = JSON.parse(localStorage.getItem(chatKey)); const currentName = chatData.name || `聊天 ${new Date(parseInt(chatId)).toLocaleString()}`; const newName = prompt('请输入新的聊天名称', currentName); if (newName) { chatData.name = newName; localStorage.setItem(chatKey, JSON.stringify(chatData)); updateChatList(); } } function loadChat(chatId) { currentChatId = chatId; localStorage.setItem('currentChatId', chatId); clearChatArea(); const chatData = JSON.parse(localStorage.getItem(`chat_${chatId}`) || { messages: [] }); chatData.messages.forEach(msg => { appendMessage(msg.content, msg.isAssistant, false); }); updateChatList() } function clearChatArea() { chatArea.innerHTML = ''; welcomeMessage.style.display = 'flex'; } function appendMessage(content, isAssistant = false, saveToStorage = true) { welcomeMessage.style.display = 'none'; const messageDiv = document.createElement('div'); messageDiv.className = `max-w-4xl mx-auto mb-4 p-4 rounded-lg ${isAssistant ? 'bg-gray-100' : 'bg-white border'} markdown-body relative`; const renderedContent = DOMPurify.sanitize(marked.parse(content)); messageDiv.innerHTML = renderedContent; // 添加复制按钮 const copyBtn = document.createElement('button'); copyBtn.className = 'absolute top-2 right-2 p-1 bg-gray-200 rounded-md text-xs'; copyBtn.textContent = '复制'; copyBtn.onclick = () => { navigator.clipboard.writeText(content).then(() => { copyBtn.textContent = '已复制'; setTimeout(() => copyBtn.textContent = '复制', 2000); }); }; messageDiv.appendChild(copyBtn); chatArea.appendChild(messageDiv); chatArea.scrollTop = chatArea.scrollHeight; // 仅在需要时保存到本地存储 if (saveToStorage && currentChatId) { // 确保读取和保存完整的数据结构 const chatData = JSON.parse(localStorage.getItem(`chat_${currentChatId}`) || '{"name": "新聊天", "messages": []}'); chatData.messages.push({ content, isAssistant }); localStorage.setItem(`chat_${currentChatId}`, JSON.stringify(chatData)); } } function startEventStream(message) { if (currentEventSource) { currentEventSource.close(); } // 选项值, // 组装01;http://localhost:8090/api/v1/ollama/generate_stream?message=Hello&model=deepseek-r1:1.5b // 组装02;http://localhost:8090/api/v1/openai/generate_stream?message=Hello&model=gpt-4o const ragTag = document.getElementById('ragSelect').value; const aiModelSelect = document.getElementById('aiModel'); const aiModelValue = aiModelSelect.value; // 获取选中的 aiModel 的 value const aiModelModel = aiModelSelect.options[aiModelSelect.selectedIndex].getAttribute('model'); // 获取选中的 aiModel 的 model 属性 let url; if (ragTag) { url = `http://localhost:8090/api/v1/${aiModelValue}/generate_stream_rag?message=${encodeURIComponent(message)}&ragTag=${encodeURIComponent(ragTag)}&model=${encodeURIComponent(aiModelModel)}`; } else { url = `http://localhost:8090/api/v1/${aiModelValue}/generate_stream?message=${encodeURIComponent(message)}&model=${encodeURIComponent(aiModelModel)}`; } currentEventSource = new EventSource(url); let accumulatedContent = ''; let tempMessageDiv = null; currentEventSource.onmessage = function(event) { try { const data = JSON.parse(event.data); if (data.result?.output?.content) { const newContent = data.result.output.content; accumulatedContent += newContent; // 首次创建临时消息容器 if (!tempMessageDiv) { tempMessageDiv = document.createElement('div'); tempMessageDiv.className = 'max-w-4xl mx-auto mb-4 p-4 rounded-lg bg-gray-100 markdown-body relative'; chatArea.appendChild(tempMessageDiv); welcomeMessage.style.display = 'none'; } // 直接更新文本内容(先不解析Markdown) tempMessageDiv.textContent = accumulatedContent; chatArea.scrollTop = chatArea.scrollHeight; } if (data.result?.output?.properties?.finishReason === 'STOP') { currentEventSource.close(); // 流式传输完成后进行最终渲染 const finalContent = accumulatedContent; tempMessageDiv.innerHTML = DOMPurify.sanitize(marked.parse(finalContent)); // 添加复制按钮 const copyBtn = document.createElement('button'); copyBtn.className = 'absolute top-2 right-2 p-1 bg-gray-200 rounded-md text-xs'; copyBtn.textContent = '复制'; copyBtn.onclick = () => { navigator.clipboard.writeText(finalContent).then(() => { copyBtn.textContent = '已复制'; setTimeout(() => copyBtn.textContent = '复制', 2000); }); }; tempMessageDiv.appendChild(copyBtn); // 保存到本地存储 if (currentChatId) { // 正确的数据结构应该是对象包含messages数组 const chatData = JSON.parse(localStorage.getItem(`chat_${currentChatId}`) || '{"name": "新聊天", "messages": []}'); chatData.messages.push({ content: finalContent, isAssistant: true }); localStorage.setItem(`chat_${currentChatId}`, JSON.stringify(chatData)); } } } catch (e) { console.error('Error parsing event data:', e); } }; currentEventSource.onerror = function(error) { console.error('EventSource error:', error); currentEventSource.close(); }; } submitBtn.addEventListener('click', () => { const message = messageInput.value.trim(); if (!message) return; if (!currentChatId) { createNewChat(); } appendMessage(message, false); messageInput.value = ''; startEventStream(message); }); messageInput.addEventListener('keypress', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submitBtn.click(); } }); newChatBtn.addEventListener('click', createNewChat); toggleSidebarBtn.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); updateSidebarIcon(); }); function updateSidebarIcon() { const iconPath = document.getElementById('sidebarIconPath'); if (sidebar.classList.contains('-translate-x-full')) { iconPath.setAttribute('d', 'M4 6h16M4 12h4m12 0h-4M4 18h16'); } else { iconPath.setAttribute('d', 'M4 6h16M4 12h16M4 18h16'); } } // Initialize updateChatList(); const savedChatId = localStorage.getItem('currentChatId'); if (savedChatId) { loadChat(savedChatId); } // Handle window resize for responsive design window.addEventListener('resize', () => { if (window.innerWidth > 768) { sidebar.classList.remove('-translate-x-full'); } else { sidebar.classList.add('-translate-x-full'); } }); // Initial check for mobile devices if (window.innerWidth <= 768) { sidebar.classList.add('-translate-x-full'); } updateSidebarIcon(); // 上传知识下拉菜单控制 const uploadMenuButton = document.getElementById('uploadMenuButton'); const uploadMenu = document.getElementById('uploadMenu'); // 切换菜单显示 uploadMenuButton.addEventListener('click', (e) => { e.stopPropagation(); uploadMenu.classList.toggle('hidden'); }); // 点击外部区域关闭菜单 document.addEventListener('click', (e) => { if (!uploadMenu.contains(e.target) && e.target !== uploadMenuButton) { uploadMenu.classList.add('hidden'); } }); // 菜单项点击后关闭菜单 document.querySelectorAll('#uploadMenu a').forEach(item => { item.addEventListener('click', () => { uploadMenu.classList.add('hidden'); }); });
2301_79945976/mcp-project
docs/dev-ops/nginx/html/js/index.js
JavaScript
unknown
14,751
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件上传</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdn.tailwindcss.com"></script> <style> /* 加载动画 */ .loader { animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> </head> <body class="flex justify-center items-center min-h-screen bg-gray-100"> <!-- 上传文件模态框 --> <div class="bg-white p-6 rounded-lg shadow-lg w-96 relative"> <!-- 加载遮罩层 --> <div id="loadingOverlay" class="hidden absolute inset-0 bg-white bg-opacity-90 flex flex-col items-center justify-center rounded-lg"> <div class="loader mb-4"> <svg class="h-8 w-8 text-blue-600" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12 2V6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M12 18V22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M4.93 4.93L7.76 7.76" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M16.24 16.24L19.07 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M2 12H6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M18 12H22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M4.93 19.07L7.76 16.24" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> <path d="M16.24 7.76L19.07 4.93" stroke="currentColor" stroke-width="2" stroke-linecap="round"/> </svg> </div> <p class="text-gray-600">文件上传中,请稍候...</p> </div> <h2 class="text-xl font-semibold text-center mb-4">添加知识</h2> <form id="uploadForm" enctype="multipart/form-data"> <!-- 知识标题输入 --> <div class="mb-4"> <label for="title" class="block text-sm font-medium text-gray-700">知识标题</label> <input type="text" id="title" name="title" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" placeholder="输入知识标题" required /> </div> <!-- 上传文件区域 --> <div class="mb-4"> <label for="file" class="block text-sm font-medium text-gray-700">上传文件</label> <div class="mt-2 border-dashed border-2 border-gray-300 p-4 text-center text-gray-500"> <input type="file" id="file" name="file" accept=".pdf,.csv,.txt,.md,.sql,.java" class="hidden" multiple /> <label for="file" class="cursor-pointer"> <div>将文件拖到此处或点击上传</div> <div class="mt-2 text-sm text-gray-400">支持的文件类型:.pdf, .csv, .txt, .md, .sql, .java</div> </label> </div> </div> <!-- 待上传文件列表 --> <div class="mb-4" id="fileList"> <ul class="list-disc pl-5 text-gray-700"></ul> </div> <!-- 提交按钮 --> <div class="flex justify-center"> <button type="submit" class="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700"> 提交 </button> </div> </form> </div> <script> const fileListElement = document.querySelector('#fileList ul'); // 文件选择变更处理 document.getElementById('file').addEventListener('change', function (e) { const files = Array.from(e.target.files); fileListElement.innerHTML = ''; // 清空列表 files.forEach((file, index) => { const listItem = document.createElement('li'); listItem.className = 'flex justify-between items-center'; listItem.innerHTML = ` <span>${file.name}</span> <button type="button" class="text-red-500 hover:text-red-700" onclick="removeFile(${index})">删除</button> `; fileListElement.appendChild(listItem); }); }); // 移除文件 function removeFile(index) { const input = document.getElementById('file'); let files = Array.from(input.files); files.splice(index, 1); // 创建一个新的DataTransfer对象 const dataTransfer = new DataTransfer(); files.forEach(file => dataTransfer.items.add(file)); // 更新文件输入对象的文件列表 input.files = dataTransfer.files; // 更新文件列表UI const fileListItems = fileListElement.children; fileListItems[index].remove(); } // 提交事件处理 document.getElementById('uploadForm').addEventListener('submit', function (e) { e.preventDefault(); const loadingOverlay = document.getElementById('loadingOverlay'); const input = document.getElementById('file'); const files = Array.from(input.files); if (files.length === 0) { alert('请先选择一个文件'); return; } // 显示加载状态 loadingOverlay.classList.remove('hidden'); const formData = new FormData(); formData.append('ragTag', document.getElementById('title').value); files.forEach(file => formData.append('file', file)); axios.post('http://localhost:8090/api/v1/rag/file/upload', formData) .then(response => { if (response.data.code === '0000') { // 成功提示并关闭窗口 setTimeout(() => { alert('上传成功,窗口即将关闭'); window.close(); }, 500); } else { throw new Error(response.data.info || '上传失败'); } }) .catch(error => { alert(error.message); }) .finally(() => { // 隐藏加载状态 loadingOverlay.classList.add('hidden'); // 清空表单(无论成功与否) input.value = ''; document.getElementById('title').value = ''; fileListElement.innerHTML = ''; }); }); </script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/upload.html
HTML
unknown
6,434
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Chat</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-100 h-screen"> <div class="container mx-auto max-w-3xl h-screen flex flex-col"> <!-- 消息容器 --> <div id="messageContainer" class="flex-1 overflow-y-auto p-4 space-y-4 bg-white rounded-lg shadow-lg"> <!-- 消息历史将在此动态生成 --> </div> <!-- 输入区域 --> <div class="p-4 bg-white rounded-lg shadow-lg mt-4"> <div class="flex space-x-2"> <input type="text" id="messageInput" placeholder="输入消息..." class="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" onkeypress="handleKeyPress(event)" > <button onclick="sendMessage()" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors" > 发送 </button> </div> </div> </div> <script> // 添加消息到容器 function addMessage(content, isUser = false) { const container = document.getElementById('messageContainer'); const messageDiv = document.createElement('div'); messageDiv.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`; messageDiv.innerHTML = ` <div class="max-w-[80%] p-3 rounded-lg ${ isUser ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800' }"> ${content} </div> `; container.appendChild(messageDiv); container.scrollTop = container.scrollHeight; // 滚动到底部 } // 发送消息 async function sendMessage() { const input = document.getElementById('messageInput'); const message = input.value.trim(); if (!message) return; // 清空输入框 input.value = ''; // 添加用户消息 addMessage(message, true); // 添加初始AI消息占位 addMessage('<span class="animate-pulse">▍</span>'); // 构建API URL const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=deepseek-r1:1.5b&message=${encodeURIComponent(message)}`; // 使用EventSource接收流式响应 const eventSource = new EventSource(apiUrl); let buffer = ''; eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data); const content = data.result?.output?.content || ''; const finishReason = data.result?.metadata?.finishReason; if (content) { buffer += content; updateLastMessage(buffer + '<span class="animate-pulse">▍</span>'); } if (finishReason === 'STOP') { eventSource.close(); updateLastMessage(buffer); // 移除加载动画 } } catch (error) { console.error('解析错误:', error); } }; eventSource.onerror = (error) => { console.error('EventSource错误:', error); eventSource.close(); }; } // 更新最后一条消息 function updateLastMessage(content) { const container = document.getElementById('messageContainer'); const lastMessage = container.lastChild.querySelector('div'); lastMessage.innerHTML = content; container.scrollTop = container.scrollHeight; } // 回车发送 function handleKeyPress(event) { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); sendMessage(); } } </script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/第4节:ai-case-04.html
HTML
unknown
4,288
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Chat Interface</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-50"> <div class="flex h-screen"> <!-- Sidebar --> <div id="sidebar" class="w-64 bg-white border-r border-gray-200 flex flex-col"> <div class="p-4"> <button id="newChatBtn" class="w-full flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" /> </svg> 新聊天 </button> </div> <div id="chatList" class="flex-1 overflow-y-auto p-2 space-y-2"></div> </div> <!-- Main Content --> <div class="flex-1 flex flex-col"> <!-- Top Bar --> <div class="bg-white border-b border-gray-200 p-4 flex items-center gap-4"> <select id="modelSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs"> <option value="deepseek-r1:1.5b">deepseek-r1</option> </select> <select id="promptSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs text-gray-400"> <option>选择一个提示词</option> </select> </div> <!-- Chat Area --> <div id="chatArea" class="flex-1 overflow-y-auto p-4 space-y-4"></div> <!-- Input Area --> <div class="bg-white border-t border-gray-200 p-4"> <div class="max-w-4xl mx-auto flex flex-col gap-4"> <textarea id="messageInput" rows="3" class="w-full p-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="输入一条消息..."></textarea> <div class="flex justify-between items-center"> <div class="flex items-center gap-2"> <button class="p-2 hover:bg-gray-100 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M4 5a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V7a2 2 0 00-2-2h-1.586a1 1 0 01-.707-.293l-1.121-1.121A2 2 0 0011.172 3H8.828a2 2 0 00-1.414.586L6.293 4.707A1 1 0 015.586 5H4zm6 9a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd" /> </svg> </button> <button class="p-2 hover:bg-gray-100 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clip-rule="evenodd" /> </svg> </button> </div> <button id="sendBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"> 发送 </button> </div> </div> </div> </div> </div> <script> // Chat management let chats = []; let currentChatId = null; // Initialize chat interface document.addEventListener('DOMContentLoaded', () => { // New chat button handler document.getElementById('newChatBtn').addEventListener('click', createNewChat); // Send message button handler document.getElementById('sendBtn').addEventListener('click', sendMessage); // Create initial chat createNewChat(); }); function createNewChat() { const chatId = Date.now().toString(); const chat = { id: chatId, name: `新对话 ${chats.length + 1}`, messages: [] }; chats.push(chat); currentChatId = chatId; // Add to sidebar const chatList = document.getElementById('chatList'); const chatElement = createChatListItem(chat); chatList.appendChild(chatElement); // Clear chat area document.getElementById('chatArea').innerHTML = ''; document.getElementById('messageInput').value = ''; } function createChatListItem(chat) { const div = document.createElement('div'); div.className = 'flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg cursor-pointer group'; div.innerHTML = ` <span class="flex-1">${chat.name}</span> <div class="hidden group-hover:flex items-center gap-2"> <button onclick="renameChatPrompt('${chat.id}')" class="p-1 hover:bg-gray-200 rounded"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"> <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" /> </svg> </button> <button onclick="deleteChat('${chat.id}')" class="p-1 hover:bg-gray-200 rounded"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" /> </svg> </button> </div> `; div.addEventListener('click', (e) => { if (!e.target.closest('button')) { selectChat(chat.id); } }); return div; } function selectChat(chatId) { currentChatId = chatId; const chat = chats.find(c => c.id === chatId); // Update chat area const chatArea = document.getElementById('chatArea'); chatArea.innerHTML = ''; chat.messages.forEach(msg => { appendMessage(msg.role, msg.content); }); } function renameChatPrompt(chatId) { const chat = chats.find(c => c.id === chatId); const newName = prompt('请输入新的对话名称:', chat.name); if (newName) { chat.name = newName; updateChatList(); } } function deleteChat(chatId) { if (confirm('确定要删除这个对话吗?')) { chats = chats.filter(c => c.id !== chatId); updateChatList(); if (currentChatId === chatId) { if (chats.length > 0) { selectChat(chats[0].id); } else { createNewChat(); } } } } function updateChatList() { const chatList = document.getElementById('chatList'); chatList.innerHTML = ''; chats.forEach(chat => { chatList.appendChild(createChatListItem(chat)); }); } function appendMessage(role, content) { const chatArea = document.getElementById('chatArea'); const messageDiv = document.createElement('div'); messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`; const bubble = document.createElement('div'); bubble.className = `max-w-[80%] p-3 rounded-lg ${ role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-800' }`; bubble.textContent = content; messageDiv.appendChild(bubble); chatArea.appendChild(messageDiv); chatArea.scrollTop = chatArea.scrollHeight; } async function sendMessage() { const input = document.getElementById('messageInput'); const message = input.value.trim(); if (!message) return; // Clear input input.value = ''; // Add user message appendMessage('user', message); // Get current chat const chat = chats.find(c => c.id === currentChatId); chat.messages.push({ role: 'user', content: message }); // Create API URL with parameters const model = document.getElementById('modelSelect').value; const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=${encodeURIComponent(model)}&message=${encodeURIComponent(message)}`; try { // Create temporary div for assistant's response const assistantMessage = document.createElement('div'); assistantMessage.className = 'flex justify-start'; const bubble = document.createElement('div'); bubble.className = 'max-w-[80%] p-3 rounded-lg bg-gray-100 text-gray-800'; assistantMessage.appendChild(bubble); document.getElementById('chatArea').appendChild(assistantMessage); // Set up EventSource const eventSource = new EventSource(apiUrl); let fullResponse = ''; eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data); const content = data.result.output.content; const finishReason = data.result.metadata.finishReason; if (content) { fullResponse += content; bubble.textContent = fullResponse; document.getElementById('chatArea').scrollTop = document.getElementById('chatArea').scrollHeight; } if (finishReason === 'STOP') { eventSource.close(); chat.messages.push({ role: 'assistant', content: fullResponse }); } } catch (error) { console.error('Error parsing message:', error); } }; eventSource.onerror = (error) => { console.error('EventSource failed:', error); eventSource.close(); }; } catch (error) { console.error('Error sending message:', error); } } </script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/第7节:ai-case-01.html
HTML
unknown
11,283
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>知识库上传</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-100 min-h-screen p-8"> <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-md p-6"> <h1 class="text-2xl font-bold text-gray-800 mb-6">知识库上传</h1> <!-- 错误提示 --> <div id="error" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded-lg"></div> <!-- 上传表单 --> <form id="uploadForm" class="space-y-4"> <!-- 知识库名称 --> <div> <label class="block text-sm font-medium text-gray-700 mb-1">知识库名称</label> <input type="text" id="ragTag" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="请输入知识库名称" required> </div> <!-- 文件上传区域 --> <div> <label class="block text-sm font-medium text-gray-700 mb-1">选择文件</label> <div class="flex items-center justify-center w-full"> <label class="flex flex-col w-full border-2 border-dashed rounded-lg hover:border-gray-400 transition-colors h-32"> <div class="flex flex-col items-center justify-center pt-5 h-full"> <svg class="w-8 h-8 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/> </svg> <span class="text-sm text-gray-500">点击选择文件或拖拽到此区域</span> <span class="text-xs text-gray-400">支持格式:md, txt, sql</span> </div> <input type="file" id="fileInput" class="hidden" multiple accept=".md,.txt,.sql"> </label> </div> <!-- 文件列表 --> <div id="fileList" class="mt-2 space-y-1"></div> </div> <!-- 上传按钮 --> <button type="submit" class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center"> <svg id="spinner" class="hidden w-4 h-4 mr-2 animate-spin" viewBox="0 0 24 24"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/> <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/> </svg> 开始上传 </button> </form> </div> <script> const form = document.getElementById('uploadForm'); const fileInput = document.getElementById('fileInput'); const fileList = document.getElementById('fileList'); const errorDiv = document.getElementById('error'); const spinner = document.getElementById('spinner'); // 显示文件列表 fileInput.addEventListener('change', () => { fileList.innerHTML = ''; Array.from(fileInput.files).forEach(file => { const div = document.createElement('div'); div.className = 'text-sm text-gray-600 flex justify-between items-center'; div.innerHTML = ` <span>${file.name}</span> <span class="text-gray-400">${(file.size / 1024).toFixed(2)}KB</span> `; fileList.appendChild(div); }); }); // 提交表单 form.addEventListener('submit', async (e) => { e.preventDefault(); const ragTag = document.getElementById('ragTag').value.trim(); const files = fileInput.files; // 验证输入 if (!ragTag) { showError('请输入知识库名称'); return; } if (files.length === 0) { showError('请选择至少一个文件'); return; } // 验证文件类型 const allowedTypes = ['text/markdown', 'text/plain', 'application/sql']; const invalidFiles = Array.from(files).filter(file => !allowedTypes.includes(file.type) ); if (invalidFiles.length > 0) { showError(`无效文件类型:${invalidFiles.map(f => f.name).join(', ')}`); return; } // 开始上传 try { toggleLoading(true); const formData = new FormData(); formData.append('ragTag', ragTag); Array.from(files).forEach(file => { formData.append('file', file); }); const response = await fetch('http://localhost:8090/api/v1/rag/file/upload', { method: 'POST', body: formData }); const result = await response.json(); if (result.code === '0000') { alert('上传成功!'); form.reset(); fileList.innerHTML = ''; } else { showError(result.info || '上传失败'); } } catch (err) { showError('网络错误,请稍后重试'); } finally { toggleLoading(false); } }); function showError(message) { errorDiv.textContent = message; errorDiv.classList.remove('hidden'); setTimeout(() => errorDiv.classList.add('hidden'), 3000); } function toggleLoading(isLoading) { spinner.classList.toggle('hidden', !isLoading); form.querySelector('button').disabled = isLoading; } </script> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/第7节:ai-case-02.html
HTML
unknown
6,417
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Chat Interface</title> <script src="https://cdn.tailwindcss.com"></script> <script> // Simple utility to handle sending messages and receiving data from the server. async function sendMessage(chatId, message) { const chatBox = document.getElementById(chatId); const inputField = document.getElementById("user-input"); // Append user's message to the chat chatBox.innerHTML += `<div class="p-2 mb-2 bg-gray-200 rounded-md text-left">${message}</div>`; inputField.value = ''; // Clear input field const apiUrl = `/api/v1/ollama/generate_stream?model=deepseek-r1:1.5b&message=${encodeURIComponent(message)}`; const eventSource = new EventSource(apiUrl); eventSource.onmessage = function (event) { const response = JSON.parse(event.data); const content = response[0]?.result?.output?.content; const finishReason = response[0]?.result?.metadata?.finishReason; if (content) { chatBox.innerHTML += `<div class="p-2 mb-2 bg-gray-100 rounded-md text-right">${content}</div>`; } if (finishReason === "STOP") { eventSource.close(); } }; } // Create new chat function createNewChat() { const chatList = document.getElementById('chat-list'); const chatId = 'chat-' + Date.now(); const newChat = document.createElement('div'); newChat.className = 'chat-item p-2 hover:bg-gray-200 cursor-pointer'; newChat.innerHTML = `<span class="text-sm">Chat ${chatList.children.length + 1}</span>`; newChat.setAttribute('data-chat-id', chatId); newChat.onclick = function () { selectChat(chatId); }; chatList.appendChild(newChat); } // Select chat function selectChat(chatId) { const chats = document.querySelectorAll('.chat-item'); chats.forEach(chat => chat.classList.remove('bg-gray-300')); const selectedChat = document.querySelector(`[data-chat-id="${chatId}"]`); selectedChat.classList.add('bg-gray-300'); // Display the chat box const chatBox = document.getElementById('chat-box'); chatBox.innerHTML = `<div id="${chatId}" class="p-4 overflow-y-auto h-96 bg-gray-50 rounded-md"></div>`; } // Handle send button click or Enter key press function handleSend() { const message = document.getElementById("user-input").value.trim(); if (message) { const activeChat = document.querySelector('.chat-item.bg-gray-300'); if (activeChat) { const chatId = activeChat.getAttribute('data-chat-id'); sendMessage(chatId, message); } } } // Handle Enter key press for sending a message document.getElementById('user-input').addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); handleSend(); } }); </script> </head> <body class="bg-gray-100 h-screen flex flex-col"> <!-- Top Bar --> <div class="flex items-center justify-between bg-white p-4 shadow-md"> <div class="flex items-center space-x-2"> <button onclick="createNewChat()" class="px-4 py-2 bg-blue-500 text-white rounded-md">新聊天</button> </div> <div class="flex space-x-4"> <select class="p-2 border rounded-md"> <option>deepseek-r1</option> </select> <span class="text-green-500">Ollama正在运行 🦙</span> </div> </div> <div class="flex flex-1"> <!-- Left Sidebar (Chat List) --> <div class="w-1/4 p-4 overflow-y-auto bg-white shadow-md"> <div id="chat-list"> <!-- Chat items will appear here --> </div> </div> <!-- Chat Area --> <div class="flex-1 p-6 flex flex-col space-y-4"> <div id="chat-box" class="bg-gray-100 p-4 rounded-md h-full overflow-y-auto"> <!-- Messages will appear here --> </div> <!-- Message Input Section --> <div class="flex space-x-2 items-center"> <input id="user-input" type="text" placeholder="输入一条消息..." class="flex-1 p-2 border rounded-md focus:outline-none"> <button onclick="handleSend()" class="px-4 py-2 bg-blue-500 text-white rounded-md">提交</button> </div> </div> </div> </body> </html>
2301_79945976/mcp-project
docs/dev-ops/nginx/html/第7节:ai-case-03.html
HTML
unknown
4,815
/* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_OpenHarmony_SA_2023_0101 { meta: date = "2023-02-13" openharmony_sa = "OpenHarmony-SA-2023-0101" cve = "CVE-2023-0035" file = "libsoftbus_client.z.so" strings: $fix = "write InterfaceToken failed!" condition: $fix and console.log("OpenHarmony-SA-2023-0101 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/01/OpenHarmony-SA-2023-0101/TestCaseRule-OpenHarmony-SA-2023-0101.yara
YARA
unknown
1,012
/* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_OpenHarmony_SA_2023_0102 { meta: date = "2023-02-17" openharmony_sa = "OpenHarmony-SA-2023-0102" cve = "CVE-2023-0036" file = "libinputmethod_service.z.so" strings: /* .text:00045E0E LDRB.W R3, [SP,#0x68+var_34] .text:00045E12 ADD R0, PC ; .text:00045E14 LDR R2, [SP,#0x68+var_30] */ $fix = {9D F8 34 30 78 44 0E 9A} condition: $fix and console.log("OpenHarmony-SA-2023-0102 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/01/OpenHarmony-SA-2023-0102/TestCaseRule-OpenHarmony-SA-2023-0102.yara
YARA
unknown
1,207
/* * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_OpenHarmony_SA_2023_0201 { meta: date = "2023-02" openharmony_sa = "OpenHarmony-SA-2023-0201" cve = "CVE-2023-0083" severity = "low" file = "libace_engine_declarative_ark.z.so" //受影响于OpenHarmony-v3.1-Release到OpenHarmony-v3.1.5-Release strings: $fix = "The number of argument is less than 1, or the argument is not array." //更新后字符串 condition: (elf.machine == elf.EM_ARM) and $fix and console.log("OpenHarmony-SA-2023-0201 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/02/OpenHarmony-SA-2023-0201/TestCaseRule-OpenHarmony-SA-2023-0201.yara
YARA
unknown
1,197
/* * Copyright (c) 2024 Beijing University Of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2022_4450 { meta: date = "2023-1-15" file = "/system/lib/libhukssdk.z.so" openharmony_sa = "" strings: $original_pattern = {08 46 DF 22 7C 44 21 46 82 F0 8A ED 01 98 21 46 DF 22 00 68 82 F0 84 ED} $new_pattern = { 08 46 31 46 DF 22 82 F0 92 E8 00 20 31 46 20 60 DF 22 02 9C 20 68 82 F0 8A E8 } condition: ((not $original_pattern) and $new_pattern) and console.log("CVE_2022_4450 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/03/CVE-2022-4450/TestCaseInfo-CVE-2022-4450.yara
YARA
unknown
1,137
/* * Copyright (c) 2024 BUPT. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_CVE_2023_23914 { meta: date="2023-03" openharmony_sa="" cve="CVE-2023-23914" affected_files="libhttp.z.so" path ="rk3568/lib.unstripped/communication/netstack/libhttp.z.so" strings: $fix = "Reject response due to more than %u content encodings" condition: $fix and console.log("CVE-2023-23914 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/03/CVE-2023-23914/TestCaseRule-CVE-2023-23914.yara
YARA
unknown
989
/* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_OpenHarmony_SA_2023_0301 { meta: date = "2023-03-08" openharmony_sa = "OpenHarmony-SA-2023-0301" cve = "CVE-2023-24465" severity = "medium" file = "libwifi_scan_ability.z.so" func = "WifiScanStub::OnScanByParams" strings: $features = "run OnScanByParams code %{public}u, datasize %{public}zu" nocase wide ascii /* 3.1.4 vul code .text:0000B0D0 01 46 MOV R1, R0 .text:0000B0D2 20 46 MOV R0, R4 */ $vul = {01 46 ?? 46} /* 3.1.4 with patch .text:0000B0DA 7D 44 ADD R5, PC ; "" .text:0000B0DC 08 BF IT EQ .text:0000B0DE 29 46 MOVEQ R1, R5 */ $fix = {7? 44 08 BF ?? 46} condition: (elf.machine == elf.EM_ARM) and $features and ((not $vul) or $fix) and console.log("OpenHarmony-SA-2023-0301 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/03/OpenHarmony-SA-2023-0301/TestCaseRule-OpenHarmony-SA-2023-0301.yara
YARA
unknown
1,828
/* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_OpenHarmony_SA_2023_0302 { meta: date = "2023-03-10" openharmony_sa = "OpenHarmony-SA-2023-0302" file = "libappexecfwk_core.z.so" path = "rk3568/appexecfwk/bundle_framework/libappexecfwk_core.z.so" strings: $fix = "ERR_APPEXECFWK_PARSE_PROFILE_PROP_SIZE_CHECK_ERROR" condition: $fix and console.log("OpenHarmony-SA-2023-0302 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/03/OpenHarmony-SA-2023-0302/TestCaseRule-OpenHarmony-SA-2023-0302.yara
YARA
unknown
1,043
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_OpenHarmony_CVE_2022_30787 { meta: date = "2024-01-15" file = "/system/bin/fsck.ntfs" strings: $fix = "name in inode %lld" condition: $fix and console.log("TestCaseRule-OpenHarmony-CVE-2022-30787 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2023/04/OpenHarmony-CVE-2022-30787/TestCaseRule-OpenHarmony-CVE-2022-30787.yara
YARA
unknown
973
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_2398 { meta: date="2024-11-11" openharmony_sa="" cve="CVE-2024-2398" affected_files="/system/lib/libcurl_shared.z.so" strings: $fix= {F0 B5 ?? B0 ?? 46 D0 F8 ?? ?? ?? 4D ?? 44 60 B1} condition: $fix and console.log("CVE-2024-2398 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/06/CVE-2024-2398/TestCaseRule-CVE-2024-2398.yara
YARA
unknown
1,004
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_2478 { meta: date="2024-11-11" openharmony_sa="" cve="CVE-2024-2478" affected_files="/system/lib/libwpa_sys.z.so"//in 4.1.x, and "/system/lib/libwpa.z.so" in 4.0.x strings: $fixstring= "EAP-PEAP: Require Phase 2 authentication for initial connection" condition: $fixstring and console.log("CVE-2024-2478 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/06/CVE-2024-2478/TestCaseRule-CVE-2024-2478.yara
YARA
unknown
1,077
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_26883 { meta: date="2024-12-05" openharmony_sa="" cve="CVE-2024-26883" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix_4_0_x = {89 35 01 D0 29 85 4C B9 3F 0D 55 6B 03 FE FF 54 14 00 00 14} $fix_4_1_x = {1F 01 09 6B 69 00 00 54 D4 00 80 92 EA FF FF 17} condition: ($fix_4_0_x or $fix_4_1_x) and console.log("CVE-2024-26883 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/07/CVE-2024-26883/TestCaseRule-CVE-2024-26883.yara
YARA
unknown
1,124
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_26884 { meta: date="2024-12-05" openharmony_sa="" cve="CVE-2024-26884" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {1F 01 09 6B 48 03 00 54 E8 03 08 2A} condition: $fix and console.log("CVE-2024-26884 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/07/CVE-2024-26884/TestCaseRule-CVE-2024-26884.yara
YARA
unknown
1,006
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule TestCaseRule_CVE_2024_27004 { meta: date = "2024-12-23" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {08 20 80 D2 49 04 80 52 A8 D5 FB F2 ?? 16 01 ?? 00 80 ?? 91} condition: $fix and console.log("CVE-2024-27004 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/07/CVE-2024-27004/TestCaseRule-CVE-2024-27004.yara
YARA
unknown
1,021
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_27038 { meta: date="2024-05-01" openharmony_sa="" cve="CVE_2024_27038" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $vul = {1f 04 40 b1 48 00 00 54 00 00 40 f9} $fix = {1f 04 40 b1 68 00 00 54 48 00 00 54 00 00 40 f9} condition: ((not $vul) or $fix) and console.log("CVE_2024_27038 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/07/CVE-2024-27038/CVE-2024-27038.yara
YARA
unknown
1,081
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2023_52739 { meta: date="2025-06-30" openharmony_sa="" cve="CVE_2023_52739" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $vul = {6a 16 42 f9 4a 21 00 91 15 00 00 14} $fix = {68 1a 42 f9 17 05 00 f9 1b 00 00 14} condition: ((not $vul) or $fix) and console.log("CVE_2024_52739 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2023-52739/TestCaseRule-CVE-2023-52739.yara
YARA
unknown
1,069
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_52781 { meta: date="2024-05-21" openharmony_sa="" cve="CVE_2023_52781" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $vul = {6a 16 42 f9 4a 21 00 91 15 00 00 14} $fix = {68 1a 42 f9 17 05 00 f9 1b 00 00 14} condition: ((not $vul) or $fix) and console.log("CVE_2024_27038 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2023-52781/CVE-2023-52781.yara
YARA
unknown
1,069
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_52835 { meta: data="2024-12-17" openharmony_sa="" cve="CVE-2024-52835" file="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $b_version = {C8 7E 7D 93 08 05 00 D1 1F 05 40 F1} $b_version2 = {08 FD 4C D3 08 11 C0 DA 1F D5 00 71} condition: $b_version and $b_version2 and console.log("CVE-2023-52835 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2023-52835/TestCaseRule-CVE-2023-52835.yara
YARA
unknown
1,075
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2023_52868 { meta: date = "2024-12-27" file = "" strings: $fix = {FA 03 16 AA ?2 6F 00 ?0 42 ?? ?? 91 81 02 80 52 43 87 44 B8 E0 03 1A AA ?? B? E4 97} condition: $fix and console.log("TestCaseRule_CVE_2023_52868 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2023-52868/TestCaseRule-CVE-2023-52868.yara
YARA
unknown
1,007
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_26733 { meta: date="2024-12-23" openharmony_sa="" cve="CVE-2024-26733" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {61 62 03 91 1F 39 00 71 02 31 89 1A} condition: $fix and console.log("CVE-2024-26733 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-26733/TestCaseRule-CVE-2024-26733.yara
YARA
unknown
1,006
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_26934 { meta: date="2024-12-05" openharmony_sa="" cve="CVE-2024-26934" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {?? E0 FF 97 E0 03 14 AA ?? ?? DB 97} condition: $fix and console.log("CVE-2024-26934 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-26934/TestCaseRule-CVE-2024-26934.yara
YARA
unknown
1,006
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_27399 { meta: date = "2024-05-23" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" openharmony_sa="" cve="CVE_2024_27399" strings: $vul = {75 02 40 F9 ?? 05 10 37 } $fix = {75 02 40 F9 ?? 05 10 37 D5 04 00 B4} condition: ((not $vul) or $fix) and console.log("CVE_2024_27399 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-27399/TestCaseRule-CVE-2024-27399.yara
YARA
unknown
1,098
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_28182 { meta: date="2024-11-15" openharmony_sa="" cve="CVE-2024-28182" affected_files="/system/lib/platformsdk/libnghttp2_shared.z.so" strings: $fixstring = "Too many CONTINUATION frames following a HEADER frame" condition: $fixstring and console.log("CVE-2024-28182 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-28182/TestCaseRule-CVE-2024-28182.yara
YARA
unknown
1,069
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_35789 { meta: date = "20240508" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {0? 1D 00 94} $unfix = {A4 1D 00 94} /* 4.1.3 版本特殊判断 */ $s = {B4 34 00 94} condition: $fix and ( not $unfix or $s ) and console.log("CVE-2024-35789 pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-35789/CVE-2024-35789.yara
YARA
unknown
1,055
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestcaseRule_OpenHarmony_CVE_2024_35822 { meta: date = "2024-05-17" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = "USB gadget: queue request to disabled ep 0x%x (%s)\n" condition: $fix and console.log("OpenHarmony-CVE-2024-35822 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-35822/TestcaseRule-OpenHarmony-CVE-2024-35822.yara
YARA
unknown
1,027
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_OpenHarmony_CVE_2024_35969 { meta: date="2024-06-20" files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {C0 82 00 91 08 FC DF 88 08 02 00 34} condition: $fix and console.log("CVE-2024-35969 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-35969/TestCaseRule-OpenHarmony-CVE-2024-35969.yara
YARA
unknown
975
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" import "elf" rule CVE_2024_36008 { meta: date="2024-12-18" openharmony_sa="" cve="CVE-2024-36008" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix= {C6 06 00 B4 F3 03 00 AA A0 02 80 12 4B 0C 1C 12 7F 81 03 71} condition: $fix and console.log("CVE-2024-36008 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36008/TestCaseRule-CVE-2024-36008.yara
YARA
unknown
1,041
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_36899 { meta: date="2024-12-06" openharmony_sa="" cve="CVE-2024-36939" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {?? ?? E3 97 60 32 52 F9} condition: $fix and console.log("CVE-2024-36899 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36899/TestCaseRule-CVE-2024-36899.yara
YARA
unknown
993
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_36901 { meta: date="2024-12-16" openharmony_sa="" cve="CVE-2024-36901" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {CB B0 9B 52 A8 83 1F F8 48 2C 40 F9 08 F9 7F 92 09 01 40 F9 0A 5D 40 F9 4B 58 01 79 48 08 40 F9 49 08 00 F9 EA 05 00 B4 4B A9 41 B9 8B 04 00 35 F5 03 01 AA 6A 72 40 79 4A 02 10 37} condition: $fix and console.log("CVE-2024-36901 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36901/TestCaseRule-CVE-2024-36901.yara
YARA
unknown
1,149
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_36904 { meta: date = "20240508" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {B5 FD FF 35} condition: $fix and console.log("CVE-2024-36904 pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36904/CVE-2024-36904.yara
YARA
unknown
940
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule CVE_2024_36939 { meta: date="2024-12-06" openharmony_sa="" cve="CVE-2024-36939" affected_files="/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = {?? ?? 37 94 80 00 00 B4 E0 03 13 AA ?? D5 FF 97 04 00 00 14 E0 03 13 AA ?? D5 FF 97 60 01 80 12} condition: $fix and console.log("CVE-2024-36939 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36939/TestCaseRule-CVE-2024-36939.yara
YARA
unknown
1,065
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_36940 { meta: date="2024-12-10" file="" strings: $fix={60 2A 40 F9 01 A4 00 ?0 21 ?? ?? 91 E2 03 14 2A ?? ?? 0A 94 E7 FF FF 17} $nofix={68 0A 40 F9 E0 03 13 AA 01 05 40 F9 02 11 40 B9 10 00 00 94 E0 03 13 AA} condition: $fix and not $nofix and console.log("TestCaseRule_CVE-2024-36940 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36940/TestCaseRule-CVE-2024-36940.yara
YARA
unknown
1,057
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_36941 { meta: data = "2024-12-07" openharmony_sa = "" cve = "CVE-2024-36941" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix_version = {A9 02 00 B4 77 56 14 9B} condition: // 匹配 5.0 版本的机器码并输出信息 $fix_version and console.log("CVE-2024-36941 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-36941/TestCaseRule-CVE-2024-36941.yara
YARA
unknown
1,104
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_CVE_2024_4603 { meta: date="2024-11-14" file="" strings: $fix={70 B5 05 46 80 68 0C 46 00 28 1C BF E9 68 00 29 02 D1 72 25 19 26 15 E0} condition: $fix and console.log("TestCaseRule_CVE_2024_4603 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/08/CVE-2024-4603/TestCaseRule-CVE-2024-4603.yara
YARA
unknown
955
/* * Copyright (c) 2024 Beijing University of Posts and Telecommunications. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import "console" rule TestCaseRule_OpenHarmony_CVE_2024_25739 { meta: date = "2024-02-12" file = "/dev/block/platform/fe310000.sdhci/by-name/boot_linux" strings: $fix = "LEB size too small for a volume record" condition: $fix and console.log("OpenHarmony-CVE-2024-25739 testcase pass") }
2301_80000730/security
vulntest/SSTSTestcases/2024/09/CVE-2024-25739/TestCaseRule-OpenHarmony-CVE-2024-25739.yara
YARA
unknown
1,013