添加项目文件。
This commit is contained in:
parent
60a80ea731
commit
edac14bb49
71
OpenAI.cs
Normal file
71
OpenAI.cs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace OpenAIClient
|
||||||
|
{
|
||||||
|
internal class OpenAI
|
||||||
|
{ // 替换为你的 OpenAI API 密钥
|
||||||
|
private const string OPENAI_API_KEY = "your-openai-api-key-here";
|
||||||
|
// 指定模型(例如 gpt-3.5-turbo 或 gpt-4)
|
||||||
|
private const string MODEL_NAME = "qwen3-30b-a3b";
|
||||||
|
public static async Task<string> GetOpenAIAnswer(string question)
|
||||||
|
{
|
||||||
|
using (var client = new HttpClient())
|
||||||
|
{
|
||||||
|
// 设置 API 地址和请求头
|
||||||
|
client.BaseAddress = new Uri("http://localhost:1234/v1/chat/completions");
|
||||||
|
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {OPENAI_API_KEY}");
|
||||||
|
|
||||||
|
// 构建请求体(JSON 格式)
|
||||||
|
var request = new
|
||||||
|
{
|
||||||
|
model = MODEL_NAME,
|
||||||
|
messages = new[]
|
||||||
|
{
|
||||||
|
new { role = "user", content = question }
|
||||||
|
},
|
||||||
|
temperature = 0.7, // 控制随机性(0-1)
|
||||||
|
max_tokens = 200 // 最大生成长度
|
||||||
|
};
|
||||||
|
|
||||||
|
var jsonRequest = System.Text.Json.JsonSerializer.Serialize(request);
|
||||||
|
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
|
||||||
|
|
||||||
|
// 发送 POST 请求
|
||||||
|
var response = await client.PostAsync("", content);
|
||||||
|
|
||||||
|
// 确保响应成功
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
// 解析 JSON 响应
|
||||||
|
var jsonResponse = await response.Content.ReadAsStringAsync();
|
||||||
|
var result = System.Text.Json.JsonSerializer.Deserialize<OpenAIResponse>(jsonResponse);
|
||||||
|
|
||||||
|
// 提取模型回答
|
||||||
|
return result?.Choices[0].Message.Content.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义响应类结构(根据实际 API 响应调整)
|
||||||
|
private class OpenAIResponse
|
||||||
|
{
|
||||||
|
public Choice[] Choices { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Choice
|
||||||
|
{
|
||||||
|
public Message Message { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Message
|
||||||
|
{
|
||||||
|
public string Content { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
25
OpenAIClient.sln
Normal file
25
OpenAIClient.sln
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
# Visual Studio Version 17
|
||||||
|
VisualStudioVersion = 17.14.36017.23 d17.14
|
||||||
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAIClient", "OpenAIClient\OpenAIClient.csproj", "{9074BE39-1E09-4878-8DCC-977FBDCC2D70}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{9074BE39-1E09-4878-8DCC-977FBDCC2D70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{9074BE39-1E09-4878-8DCC-977FBDCC2D70}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{9074BE39-1E09-4878-8DCC-977FBDCC2D70}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{9074BE39-1E09-4878-8DCC-977FBDCC2D70}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
|
HideSolutionNode = FALSE
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
|
SolutionGuid = {E1588CC4-630A-4910-931D-CE42D6F32E9C}
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
71
OpenAIClient/OpenAI.cs
Normal file
71
OpenAIClient/OpenAI.cs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace OpenAIClient
|
||||||
|
{
|
||||||
|
internal class OpenAI
|
||||||
|
{
|
||||||
|
public static string CallOpenAISync(string apiKey, string model, string prompt)
|
||||||
|
{
|
||||||
|
var request = (HttpWebRequest)WebRequest.Create("http://localhost:1234/v1/chat/completions");
|
||||||
|
request.Method = "POST";
|
||||||
|
request.Headers["Authorization"] = "Bearer " + apiKey;
|
||||||
|
request.ContentType = "application/json";
|
||||||
|
|
||||||
|
// 1️⃣ 封装 JSON 请求对象
|
||||||
|
var message = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{ "role", "user" },
|
||||||
|
{ "content", prompt }
|
||||||
|
};
|
||||||
|
|
||||||
|
var requestBody = new
|
||||||
|
{
|
||||||
|
model = model,
|
||||||
|
messages = new[] { message }
|
||||||
|
};
|
||||||
|
|
||||||
|
string jsonData = JsonConvert.SerializeObject(requestBody);
|
||||||
|
|
||||||
|
// 2️⃣ 写入请求体
|
||||||
|
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
|
||||||
|
{
|
||||||
|
streamWriter.Write(jsonData);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 3️⃣ 获取响应
|
||||||
|
var response = (HttpWebResponse)request.GetResponse();
|
||||||
|
using (var streamReader = new StreamReader(response.GetResponseStream()))
|
||||||
|
{
|
||||||
|
string result = streamReader.ReadToEnd();
|
||||||
|
|
||||||
|
// 4️⃣ 解析 JSON 响应,提取文本
|
||||||
|
JObject jsonResponse = JObject.Parse(result);
|
||||||
|
|
||||||
|
string content = jsonResponse["choices"]?[0]?["message"]?["content"]?.ToString();
|
||||||
|
return content ?? "(未找到回答内容)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (WebException ex)
|
||||||
|
{
|
||||||
|
using (var stream = ex.Response.GetResponseStream())
|
||||||
|
using (var reader = new StreamReader(stream))
|
||||||
|
{
|
||||||
|
string error = reader.ReadToEnd();
|
||||||
|
Console.WriteLine("错误: " + error);
|
||||||
|
}
|
||||||
|
return "(请求失败)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
16
OpenAIClient/OpenAIClient.csproj
Normal file
16
OpenAIClient/OpenAIClient.csproj
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
80
OpenAIClient/Program.cs
Normal file
80
OpenAIClient/Program.cs
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace OpenAIClient
|
||||||
|
{
|
||||||
|
internal class Program
|
||||||
|
{
|
||||||
|
private const string ApiKey = "KEY";
|
||||||
|
private const string Model = "qwen3-30b-a3b";
|
||||||
|
private static readonly Regex CommentRegex =
|
||||||
|
new(@"(\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
private static string Translate(string raw)
|
||||||
|
{
|
||||||
|
// 去掉注释定界符
|
||||||
|
var content = raw.StartsWith("/*")
|
||||||
|
? raw[2..^2]
|
||||||
|
: raw[2..];
|
||||||
|
|
||||||
|
content = content.Trim();
|
||||||
|
if (string.IsNullOrEmpty(content))
|
||||||
|
return raw; // 空注释直接返回
|
||||||
|
|
||||||
|
string zh = OpenAI.CallOpenAISync(
|
||||||
|
ApiKey,
|
||||||
|
Model,
|
||||||
|
$"你是一位专业的翻译员,将下面的内容翻译成中文,不允许输出除了翻译内容以外的内容,需要翻译的内容:{content}\n/no_think"
|
||||||
|
).TrimStart('\n').Trim();
|
||||||
|
Console.WriteLine(zh);
|
||||||
|
if (raw.StartsWith("/*"))
|
||||||
|
return $"/* {zh} */";
|
||||||
|
|
||||||
|
// 处理包含换行的 // 注释
|
||||||
|
var lines = zh.Split(new[] { "\r\n", "\n", "\r" },
|
||||||
|
StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
return "// " + string.Join(Environment.NewLine + "// ", lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Run(string srcPath, string dstPath)
|
||||||
|
{
|
||||||
|
var source = File.ReadAllText(srcPath);
|
||||||
|
|
||||||
|
// 简单缓存,避免重复翻译相同内容
|
||||||
|
var cache = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
string result = CommentRegex.Replace(source, match =>
|
||||||
|
{
|
||||||
|
var key = match.Value;
|
||||||
|
if (!cache.TryGetValue(key, out var translated))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
translated = Translate(key);
|
||||||
|
cache[key] = translated;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 失败时保留原文并在行尾加标记
|
||||||
|
translated = key + " /* 翻译失败: " + ex.Message + " */";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return translated;
|
||||||
|
});
|
||||||
|
|
||||||
|
File.WriteAllText(dstPath, result, Encoding.UTF8);
|
||||||
|
Console.WriteLine($"翻译完成: {dstPath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void Main(string[] args)
|
||||||
|
{
|
||||||
|
Run(
|
||||||
|
@"D:\Projects\M1\PML\hv\IA32\ia32.h",
|
||||||
|
@"D:\Projects\M1\PML\hv\IA32\ia32.zh.h");
|
||||||
|
Console.WriteLine("OK");
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user