Skip to content

A command-line tool to convert handwritten notes to markdown files

feat: added Claude support

Tejas Raskar7c5a8fa2e6ec
diff --git a/Cargo.lock b/Cargo.lock
index dfd07f1..9f89970 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -820,7 +820,7 @@ dependencies = [
[[package]]
name = "notedmd"
-version = "0.2.1"
+version = "0.2.2"
dependencies = [
"async-trait",
"base64",
diff --git a/Cargo.toml b/Cargo.toml
index 9d5ce5b..0f9cffa 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "notedmd"
-version = "0.2.1"
+version = "0.2.2"
edition = "2024"
description = "A command-line tool to convert handwritten notes into a clean and readable Markdown file."
license = "MIT"
diff --git a/src/claude_client.rs b/src/claude_client.rs
new file mode 100644
index 0000000..3bed973
--- /dev/null
+++ b/src/claude_client.rs
@@ -0,0 +1,134 @@
+use crate::ai_provider::AiProvider;
+use crate::file_utils::FileData;
+use async_trait::async_trait;
+use reqwest::Client;
+use serde::{Deserialize, Serialize};
+
+// Request structs
+
+#[derive(Serialize)]
+struct ClaudeRequest {
+ model: String,
+ max_tokens: u32,
+ messages: Vec<Message>,
+}
+
+#[derive(Serialize)]
+struct Message {
+ role: String,
+ content: Vec<Content>,
+}
+
+#[derive(Serialize)]
+struct Content {
+ #[serde(rename = "type")]
+ content_type: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ text: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ source: Option<Source>,
+}
+
+#[derive(Serialize)]
+struct Source {
+ #[serde(rename = "type")]
+ source_type: String,
+ media_type: String,
+ data: String,
+}
+
+// Response structs
+
+#[derive(Deserialize, Debug)]
+pub struct ClaudeResponse {
+ pub content: Vec<ContentResponse>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct ContentResponse {
+ pub text: String,
+}
+
+// Client
+pub struct ClaudeClient {
+ client: Client,
+ api_key: String,
+ model: String,
+ prompt: Option<String>,
+}
+
+impl ClaudeClient {
+ pub fn new(api_key: String, model: String, prompt: Option<String>) -> Self {
+ Self {
+ client: Client::new(),
+ api_key,
+ model,
+ prompt,
+ }
+ }
+}
+
+#[async_trait]
+impl AiProvider for ClaudeClient {
+ async fn send_request(
+ &self,
+ file_data: FileData,
+ ) -> Result<String, Box<dyn std::error::Error>> {
+ let url = "https://api.anthropic.com/v1/messages".to_string();
+
+ let prompt = if let Some(custom_prompt) = &self.prompt {
+ custom_prompt.clone()
+ } else {
+ "Take the handwritten notes from this image and convert them into a clean, well-structured Markdown file. Pay attention to headings, lists, and any other formatting. Resemble the hierarchy. Use latex for mathematical equations. For latex use the $$ syntax instead of ```latex. Do not skip anything from the original text. The output should be suitable for use in Obsidian. Just give me the markdown, do not include other text in the response apart from the markdown file. No explanation on how the changes where made is needed".to_string()
+ };
+
+ let request_body = ClaudeRequest {
+ model: self.model.clone(),
+ max_tokens: 4096,
+ messages: vec![Message {
+ role: "user".to_string(),
+ content: vec![
+ Content {
+ content_type: "image".to_string(),
+ text: None,
+ source: Some(Source {
+ source_type: "base64".to_string(),
+ media_type: file_data.mime_type,
+ data: file_data.encoded_data,
+ }),
+ },
+ Content {
+ content_type: "text".to_string(),
+ text: Some(prompt),
+ source: None,
+ },
+ ],
+ }],
+ };
+
+ let response = self
+ .client
+ .post(&url)
+ .header("x-api-key", &self.api_key)
+ .header("anthropic-version", "2023-06-01")
+ .json(&request_body)
+ .send()
+ .await?
+ .json::<ClaudeResponse>()
+ .await?;
+
+ let response_text = response.content.first();
+ let markdown_text = if let Some(part) = response_text {
+ &part.text
+ } else {
+ println!("{}", "Could not find text in Claude response.");
+ std::process::exit(1);
+ };
+
+ let cleaned_markdown = markdown_text
+ .trim_start_matches("```markdown")
+ .trim_end_matches("```");
+
+ Ok(cleaned_markdown.to_string())
+ }
+}
diff --git a/src/cli.rs b/src/cli.rs
index 0e32188..edfb62a 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -41,6 +41,10 @@ pub enum Commands {
#[arg(long, help = "Set your Gemini API key for future use")]
set_api_key: Option<String>,
+ /// Set your Claude API key
+ #[arg(long, help = "Set your Claude API key for future use")]
+ set_claude_api_key: Option<String>,
+
/// Show config file location
#[arg(long, help = "Display the path to your configuration file")]
show_path: bool,
diff --git a/src/config.rs b/src/config.rs
index 30f0943..6e75c20 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -8,6 +8,13 @@ pub struct Config {
pub active_provider: Option<String>,
pub gemini: Option<GeminiConfig>,
pub ollama: Option<OllamaConfig>,
+ pub claude: Option<ClaudeConfig>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Default)]
+pub struct ClaudeConfig {
+ pub api_key: String,
+ pub model: String,
}
#[derive(Serialize, Deserialize, Debug, Default)]
diff --git a/src/main.rs b/src/main.rs
index 060e07b..1a6a611 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,5 @@
mod ai_provider;
+mod claude_client;
mod cli;
mod config;
mod file_utils;
@@ -8,9 +9,10 @@ mod ui;
use ai_provider::AiProvider;
use clap::Parser;
+use claude_client::ClaudeClient;
use cli::{Cli, Commands};
use colored::*;
-use config::{Config, GeminiConfig, OllamaConfig};
+use config::{ClaudeConfig, Config, GeminiConfig, OllamaConfig};
use dialoguer::Input;
use dialoguer::Select;
use dialoguer::{Password, theme::ColorfulTheme};
@@ -112,6 +114,7 @@ async fn main() {
Commands::Config {
set_api_key,
show_path,
+ set_claude_api_key,
} => {
if show_path {
if let Some(config_path) = config::get_config_path() {
@@ -138,7 +141,28 @@ async fn main() {
}
}
- if !show_path && set_api_key.is_none() {
+ if let Some(ref key) = set_claude_api_key {
+ let mut config = Config::load();
+ config.active_provider = Some("claude".to_string());
+ let model = Input::with_theme(&ColorfulTheme::default())
+ .with_prompt("Claude model")
+ .default("claude-3-opus-20240229".to_string())
+ .interact_text()
+ .unwrap();
+
+ config.claude = Some(config::ClaudeConfig {
+ api_key: key.to_string(),
+ model: model,
+ });
+
+ if let Err(e) = config.save() {
+ println!("Error while saving config: {}", e)
+ } else {
+ println!("Config saved successfully.");
+ }
+ }
+
+ if !show_path && set_api_key.is_none() && set_claude_api_key.is_none() {
if let Some(config_path) = get_config_path() {
if config_path.exists() {
let config = Config::load();
@@ -152,6 +176,7 @@ async fn main() {
let providers = vec![
"Gemini API (Cloud-based, requires API key)",
+ "Claude API (Cloud-based, requires API key)",
"Ollama (Local, requires Ollama to be set up)",
];
let selected_provider = Select::with_theme(&ColorfulTheme::default())
@@ -192,6 +217,42 @@ async fn main() {
};
}
1 => {
+ let mut config = Config::load();
+ let _api_key = match Password::with_theme(&ColorfulTheme::default())
+ .with_prompt("Enter your Claude API key: ")
+ .interact()
+ {
+ Ok(key) => {
+ config.active_provider = Some("claude".to_string());
+ let model = Input::with_theme(&ColorfulTheme::default())
+ .with_prompt("Claude model")
+ .default("claude-3-opus-20240229".to_string())
+ .interact_text()
+ .unwrap();
+
+ config.claude = Some(ClaudeConfig {
+ api_key: key.clone(),
+ model: model,
+ });
+ let _save = match config.save() {
+ Ok(()) => {
+ println!("{}", "Config saved successfully.".green())
+ }
+ Err(e) => eprintln!(
+ "{}:{}",
+ "Error saving the config.".red(),
+ e
+ ),
+ };
+ key
+ }
+ Err(e) => {
+ eprintln!("{}", e);
+ std::process::exit(1);
+ }
+ };
+ }
+ 2 => {
let url = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Ollama server url")
.default("http://localhost:11434".to_string())
@@ -264,6 +325,25 @@ async fn main() {
};
Box::new(OllamaClient::new(url, model, prompt))
}
+ Some("claude") => {
+ let api_key = if let Some(key) = api_key {
+ key
+ } else if let Some(claude_config) = &config.claude {
+ claude_config.api_key.clone()
+ } else {
+ eprintln!("{}", "Claude is not configured properly. Run 'notedmd config' to configure it.".red());
+ std::process::exit(1);
+ };
+
+ let model = if let Some(claude_config) = &config.claude {
+ claude_config.model.clone()
+ } else {
+ eprintln!("{}", "Claude is not configured properly. Run 'notedmd config' to configure it.".red());
+ std::process::exit(1);
+ };
+
+ Box::new(ClaudeClient::new(api_key, model, prompt))
+ }
_ => {
eprintln!(
"{}",